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

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.

Related

CefSharp Wpf , Session Cookie for multiple instances

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;
}

StackExchange Redis ConnectionString

What is the full format of the ConnectionString used in StackExchange.Redis?
I have searched but cannot find documentation for it.
If in doubt, use the ConfigurationOptions class (which has properties etc) and ToString() it when you are ready to obtain the configuration-string. However, I suspect you are looking for this
Update. The 'correct' answer links to crazy documentation.
There doesn't seem to be a connect string...
var client = redis.createClient(9000); // Open a port on localhost
var client = redis.createClient('/tmp/redis.sock'); // Open a unix socket
var client = redis.createClient(9000, 'example.com');
This, and options are documented on the README.

Is there any way to trace\log the sql using Dapper?

Is there a way to dump the generated sql to the Debug log or something? I'm using it in a winforms solution so the mini-profiler idea won't work for me.
I got the same issue and implemented some code after doing some search but having no ready-to-use stuff. There is a package on nuget MiniProfiler.Integrations I would like to share.
Update V2: it supports to work with other database servers, for MySQL it requires to have MiniProfiler.Integrations.MySql
Below are steps to work with SQL Server:
1.Instantiate the connection
var factory = new SqlServerDbConnectionFactory(_connectionString);
using (var connection = ProfiledDbConnectionFactory.New(factory, CustomDbProfiler.Current))
{
// your code
}
2.After all works done, write all commands to a file if you want
File.WriteAllText("SqlScripts.txt", CustomDbProfiler.Current.ProfilerContext.BuildCommands());
Dapper does not currently have an instrumentation point here. This is perhaps due, as you note, to the fact that we (as the authors) use mini-profiler to handle this. However, if it helps, the core parts of mini-profiler are actually designed to be architecture neutral, and I know of other people using it with winforms, wpf, wcf, etc - which would give you access to the profiling / tracing connection wrapper.
In theory, it would be perfectly possible to add some blanket capture-point, but I'm concerned about two things:
(primarily) security: since dapper doesn't have a concept of a context, it would be really really easy for malign code to attach quietly to sniff all sql traffic that goes via dapper; I really don't like the sound of that (this isn't an issue with the "decorator" approach, as the caller owns the connection, hence the logging context)
(secondary) performance: but... in truth, it is hard to say that a simple delegate-check (which would presumably be null in most cases) would have much impact
Of course, the other thing you could do is: steal the connection wrapper code from mini-profiler, and replace the profiler-context stuff with just: Debug.WriteLine etc.
You should consider using SQL profiler located in the menu of SQL Management Studio → Extras → SQL Server Profiler (no Dapper extensions needed - may work with other RDBMS when they got a SQL profiler tool too).
Then, start a new session.
You'll get something like this for example (you see all parameters and the complete SQL string):
exec sp_executesql N'SELECT * FROM Updates WHERE CAST(Product_ID as VARCHAR(50)) = #appId AND (Blocked IS NULL OR Blocked = 0)
AND (Beta IS NULL OR Beta = 0 OR #includeBeta = 1) AND (LangCode IS NULL OR LangCode IN (SELECT * FROM STRING_SPLIT(#langCode, '','')))',N'#appId nvarchar(4000),#includeBeta bit,#langCode nvarchar(4000)',#appId=N'fea5b0a7-1da6-4394-b8c8-05e7cb979161',#includeBeta=0,#langCode=N'de'
Try Dapper.Logging.
You can get it from NuGet. The way it works is you pass your code that creates your actual database connection into a factory that creates wrapped connections. Whenever a wrapped connection is opened or closed or you run a query against it, it will be logged. You can configure the logging message templates and other settings like whether SQL parameters are saved. Elapsed time is also saved.
In my opinion, the only downside is that the documentation is sparse, but I think that's just because it's a new project (as of this writing). I had to dig through the repo for a bit to understand it and to get it configured to my liking, but now it's working great.
From the documentation:
The tool consists of simple decorators for the DbConnection and
DbCommand which track the execution time and write messages to the
ILogger<T>. The ILogger<T> can be handled by any logging framework
(e.g. Serilog). The result is similar to the default EF Core logging
behavior.
The lib declares a helper method for registering the
IDbConnectionFactory in the IoC container. The connection factory is
SQL Provider agnostic. That's why you have to specify the real factory
method:
services.AddDbConnectionFactory(prv => new SqlConnection(conStr));
After registration, the IDbConnectionFactory can be injected into
classes that need a SQL connection.
private readonly IDbConnectionFactory _connectionFactory;
public GetProductsHandler(IDbConnectionFactory connectionFactory)
{
_connectionFactory = connectionFactory;
}
The IDbConnectionFactory.CreateConnection will return a decorated
version that logs the activity.
using (DbConnection db = _connectionFactory.CreateConnection())
{
//...
}
This is not exhaustive and is essentially a bit of hack, but if you have your SQL and you want to initialize your parameters, it's useful for basic debugging. Set up this extension method, then call it anywhere as desired.
public static class DapperExtensions
{
public static string ArgsAsSql(this DynamicParameters args)
{
if (args is null) throw new ArgumentNullException(nameof(args));
var sb = new StringBuilder();
foreach (var name in args.ParameterNames)
{
var pValue = args.Get<dynamic>(name);
var type = pValue.GetType();
if (type == typeof(DateTime))
sb.AppendFormat("DECLARE #{0} DATETIME ='{1}'\n", name, pValue.ToString("yyyy-MM-dd HH:mm:ss.fff"));
else if (type == typeof(bool))
sb.AppendFormat("DECLARE #{0} BIT = {1}\n", name, (bool)pValue ? 1 : 0);
else if (type == typeof(int))
sb.AppendFormat("DECLARE #{0} INT = {1}\n", name, pValue);
else if (type == typeof(List<int>))
sb.AppendFormat("-- REPLACE #{0} IN SQL: ({1})\n", name, string.Join(",", (List<int>)pValue));
else
sb.AppendFormat("DECLARE #{0} NVARCHAR(MAX) = '{1}'\n", name, pValue.ToString());
}
return sb.ToString();
}
}
You can then just use this in the immediate or watch windows to grab the SQL.
Just to add an update here since I see this question still get's quite a few hits - these days I use either Glimpse (seems it's dead now) or Stackify Prefix which both have sql command trace capabilities.
It's not exactly what I was looking for when I asked the original question but solve the same problem.

4004 RIA Service error - Remote database

After finaly be abble to setup my silverlight app with RIA, I call the following code to get my list of citie objects from my remote database:
_context = context;
var load =_context.Load(_context.GetCitiesQuery());
_cities = new ObservableCollection<City>(load.Entities);
I get no errors, but also no data. After using fiddler I do see that I get a responce looking like this:
#GetCitiesResponsehttp://tempuri.org/#GetCitiesResult aDomainServices i)http://www.w3.org/2001/XMLSchema-instance^
TotalCount�^
RootResults b4http://schemas.datacontract.org/2004/07/Gymsport.Web_City_CityID�_CityName�Oelegem_PostCode�� _City_CityID�_CityName�Ranst_PostCode�� _City_CityID�_CityName�Emblem_PostCode�� _City_CityID�_CityName�Ranst_PostCode��
Which is a lot of rubbish, but between the lines you can read it returns a couple of cities.
But for some reason my silverlight app doens't pick up on those.
Any suggestions on how to look for a solution?
Thanks in advance.
Grtz
T
Solution:
I had to work with the EntityList object to convert the result of the query to an observable collection. Thank you Firefox ErrorConsole :)

Internet Explorer 9 RC stops my WinForms WebBrowser control to work in editing mode

Using the IHtmlDocument2.designMode property set to On to switch a WebBrowser control hosted on a Windows Forms form to editing mode suddenly stopped working after installing Microsoft Internet Explorer 9 RC.
Question:
Any chance to fix this?
I already tried to tweak with doctype or with the EmulateIE7 meta tag but without success.
(An example would be this project)
Update 2011-02-21:
As Eric Lawrence suggested, I adjusted the "Zeta" example to set the document text before setting the edit mode.
Unfortunately I did not manage to switch to design mode, either.
Update 2011-02-24:
Parts of the discussion also take place in Eric's blog.
Update 2011-02-26:
What I currently eperience is that the behaviour seems to be different for HTTP URLs and for content that was added via WebBrowser.DocumentText.
First tests seems to prove this assumption.
I'm now going to build a solution around this assumption and post updates and a proof-of-concept here.
Update 2011-02-26 (2):
I've now built a proof-of-concept with a built-in web server which I believe is also working well with IE 9. If anyone would like to download and test whether it is working and give me a short feedback, I can clean up and release the source code for this.
Update 2011-02-26 (3):
No feedback yet, I still updated the HTML Edit Control article and demo over at the Code Project.
Update 2011-03-16:
Since Internet Explorer 9 was released yesterday, we updated our major products to use the idea with the integrated web server as described in the HTML Edit Control article.
After nearly a month of testing, I think it works quite well.
If you do experience any issues in the future with this approach, please post your comments here and I can investigate and fix.
I had a similar problem and got around it by adding the following line to the DocumentCompleted event:
((HTMLBody)_doc.body).contentEditable = "true";
We just need an empty editable control. I did however step through debugger and add value to the control's InnerHtml and it displayed it fine, and I could edit it.
Small update, we were able to get the control editable using this line also:
browserControl.browser.Document.Body.SetAttribute("contentEditable", "true");
This allows us to avoid referencing mshtml, (don't have to include Microsoft.mshtml.dll)
This lets us avoid increasing our installation size by 8 megs.
What's your exact code?
If I set the following code:
private void cbDesign_CheckedChanged(object sender, EventArgs e){
var instance =
Microsoft.VisualBasic.CompilerServices.NewLateBinding.LateGet(
wbView.ActiveXInstance,
null,
#"Document",
new object[0],
null,
null, null );
var objArray1 = new object[] { cbDesign.Checked ? #"On" : #"Off" };
Microsoft.VisualBasic.CompilerServices.NewLateBinding.LateSetComplex(
instance,
null,
#"designMode",
objArray1,
null,
null,
false,
true );
The IE9 Web Browser instance enters designMode without any problems. If you change the "Zeta" example to not set the document text after entering design mode, it also works fine.
Just want to add that I am also unable to enter designmode (using a WebBrowser control in my case). This was not an issue in the beta. Definitely new with the RC.
Another Code Project user suggested to use the following code:
First, add event DocumentCompleted:
private void SetupEvents()
{
webBrowser1.Navigated += webBrowser1_Navigated;
webBrowser1.GotFocus += webBrowser1_GotFocus;
webBrowser1.DocumentCompleted += this.theBrowser_DocumentCompleted;
}
Then write the function:
private void theBrowser_DocumentCompleted(
object sender,
WebBrowserDocumentCompletedEventArgs e)
{
webBrowser1.Document.Write(webBrowser1.DocumentText);
doc.designMode = "On";
}
Although I did not test this, I want to document it here for completeness.
It's fixed if the property is set after the document is loaded
private void DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
IHTMLDocument2 Doc = Document.DomDocument as IHTMLDocument2;
Doc.designMode = #"On";
}
Yesterday, Internet Explorer 9 RTM finally was released.
I did some more tiny adjustments to my control, but basically the idea with the intergrated, small web server seems to work rather well.
So the solution is in this Code Project article:
Zeta HTML Edit Control
A small wrapper class around the Windows Forms 2.0 WebBrowser control
This was the only solution that worked for me.
I hope it is OK to answer my own question and mark my answer as "answered", too?!?
I was also able to get this to work using the following inside the DocumentCompleted event:
IHTMLDocument2 Doc = browserControl.browser.Document.DomDocument as IHTMLDocument2;
if (Doc != null) Doc.designMode = #"On";
Thanks everyone!
I use HTML Editor Control, I solved this problem adding the DocumentComplete event
private void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
(((sender as WebBrowser).Document.DomDocument as IHTMLDocument2).body as HTMLBody).contentEditable = "true";
}

Resources