CefSharp Wpf , Session Cookie for multiple instances - wpf

I am very curious if there is a possibility in CEF Sharp , somehow to isolate each instance of browser from other instances.
I am creating 4 instances of browser. Logging in on of the instances ,
immediately 3 other instances become logged in as well.
Is it possible to achieve somehow in Current version that we got from Nuget ?

As of revision 2040, CEF now adds support for complete isolation of storage and permissions (cache, cookies, localStorage, access grants, etc) on a request context basis. This is also now in CEFSharp.
To make sure that no sessions overlap between multiple instances, simply create a new RequestContextSettings object, set PersistSessionCookies and/or PersistUserPreferences to false, and assign it to your browser while creating a new RequestContext - I am not sure if setting them to false is completely necessary for multiple instances, maybe someone else can give some info on that.
//usually ChromiumWebBrowser setup goes above this
RequestContextSettings requestContextSettings = new RequestContextSettings();
requestContextSettings.PersistSessionCookies = false;
requestContextSettings.PersistUserPreferences = false;
webBrowser.RequestContext = new RequestContext(requestContextSettings);
This had been giving me headaches for a while and this appears to finally solve that issue.

Just use this code, its working for me.
public MainWindow()
{
CefSharp.CefSettings settings = new CefSharp.CefSettings();
settings.CachePath = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData) + #"\CEF";
CefSharp.Cef.Initialize(settings);
InitializeComponent();
browser = new ChromiumWebBrowser("https://google.com/");
browser.BrowserSettings.ApplicationCache = CefSharp.CefState.Disabled;
}

Related

Create persistent Sqlite db in Windows phone 8

I am trying my hands on Windows phone 8 applications and I am stuck into a weird situation here. I am using sqlite in order to create sqlite db and add values into the database. I am able to create the database and add the values in the database successfully but I am having a weird situation here.
Everytime I close the emulator and start the project again the database gets created again which should not be happening because I created the db the very first time I run the application.
Does anybody know why, and how I can prevent it from recreating the database each time?
public string DB_PATH = Path.Combine(Path.Combine(ApplicationData.Current.LocalFolder.Path, "aa.sqlite"));
private SQLiteConnection dtCon;
public MainPage()
{
InitializeComponent();
CreateDatabase();
dtCon = new SQLiteConnection(DB_PATH);
var tp = dtCon.Query<Contacts>("select * from contacts").ToList();
}
private async void CreateDatabase()
{
bool isDatabaseExisting = false;
//Checking if database already exists
try
{
Windows.Storage.StorageFile storagefile = await Windows.Storage.ApplicationData.Current.LocalFolder.GetFileAsync("aa.sqlite");
isDatabaseExisting = true;
}
catch
{
isDatabaseExisting = false;
}
//if not exists then creating database
if (!isDatabaseExisting)
{
String str = System.IO.Path.Combine(Windows.Storage.ApplicationData.Current.LocalFolder.Path, "sqlite.db");
AddDataToDB(DB_PATH);
}
}
private void AddDataToDB(string str)
{
// Create the database connection.
dtCon = new SQLiteConnection(str);
// Create the table Task, if it doesn't exist.
dtCon.CreateTable<Contacts>();
Contacts oContacts = new Contacts();
oContacts.Name = "dfgdf";
oContacts.Detail = "asdfsf";
dtCon.Insert(oContacts);
}
I'm pretty sure when you close your emulator and restart, you're basically just uninstalling the application. Which is why your files or not there anymore -- as it looks like you're storing your data in isolated storage. I do not know if there is anyway around this.
You can buy a very cheap Windows 8/8.1 Phone and the files will persist until you manually uninstall the test application.
As #Chubosaurus says, closing and re-opening the emulator will remove all the apps. You can generally keep it running as long as you want and keep re-deploying your app to the emulator (although obviously rebooting the host PC will kill it).
You can save and restore the data from your emulator image via the ISETool command. See more here
Try adding Console.WriteLine("True"); and Console.WriteLine("False"); into the expected places after checking isDatabaseExisting to see/understand what the code path really is.

Same functionality as HTTPClient in Codename one

I was wondering how I can achieve something like an HTTPClient.
I tried WebBrowser class but it seems that the execution continues even though the URL specified has not yet loaded.
public void testWebBrowser(){
final WebBrowser b = new WebBrowser(){
#Override
public void onLoad(String url) {
BrowserComponent c = (BrowserComponent)this.getInternal();
JavascriptContext ctx = new JavascriptContext(c);
// I want this Javascript context here
}
};
// just a test URL
b.setURL("http://youtube.com");
// Suppose to get the Javascript context here though it executes without waiting for the whole page to load
}
How can I get the JS Context from within a WebBrowser context? Like a synchronous execution
WebBrowser browser = new WebBrowser();
browser.setURL("someURL");
// wait execution till the whole page in "someURL" loads till it executes the next line
BrowserComponent c = (BrowserComponent)browser.getInternal();
JavascriptContext ctx = new JavascriptContext(c);
If I understand correctly you are trying to create a scraping solution?
That's probably not the ideal approach since this will actually create a web browser which you then need to automate with JavaScript. I would suggest you create a webservice that encapsulates the HttpClient functionality and drive it with ConnectionRequest. This way when the web site changes you can just fix your server in a way seamless to your installed base.

How to display XML-RPC.Net Server instance data in the UI?

We've trying recently to use XML-RPC.Net library on our project.
Both server(.Net Remoting) and client have been made according to the instructions we've found on http://xml-rpc.net/.
The connection has been made, we obtain data from the server and so on.
As the title states, now, we'd like to know how to make our XML-RPC server instance, which is created after the first client call, be able to give feedback to a WPF UI.
What we'd like to accomplish is to register an event on a server property so the call could arrive to the UI thread.
We are open to any suggestions in this regard.
Here is the code that registers the channel on server side:
IDictionary props = new Hashtable();
props["name"] = "SubsetHttpChannel";
props["port"] = 5678;
channel = new System.Runtime.Remoting.Channels.Http.HttpChannel(
props,
null,
new XmlRpcServerFormatterSinkProvider()
);
ChannelServices.RegisterChannel(channel, false);
RemotingConfiguration.RegisterWellKnownServiceType( typeof(SubsetServer), "subsetserver.rem", WellKnownObjectMode.Singleton);
This is the code that shows how we'd like to set the property after Server instance is created on the UI:
Server = new SubsetServer();
Server.Machine.OnChangeState += delegate(State actual, State next, Event pEvent)
{
uiWindowInstance.PostMessage(string.Format("Subset Server: {0} -> {1}", actual.Name, next.Name));
};
Technologies used: VS2012, WPF 4.5 and XML-RPC.NET 2.5.0
Thanks in Advance
Thanks to anyone that took the time to read it and try to answer.
I found a solution that fits me for the moment. I'd like to share it with you in the hope someone could give any hints wheter this is a solution that may generate problems in the future.
After analyzing, I found out that both server instances run in the same process. So I've created a Singleton as a property inside my Server.
I've put whatever I need inside the Singleton, so for the delegate I'd like to use in my question, the code now is:
Server = new SubsetServer();
Server.**singleton**.Machine.OnChangeState += delegate(State actual, State next, Event pEvent)
{
uiWindowInstance.PostMessage(string.Format("Subset Server: {0} -> {1}", actual.Name, next.Name));
};
Hope this helps anyone else.
Please comment if you find any flaws.

Silverlight HttpWebRequest.Create hangs inside async block

I am trying to prototype a Rpc Call to a JBOSS webserver from Silverlight (4). I have written the code and it is working in a console application - so I know that Jboss is responding to the web request. Porting it to silverlight 4, is causing issues:
let uri = new Uri(queryUrl)
// this is the line that hangs
let request : HttpWebRequest = downcast WebRequest.Create(uri)
request.Method <- httpMethod;
request.ContentType <- contentType
It may be a sandbox issue, as my silverlight is being served off of my file system and the Uri is a reference to the localhost - though I am not even getting an exception. Thoughts?
Thx
UPDATE 1
I created a new project and ported my code over and now it is working; something must be unstable w/ regard to the F# Silverlight integration still. Still would appreciate thoughts on debugging the "hanging" web create in the old model...
UPDATE 2
let uri = Uri("http://localhost./portal/main?isSecure=IbongAdarnaNiFranciscoBalagtas")
// this WebRequest.Create works fine
let req : HttpWebRequest = downcast WebRequest.Create(uri)
let Login = async {
let uri = new Uri("http://localhost/portal/main?isSecure=IbongAdarnaNiFranciscoBalagtas")
// code hangs on this WebRequest.Create
let request : HttpWebRequest = downcast WebRequest.Create(uri)
return request
}
Login |> Async.RunSynchronously
I must be missing something; the Async block works fine in the console app - is it not allowed in the Silverlight App?
(Thanks for sending this to fsbugs, to force us to take a hard look.)
The problem is Async.RunSynchronously. When called on the UI thread, this blocks the UI thread. And it turns out that WebRequest.Create() on Silverlight dispatches to the UI thread. So it is a deadlock.
In general, try to avoid Async.RunSynchronously on Silverlight (or on any UI thread). You can use Async.StartImmediate in this example. Alternatively, I think you can call RunSynchronously from any background thread without issues. (I have not tried enough end-to-end Silverlight scenarios myself to offer more advice as yet. You might check out
Game programming in F# (with Silverlight and WPF)
F# and Silverlight
F# async on the client side
for a few short examples.)
(In retrospect, the F# design team thinks that we maybe should not have included Async.RunSynchronously in FSharp.Core for Silverlight; the method potentially violates the spirit of the platform (no blocking calls). It's possible we'll deprecate that method in future Silverlight releases. On the other hand, it still does have valid uses for CPU-intensive parallelism on Silverlight, e.g. running a bunch on (non-IO) code in parallel on background threads.)
Seems like a similar issue here - though no reference to silverlight (in fact it is a "windows service class"):
http://social.msdn.microsoft.com/Forums/en-US/netfxnetcom/thread/10854fc4-2149-41e2-b315-c533586bb65d
I had similar problem. I was making a Silverlight MVVM ViewModel to bind data from web.
Don Syme commented himself:
I’m not a data-binding expert, but I
believe you can’t “hide” the asyncness
of a view model like this for WPF and
Silverlight. I think you would need to
expose Task, Async or an
observable collection. AFAIK the only
way to get Silverlight and WPF to bind
asynchronously to a property is if it
is an observable collection.
Anyway, I installed F# Power Pack to get AsyncReadToEnd.
It didn't solve the case... I added domains to trusted sites but it didn't help... Then I added a MySolution.Web -asp.net-site and clientaccesspolicy.xml. I don't know if those had any effect.
Now, with Async.StartImmediate I got web service call working:
let mutable callresult = ""
//let event = new Event<string>()
//let eventvalue = event.Publish
let internal fetch (url : Uri) trigger =
let req = WebRequest.CreateHttp url
//req.CookieContainer <- new CookieContainer()
let asynccall =
async{
try
let! res = req.AsyncGetResponse()
use stream = res.GetResponseStream()
use reader = new StreamReader(stream)
let! txt = reader.AsyncReadToEnd()
//event.Trigger(txt)
callresult <- txt //I had some processing here...
trigger "" |> ignore
with
| :? System.Exception as ex ->
failwith(ex.ToString()) //just for debug
}
asynccall |> Async.StartImmediate
Now I will need my ViewModel to listen the mutable callresult.
In your case you need also a crossdomain.xml to the server.
The trigger is needed to use the UI-thread:
let trigger _ =
let update _ = x.myViewModelProperty <- callresult
System.Windows.Deployment.Current.Dispatcher.BeginInvoke(new Action(update)) |> ignore
fetch serviceUrl trigger
I think you are hitting the maximum http connections restriction: see Aynchronous web server calls in Silverlight and maximum HTTP connections and http://weblogs.asp.net/mschwarz/archive/2008/07/21/internet-explorer-8-and-maximum-concurrent-connections.aspx

Will Prism OnDemand module loading work in an OOB scenerio?

Should the loading of OnDemand Prism modules work in an OOB scenerio? If so, I cannot seem to make it work. Everything is currently working in browser without any problems. Specifically I:
register my modules in code:
protected override IModuleCatalog GetModuleCatalog() {
var catalog = new ModuleCatalog();
Uri source;
if( Application.Current.IsRunningOutOfBrowser ) {
source = IsolatedStorageSettings.ApplicationSettings[SOURCEURI] as Uri;
}
else {
var src = Application.Current.Host.Source.ToString();
src = src.Substring( 0, src.LastIndexOf( '/' ) + 1 );
source = new Uri( src );
IsolatedStorageSettings.ApplicationSettings[SOURCEURI] = source;
IsolatedStorageSettings.ApplicationSettings.Save();
}
if( source != null ) {
var mod2 = new ModuleInfo { InitializationMode = InitializationMode.OnDemand,
ModuleName = ModuleNames.mod2,
ModuleType = "mod2.Module, mod2.Directory, '1.0.0.0', Culture=neutral, PublicKeyToken=null" ),
Ref = ( new Uri( source, "mod2.xap" )).AbsoluteUri };
catalog.AddModule( mod2 );
}
// per Jeremy Likeness - did not help.
Application.Current.RootVisual = new Grid();
return ( catalog );
}
later request for the module to be loaded is made:
mModuleManager.LoadModule( ModuleNames.mod2 );
and wait for a response to an event published during the initialization of that loaded module.
The module appears to never be loaded, and when the application is running under the debugger there will be a message box that states that the web server returned a 'not found' error. I can take the requesting url for the module and enter it into Firefox and download the module with no problem.
I have not been able to find any reference to this actually being workable, but it seems as though it should. The most I have found on the subject is a blog entry by Jeremy Likeness, which covers loading modules in MEF, but applying his knowledge here did not help.
The server is localhost (I have heard it mentioned that this might cause problems). The server has a clientaccesspolicy.xml file - although I don't expect that is needed.
I am using the client stack and register it during app construction:
WebRequest.RegisterPrefix( Current.Host.Source.GetComponents( UriComponents.SchemeAndServer, UriFormat.UriEscaped ), WebRequestCreator.ClientHttp );
Followup questions:
Can all of the xaps be installed to the client desktop in some manner - or only the main application xap? specify them in appmanifest.xml somehow??
Is it worth it make this work if only the application.xap is installed and the rest of the xaps must be downloaded anyway?
Once I worked on a similar scenario. The trick is having the modules stored in isolated storage and use a module loader that reads from isolated storage when working offline.
This is because otherwise, you can't get download the modules that are in a different .xap file than the Shell.
Thanks,
Damian
It is possible to hook custom module loaders into Prism if you're willing to tweak the Prism source and build it yourself. I was actually able to get this to work pretty easily - in our app, I look on disk first for the module, and if it's not found, I fall back to loading it from the server via a third-party commercial HTTP stack that supports client certificates.
To do this, download the Prism source code, and locate the Microsoft.Practices.Composite.Modularity.XapModuleTypeLoader class. This class uses another Prism class, Microsoft.Practices.Composite.Modularity.FileDownloader, to download the .xap content; but it instantiates it directly, giving you no chance to inject your own or whatever.
So - in XapModuleTypeLoader, I added a static property to set the type of the downloader:
public static Type DownloaderType { get; set; }
Then I modified the CreateDownloader() method to use the type specified above in preference to the default one:
protected virtual IFileDownloader CreateDownloader() {
if (_downloader == null) {
if (DownloaderType == null) {
_downloader = new FileDownloader();
} else {
_downloader = (IFileDownloader)Activator.CreateInstance(DownloaderType);
}
}
return _downloader;
}
When my app starts up, I set the property to my own downloader type:
XapModuleTypeLoader.DownloaderType = typeof(LocalFileDownloader);
Voila - now Prism calls your code to load its modules.
I can send you my LocalFileDownloader class as well as the class it falls back to to load the .xap from the web if you're interested... I suspect though that if you look at Prism's FileDownloader class you'll see that it's simple enough.
With regard to your other questions, the clientaccesspolicy.xml file is probably not needed if the URL the app is installed under is the same one you're talking to, or if you're in elevated trust.
The .xaps can definitely be pre-installed on the client, but it's a bit of work. What we did was write a launcher app that is a standalone .NET 2.0 desktop app. It downloads the main .xap plus certain modules* (checking for updates and downloading only as needed), then uninstalls/reinstalls the app if necessary, then launches the app. The last two are done via sllauncher.exe, which is installed as part of Silverlight. Here's a good intro to that: http://timheuer.com/blog/archive/2010/03/25/using-sllauncher-for-silent-install-silverlight-application.aspx.
Assuming you're running under elevated trust, it should also be possible to pre-fetch the module .xaps from within the SL client, but before they're actually requested due to user action. You'd just need to put them in a folder under My Documents somewhere, and then use the custom module loading approach described above to pull them from there.
*In our case, our main .xap is 2/3 of the application. The rest of our .xaps are small, so we download them on-the-fly, with the exception of some .xaps we created as containers for third-party components. We don't expect to update those very often, so we pre-install them.

Resources