I want to know if there is a way of using C# to get the Current Silverlight Version a user is running when opening a client of an app I'm developing.
It is for logging purposes.
I want to know if they are using Silverlight 3 or 4 on their browsers
var dotNetRuntimeVersion = Deployment.Current.RuntimeVersion;
var silverlightVersion = Environment.Version.ToString();
Supported in: 5, 4, 3
Using C# only I don't know, but what you could do is detect it with javascript and then send an ajax request to a function which lets the server know what version.
http://www.apijunkie.com/APIJunkie/blog/post/2009/04/How-to-programmatically-detect-Silverlight-version.aspx
The script above needs a bit of modifications to work with 4.0 but it should be easy enough.
Environment.Version might differ from plugin version. When I was using Silverlight 4 I managed to find version which had differ in major from plugin version and it seem there was no regularity.
There is way to get Silverlight Plugin version from JS and there is way to add JS to page and invoke it from Silverlight. So with code from here: http://www.visiblox.com/blog/posts/2010/04/29/determining-silverlight-version-installed/ I managed to do it this way:
var pScriptElement = HtmlPage.Document.CreateElement("script");
pScriptElement.SetAttribute("type", "text/javascript");
pScriptElement.SetProperty("text", "function GetSilverlightVersion(){var parts = Array(\"ver-major\", \"ver-minor\", \"ver-build\", \"ver-revision\");var nav = navigator.plugins[\"Silverlight Plug-In\"];var versionStr = \"\";if (nav) {versionStr = nav.description;} else {if(SilverlightIsInstalledOnIE)versionStr = GetSilverlightVersionOnIE();else versionStr = -1;}return versionStr;}function SilverlightIsInstalledOnIE(version){if(version == null)version = \"1.0\";var AgControl = new ActiveXObject(\"AgControl.AgControl\"); if(AgControl == null)return false;elsereturn AgControl.isVersionSupported(version);}function GetSilverlightVersionOnIE(){var currVersion = Array(1,0,0,0);for(var i=0;i<currVersion.length;i++){currVersion[i] = FindSupportedMaxVersionOnIE(currVersion, i,0,10000000);}return GetVersionString(currVersion);}function GetVersionString(versionArr,currVersion,index){if(index == null)index = -1;var versionStr = \"\";for(var i=0;i<versionArr.length;i++){if(i>0)versionStr += \".\";if(i==index)versionStr +=currVersion;elseversionStr += versionArr[i];}return versionStr;}function FindSupportedMaxVersionOnIE(versionArr, index,bottom,top){if(bottom >= top){return bottom;}var currVersion = bottom;var prevVersion = currVersion;var step = 1;while(currVersion<top){if(SilverlightIsInstalledOnIE(GetVersionString(versionArr,currVersion,index))){prevVersion = currVersion;currVersion += step;step *= 2;}elsereturn FindSupportedMaxVersionOnIE(versionArr, index,prevVersion,currVersion-1)}if(SilverlightIsInstalledOnIE(GetVersionString(versionArr,top,index)))return top;elsereturn FindSupportedMaxVersionOnIE(versionArr, index,prevVersion,top-1)}");
HtmlPage.Document.Body.AppendChild(pScriptElement);
var slVer = HtmlPage.Window.Invoke("GetSilverlightVersion", null);
This way I was able to get reliable plugin version on IE and other browsers. I've created my own class for parsing and comparing versions so I can easily check if user is using plugin from before fixes or with known malfunction.
Related
We are trying to extract data from a checkbox using the Form recognizer. We have a custom model where we extract 4 fields. All fields get extracted except one ("has_observations").
We used the analyze tab on fott-2-1.azurewebsites.net and it shows correctly for all the files we are trying to do OCR on.
private static FormField GetField(this RecognizedFormCollection forms, string fieldName)
{
FormField field = null;
foreach (RecognizedForm form in forms)
{
if (form.Fields.ContainsKey(fieldName) && form.Fields[fieldName] != null)
{
field = form.Fields[fieldName];
logger.LogWarning("values is=" + field.ValueData.ToString());
break;
}
}
return field;
}
The field is "Azure.AI.FormRecognizer.Models.FormField" for "has_observations" label everytime and we have no idea how to fix it.
Which version of FormRecognizer SDK are you using? 3.1.1? You maybe calling different version from website vs from SDK.
If you are using 4.0.0-beta.X, by default it calls 2022-01-30-preview version of FormRecognizer APIs (see https://azuresdkdocs.blob.core.windows.net/$web/dotnet/Azure.AI.FormRecognizer/4.0.0-beta.3/index.html), but based on the screenshot you are using 2.1. So, API results maybe different between versions.
A few other troubleshooting options to see exact URLs and responses for http traffic from FormRecognizer SDK:
Logging with the Azure SDK for .NET, I.e. line below starts printing to the console each request/response.
var listener = AzureEventSourceListener.CreateConsoleLogger(EventLevel.Informational);
Some information will be redacted in logs. Changes to ClientOptions below will show more data (see details in Azure SDK diagnostics):
var frOptions = new FormRecognizerClientOptions() { Diagnostics = { IsLoggingContentEnabled = true, LoggedHeaderNames = { "*" }, LoggedQueryParameters = { "*" }}};
var client = new FormRecognizerClient(new Uri(endpoint), credential, frOptions);
I saved a tensorflow.keras model in python and need to use in in C# / Tensorflow.NET 0.15
var net = tf.keras.models.load_model(net_name) does not seem to be implemented
var session = tf.Session.LoadFromSavedModel(net_name);
var graph = sess.graph;
seems to work but I have then a session / graph not a keras model
I would ideally like to call something like net.predict(x), how can I get there from a graph/session ?
Yes, i Did. The best way is to convert you package to the ONNX format. ONNX is a open source format that is supposed to run on any framework (tensorflow, torch...)
In python, add the package onnx and keras2onnx:
import onnx
import keras2onnx
import onnxruntime
net_onnx = keras2onnx.convert_keras(net_keras)
onnx.save_model(net_onnx, onnx_name)
Then in C# .NET, install the nuget Microsoft.ML.
var context = new MLContext();
var session = new InferenceSession(filename);
float[] sample;
int[] dims = new int[] { 1, sample_size};
var tensor = new DenseTensor<float>(sample,dims);
var xs = new List<NamedOnnxValue>()
{
NamedOnnxValue.CreateFromTensor<float>("dense_input", tensor),
};
using (var results = session.Run(xs))
{
// manipulate the results
}
Note that you need to call explicitly the fist layer or the input layer of your network to pass on the sample. best is to give it a nice name in Keras. You can check the name in python by running net_keras.summary()
We were using cefsharp version 57.0 in our application and it was working all fine. But now due to some limitations we need to update cefsharp version to 75.1.143 and suddenly our working code broke. One change was to change LegacyJavascriptBindingEnabled to true and secondly this line is breaking:
browser.RegisterJsObject("objectForCallingServerSideMethods", this);
giving error System.ArgumentException: Registering of .Net framework built in types is not supported, create your own Object and proxy the calls if you need to access a window/Form/Control. Parameter name: value.
It was all working fine. I don't know how to deal with this. Sample code is here which was working before update.
Cef.Initialize(new CefSettings() { IgnoreCertificateErrors = true, PersistSessionCookies = true, CachePath = LocalFolderPath + "/cache" });
CefSharpSettings.ShutdownOnExit = true;
CefSharpSettings.LegacyJavascriptBindingEnabled = true; // added now for version 75.1.143
browser = new ChromiumWebBrowser("url goes here");
browser.DownloadHandler = new DownloadHandler();
browser.Width = 0;
browser.Height = 0;
browser.MenuHandler = new CustomContextHandler();
this.Controls.Add(browser);
browser.LoadingStateChanged += Browser_LoadingStateChanged;
browser.RegisterJsObject("objectForCallingServerSideMethods", this); // this line is throwing exception now. screenshot is attached.
I have sort out its solution. I was passing winform object as 'this' and in version 75.1.143 they have changed the implementation now we cannot use Window/Form/Control. I have created another class named as "BoundObject" and passed its object and it worked as expected.
public class BoundObject
{
// some implementation
// all methods from JS will be catched in this class. Before this (in version 57) we were receiving these methods from JS on windows form.
}
browser.RegisterJsObject("objectForCallingServerSideMethods", new BoundObject());
I work in a research group and I've been tasked with adding in scripting functionality to a data acquisition program. Ideally, I want to have the ability to write scripts while the data acquisition software is running (and save those scripts as files on the go). A command line might also be nice.
I'm not very experienced at all with C#, but I do have quite a bit of coding experience in other language (Objective-C, Python). I saw this link https://blogs.msdn.microsoft.com/cdndevs/2015/12/01/adding-c-scripting-to-your-development-arsenal-part-1/ which details the "Roselyn Scripting Package" but I'm not sure if that's my best option.
Can anybody suggest the easiest way of getting full scripting functionality? (I'm trying to avoid losing months of my life here =p). Links to start at/advice is much appreciated.
Thanks!
You posted an interesting link for me because I just prototyped something like that some weeks ago, but have not implemented yet. My goal is to create a C# "immediate" console on a webpage.
Have some minor issues regarding loading some assemblies programatically and have to reference them explicitly.
Here is the code behind, please later post your solution, I would be interested to know.
This alows to write c# code at runtime and also get a String return.
protected void getImmediateResult_Click(object sender, EventArgs e)
{
//building the code
string source = #"using System;
class MyType{
public static String Evaluate(){
<!expression!>
}}";
string expression = this.txtimmediate.Text;
string finalSource = source.Replace("<!expression!>", expression);
textcodeCheck.Text = finalSource;
var compileUnit = new CodeSnippetCompileUnit(finalSource);
//preparing compilation
CodeDomProvider provider = new Microsoft.CSharp.CSharpCodeProvider();
// Create the optional compiler parameters
//this correctly references the application but no System.Web etc
string[] refArray = new string[2];
UriBuilder uri = new UriBuilder(Assembly.GetExecutingAssembly().CodeBase);
refArray[0] = uri.Path;
//this works
refArray[1] = "System.Web" + ".dll";
////NOT WORKING for non microsoft assemblies
//var allRefs = Assembly.GetExecutingAssembly().GetReferencedAssemblies();
//string[] refArray = new string[allRefs.Length + 1];
//int i = 1;
//foreach (AssemblyName refer in allRefs)
//{
// refArray[i] = refer.Name + ".dll";
// i++;
//}
var compilerParameters = new CompilerParameters(refArray);
CompilerResults compilerResults = provider.CompileAssemblyFromDom(compilerParameters, compileUnit);
if (compilerResults.Errors.Count > 0)
{
//1st error
this.txtResult.Text = compilerResults.Errors[0].ErrorText;
return;
}
//running it
Type type = compilerResults.CompiledAssembly.GetType("MyType");
MethodInfo method = type.GetMethod("Evaluate");
String result = (String)method.Invoke(null, null);
this.txtResult.Text = result;
}
If you're willing to use IronPython, you can execute scripts directly in C#:
using IronPython.Hosting;
using Microsoft.Scripting.Hosting;
private static void doPython()
{
ScriptEngine engine = Python.CreateEngine();
engine.ExecuteFile(#"test.py");
}
Get IronPython here.
I'm not sure if this has even been done before, but what I am trying to accomplish can't be explained in any great detail, but basically, what I am trying to do is Process PHP scripts from within my C# Windows Forms Application.
I have already created a HTTP server, which works just fine. But now I need to be able to process PHP scripts aswell. We're working on a new privatised language over here, purely for learning and fun.
(Just a little background, not completely related):
We are now able to create a webpage like so:
Using System.Core,
System.Http,
System.Graphics and System.IO;
protected void -> Webpage(object homepage)
{
// Set Webpage properties.
homepage.Name = "Home";
homepage.Size = new Size(960[px], 100[%]);
homepage.Alignment = new AlignmentType.Vertical;
homepage.Alignment = new AlignmentType.Horizontal;
// This is a comment.
// Create objects to be rendered on the page.
Text text = new Text();
FormElements formElements = new FormElements();
private void -> Webpage.Load(object homepage)
{
text.Text = "Please enter your name below:";
text.Style = new Style(
Alignment = new AlignmentType.Horizontal,
Alignment = new AlignmentType.ManualAlignment(15[Y, px]),
Font = new Font(
Font.Family("Arial"),
Font.Size = new Size(9[pt], LineHeight(4[px])),
Font.Color = new Color.FromArgb(15, 15, 15))
);
formElements.CreateElements(TextField["textField"], SubmitButton["submitButton"], Form["form"]);
textField.Name = "name";
submitButton.Name = "submit";
form.Encapsulate(name, submit);
form.Alignment = new AlignmentType.RelativeTo(text.Bottom);
Elements[] elements = new Elements[]
{
text, form;
};
homepage.Display.Element.ElementCollection(elements);
}
private void -> Webpage.FormSubmission(object form)
{
form.Element(name).OmitSpecialCharacters();
if(form.Value is not Empty)
{
text.Text = "Hello, " + form.Element(name).Value;
}
}
}
The above sample demonstrates the ability to create a whole webpage, style it, and process form input in a nice, clean way. However, we've come to a complete dead end (trying to support PHP) and we do not wish to delve too far into server-side languages (lack of experience in that area is the main reason), so we would like to be able to "support" PHP scripts from within our WinForms app.
Anyone know of any way to process PHP scripts from within a C# winforms app?
Here is a simple http server that supports PHP:
MiniHttpd: an HTTP web server library
And here is Phalanger - The PHP Language Compiler for the .NET Framework
Use an HttpWebRequest, and request the url to the PHP page like you would to run the PHP page in your browser.
See here for more info: http://msdn.microsoft.com/en-us/library/system.net.httpwebrequest.aspx