I have below java code , I need to convert these in C#, Kindly help me ..
public class Configuration {
private ConfigContentHandler confHandler;
public Configuration() {
}
public boolean parseConfigFile() throws Exception {
boolean bReturn = true;
SAXParser parser = SAXParserFactory.newInstance().newSAXParser();
System.out.println("*** Start parsing");
try {
confHandler = new ConfigContentHandler(100);
// Configuration file must be located in main jar file folder
// Set the full Prosper file name
String sConfigFile = "configuration.xml";
// Get abstract (system independent) filename
File fFile = new File(sConfigFile);
if (!fFile.exists()) {
System.out.println("Could not find configuration file " + sConfigFile + ", trying input parameters.");
bReturn = false;
} else if (!fFile.canRead()) {
System.out.println("Could not read configuration file " + sConfigFile + ", trying input parameters.");
bReturn = false;
} else {
parser.parse(fFile, confHandler);
}
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Input error.");
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("*** End parsing");
return bReturn;
}
Thanks
C# native XML parser XmlReader doesn't support SAX and is forward-only. You may take a look at this article presenting some specific points about it. You could simulate a SAX parser using XmlReader. If it doesn't suit your needs you could also use XDocument which is a different API for working with XML files in .NET. So to conclude there's no push XML parser built into .NET framework so you might need to use a third party library or COM Interop to MSXML to achieve this if you really need an event driven parser.
I used SAX for .NET in two projects successfully in the past.
http://saxdotnet.sourceforge.net/
Related
I'm trying to communicate with some test equipment from C# over SCPI. I managed to communicate with one device that is connected through TCP/IP by using this code example.
However, my other devices are connected through USB and I haven't find how to communicate with them over USB.
BTW, I found this question, and the link from the answer to the IVI-COM programming examples in C# document, but I couldn't apply the code samples (e.g. in section 5.4) because all of the IVI and VISA COM libraries I found (e.g. VisaComLib 5.5) has only interfaces and enums in it, and no concrete class that I can use...
If you install the visa driver from either NationalInstruments or Keysight, they do implement classes:
The one from NI:
FormattedIO488Class
ResourceManagerClass
VisaConflictTableManagerClass
To get a connection, you only need 1 and 2
As soon as you try to embed the interoptypes, you need to remove the 'Class' suffix, as described here
Here comes a sample snippet from Keysight (Application Note: 5989-6338EN)
Ivi.Visa.Interop.ResourceManager rm = new Ivi.Visa.Interop.ResourceManager();
Ivi.Visa.Interop.FormattedIO488 ioobj = new Ivi.Visa.Interop.FormattedIO488();
try
{
object[] idnItems;
ioobj.IO = (Ivi.Visa.Interop.IMessage)rm.Open("GPIB2::10::INSTR",
Ivi.Visa.Interop.AccessMode.NO_LOCK, 0, "");
ioobj.WriteString("*IDN ?", true);
idnItems = (object[])ioobj.ReadList(Ivi.Visa.Interop.IEEEASCIIType.ASCIIType_Any, ",");
foreach(object idnItem in idnItems)
{
System.Console.Out.WriteLine("IDN Item of type " + idnItem.GetType().ToString());
System.Console.Out.WriteLine("\tValue of item is " + idnItem.ToString());
}
}
catch(Exception e)
{
System.Console.Out.WriteLine("An error occurred: " + e.Message);
}
finally
{
try { ioobj.IO.Close(); }
catch { }
try
{
System.Runtime.InteropServices.Marshal.ReleaseComObject(ioobj);
}
catch { }
try
{
System.Runtime.InteropServices.Marshal.ReleaseComObject(rm);
}
catch { }
}
I'm using National Instruments VISA.
Add a reference to NationalInstruments.VisaNS and NationalInstruments.Common to your project.
Create a MessageBasedSession, see the following code:
string resourceName = "USB0::0x0957::0x0118::US56070667::INSTR"; // See NI MAX for resource name
var visa = new NationalInstruments.VisaNS.MessageBasedSession(resourceName);
visa.Write("*IDN?"); // write to instrument
string res = visa.ReadString(); // read from instrument
See as well https://stackoverflow.com/a/49388678/7556646.
I am attempting to open an Imanage document, in MS Word, within a temporary test application (for debugging) to later copy over into an ActiveX control project. The error that is popping up is:
Exception thrown at 0x7618851A (msvcrt.dll) in w3wp.exe: 0xC0000005: Access >violation reading location 0x09801000.
If there is a handler for this exception, the program may be safely continued.
The error occurs when running the cmd.Execute line and I am unsure as to why I am getting the error.
using IManage;
using IMANEXTLib;
using System;
namespace WebApplication3
{
public partial class WebForm2 : System.Web.UI.Page
{
IManDatabase imanagedatabase;
IManDMS myDMS = new ManDMSClass();
protected void Page_Load(object sender, EventArgs e)
{
openImanageDoc("docNumber", "versionNumber", "server", "database", ReadOnly);
}
public void imanageLogin(string server, string database)
{
try
{
IManSession session = myDMS.Sessions.Add(server);
IManWorkArea oWorkArea = session.WorkArea;
session.TrustedLogin();
foreach (IManDatabase dbase in session.Databases)
{
if (dbase.Name == database)
{
imanagedatabase = dbase;
}
}
}
catch (Exception ex)
{
throw ex;
}
}
public void openImanageDoc(string docNo, string versionNo, string server, string database, bool isReadOnly = true)
{
IManDocument doc;
try
{
imanageLogin(server, database);
int iDocNo = int.Parse(docNo);
int iVersion = int.Parse(versionNo);
doc = imanagedatabase.GetDocument(iDocNo, iVersion);
openNRTDocument(ref doc, isReadOnly);
imanagedatabase.Session.Logout();
myDMS.Close();
}
catch (Exception Ex)
{
imanagedatabase.Session.Logout();
throw Ex;
}
finally
{
imanagedatabase = null;
myDMS = null;
}
}
public void openNRTDocument(ref IManDocument nrtDocument, Boolean isReadonly)
{
OpenCmd cmd = new OpenCmd();
ContextItems objContextItems = new ContextItems();
objContextItems.Add("NRTDMS", myDMS);
objContextItems.Add("SelectedNRTDocuments", new[] { (NRTDocument)nrtDocument.LatestVersion });
objContextItems.Add("IManExt.OpenCmd.Integration", false);
objContextItems.Add("IManExt.OpenCmd.NoCmdUI", true);
cmd.Initialize(objContextItems);
cmd.Update();
cmd.Execute();
}
}
}
Due to the nature of the error, I am presuming it is a configuration issue rather than a code error although I could be completely wrong as I am very new to programming.
I have found out that w3wp.exe is an IIS worker process created by the app pool but other than that I have no idea what the numeric code represents. Any help or advice is greatly appreciated.
The error is being raised by the OpenCmd instance because it is most likely trying to access resources such as local registry settings. It's not possible to do that in a web application, unless you host your code in a proprietary technology like ActiveX (which is specific to Internet Explorer)
Actually, it is not appropriate for you to use OpenCmd here. Those type of commands (iManage "ICommand" implementations) are intended to be used in regular Windows applications that have either the iManage FileSite or DeskSite client installed. These commands are all part of the so-called Extensibility COM libraries (iManExt.dll, iManExt2.dll, etc) and should not be used in web applications, or at least used with caution as they may inappropriately attempt to access the registry, as you've discovered, or perhaps even display input Win32 dialogs.
For a web app you should instead just limit yourself to the low-level iManage COM library (IManage.dll). This is in fact what iManage themselves do with their own WorkSite Web application
Probably what you should do is replace your openNRTDocument method with something like this:
// create a temporary file on your web server..
var filePath = Path.GetTempFileName();
// fetch a copy of the iManage document and save to the temporary file location
doc.GetCopy(filePath, imGetCopyOptions.imNativeFormat);
In an MVC web application you would then just return a FileContentResult, something like this:
// read entire document as a byte array
var docContent = File.ReadAllBytes(filePath);
// delete temporary copy of file
File.Delete(filePath);
// return byte stream to web client
return File(stream, MediaTypeNames.Application.Octet, fileName);
In a Web Forms application you could do something like this:
// set content disposition as appropriate - here example is for Word DOCX files
Response.ContentType = "application/vnd.openxmlformats-officedocument.wordprocessingml.document";
// write file to HTTP content output stream
Response.WriteFile(filePath);
Response.End();
I have developed an application that uses c# script files for certain configurations and settings. The script file contains various user generated objects and certain functions on those objects. Presently, the user has to generate a .cs file using a third party editor and supply the path to my program to make use of it. The disadvantage with this method is that the user does not have the flexibility of Auto-complete and intellisense-esque support while editing the script files.
I want to embed the script editing part into my application. I can do that using a rich-text editor. But coding the auto-complete part is a huge pain. Is there any way in which I can provide the user with an in-program editor that also does auto-complete....
Code for compiling a script dynamically in a program.
public String Compile(String inputfilepath)
{
CompilerResults res = null;
CSharpCodeProvider provider = new CSharpCodeProvider();
String errors = "";
if (provider != null)
{
try
{
Assembly asb = Assembly.Load("BHEL.PUMPSDAS.Datatypes, Version=1.0.0.0, Culture=neutral, PublicKeyToken=81d3de1e03a5907d");
CompilerParameters options = new CompilerParameters();
options.GenerateExecutable = false;
options.OutputAssembly = String.Format(outFileDir + oName);
options.GenerateInMemory = false;
options.TreatWarningsAsErrors = false;
options.ReferencedAssemblies.Add("System.dll");
options.ReferencedAssemblies.Add("System.Core.dll");
options.ReferencedAssemblies.Add("System.Xml.dll");
options.ReferencedAssemblies.Add("System.Xml.dll");
options.ReferencedAssemblies.Add(asb.Location);
res = provider.CompileAssemblyFromFile(options, inputfilepath);
errors = "";
if (res.Errors.HasErrors)
{
for (int i = 0; i < res.Errors.Count; i++)
{
errors += "\n " + i + ". " + res.Errors[i].ErrorText;
}
}
}
catch (Exception e)
{
throw (new Exception("Compilation Failed with Exception!\n" + e.Message +
"\n Compilation errors : \n" + errors + "\n"));
}
}
return errors;
}
Specifically for auto-complete, you will need to make use of two systems: a parser, and reflection.
A parser is a pretty straightforward concept, in theory, but I'm sure that it won't be easy to write for a language with as much syntactic sugar and as many context-sensitive keywords as C#.
Since .NET is inherently reflective, and provides a reflection framework, that part shouldn't be incredibly painful, either. Reflection allows you to manipulate the object-oriented elements comprising compiled assemblies--and the assemblies themselves--as objects. A method would be a Method object, for example. You can take a peek at this system by examining the members of the Type class, which provide one basic starting point for reflection. Another useful starting point is Assembly. MSDN, as usual, has a wealth of "official" information in a structured format.
I need to know if is possible to save the state of a CheckBox in C#? I mean if I check the CheckBox and close the program, once I restart the program the CheckBox will still stay checked. Is it possible to?
This is rather a general question. You need to serialise the state yourself somehow, but how, and where to depends on a lot of things.
Possibly take a look at a Settings file for a simple start.
For this, you will need to record the state of the CheckBox yourself. For example, you could store the value in an XML document that would contain your application's UI states. An example, in a very simplistic form, you could do the following:
// ... as the application is closing ...
// Store the state of the check box
System.IO.File.WriteAllText(#"C:\AppFile.txt", this.CheckBox1.IsChecked.ToString());
// ...
// ... as the application is being initialized ...
// Read the state of the check box
string value = System.IO.File.ReadAllText(#"C:\AppFile.txt");
this.CheckBox1.IsChecked = bool.Parse(value);
As you can see, this simply stores the value in a file and reads it back in during initialization. This is not a great way of doing it, but it demonstrates a possible process to follow.
The easiest way of doing this would be to use a config XML file. You can add this very easily through visual studio, there is no need to use registry and it can be used if the app is portable as the settings are saved with the program. A tutorial of how to set this up is here:
http://www.sorrowman.org/c-sharp-programmer/save-user-settings.html
If you are using Web application cookie enabled and storing the information in cookie then it is possible.
You can checkout http://www.daniweb.com/web-development/aspnet/threads/30505
http://asp.net-tutorials.com/state/cookies/
In C# you can use the Settings file. Information how to use it can be found here : http://msdn.microsoft.com/en-us/library/aa730869%28v=vs.80%29.aspx
If you wanted to save this to the Registry you could do something like this
RegistryKey Regkey = "HKEY_CURRENT_USER\\Software\\MyApplication";
RegKey.SetValue("Checkbox", Checkbox.Checked);
but personally I would save it to the .Config file
Here is an example of how to do it using the Config File if you so desire
private static string getConfigFilePath()
{
return Assembly.GetExecutingAssembly().Location + ".config";
}
private static XmlDocument loadConfigDocument()
{
XmlDocument docx = null;
try
{
docx = new XmlDocument();
docx.Load(getConfigFilePath());
return docx;
}
catch (System.IO.FileNotFoundException e)
{
throw new Exception("No configuration file found.", e);
}
}
private void rem_CheckedChanged(object sender, EventArgs e)
{
if (rem.Checked == true)
{
rem.CheckState = CheckState.Checked;
System.Xml.XmlDocument docx = new System.Xml.XmlDocument();
docx = loadConfigDocument();
System.Xml.XmlNode node;
node = docx.SelectSingleNode("//appsettings");
try
{
string key = "rem.checked";
string value = "true";
XmlElement elem = (XmlElement)node.SelectSingleNode(string.Format("//add[#key='{0}']", key));
if (elem != null)
{
elem.SetAttribute("value", value);
}
else
{
elem = docx.CreateElement("add");
elem.SetAttribute("key", key);
elem.SetAttribute("value", value);
node.AppendChild(elem);
}
docx.Save(getConfigFilePath());
}
catch (Exception e2)
{
MessageBox.Show(e2.Message);
}
}
}
I would use Settings like this:
Assuming a boolean setting called boxChecked has been created.
//if user checks box
Properties.Settings.Default.boxChecked = true;
Properties.Settings.Default.Save();
//...
//when the program loads
if(Properties.Settings.Default.boxChecked)
{
checkBox1.Checked = true;
}
else
{
checkBox1.Checked = false;
}
Can anyone tell me how to get track information from the MusicBrainz database from an audio file (mp3, wav, wma, ogg, etc...) using audio fingerprinting. I'm using MusicBrainz Sharp library, but any other library is ok.
I've seen that you must use the libofa library, that you can't use MusicBrainz Sharp to get puid from the audio file, but I can't figure out how to use libofa with C#.
Please show some examples and code snippets to help me, because I can't find them anywhere.
Thanks in advance!
The thing is that you can probably use libofa to get a fingerprint of the audio file, but if the file has no PUID available, you will be stuck and will have to use something like genpuid to submit the audio fingerprint to AmpliFIND and wait about a day to get a PUID.
That being said, I tried something similar about two years ago, but kinda lost interest in the project when I failed to write the IDv3 tags, if I remember correctly. However, the source code is available on Bitbucket.
I basically wrapped libofa using a DllImport and also wrapped genpuid (ie. read the output XML) to be able to read the fingerprint and submit the file for fingerprinting if I did not get one from libofa. I also wrote some code that reads information from MusicBrainz using MusicBrainz Sharp.
Well, at least that was what I planned back then, I think. :) I hope this helps you to solve your problem and I'd love to see an update on this.
Edit: I just noticed that I created a bug report for myself, which basically says that I still needed an implementation for my decoder which is probably why I created this question in SO. So I guess I did not implement the genpuid fingerprinter just to be able to do the fingerprint/get the guid, because I did not get the libofa fingerprinter to work correctly.
I did the wrapped genpuid approach suggested above.
private string GetPUID(string fileName)
{
Process p;
ProcessStartInfo si;
string outRow;
string puidReturned;
string gendPuidPath = #"C:\Program Files\genpuid\genpuid.exe";
string gendPuidKey = "your key here";
System.Text.RegularExpressions.Regex puidRex = new System.Text.RegularExpressions.Regex( #"puid: (\S+)" ); // sample: puid: 3c62e009-ec93-1c0f-e078-8829e885df67
System.Text.RegularExpressions.Match m;
if (File.Exists(gendPuidPath))
{
try
{
si = new ProcessStartInfo(gendPuidPath, gendPuidKey + " \"" + fileName + "\"");
si.RedirectStandardOutput = true;
si.UseShellExecute = false;
p = new Process();
p.StartInfo = si;
p.Start();
puidReturned = "";
while ((outRow = p.StandardOutput.ReadLine()) != null)
{
m = puidRex.Match(outRow);
if (m.Success)
puidReturned = m.Groups[1].Value;
Debug.WriteLine(outRow);
}
p.WaitForExit();
p.Close();
return puidReturned;
}
catch (Exception ex)
{
Debug.WriteLine(ex.Message);
Debug.WriteLine(ex.StackTrace);
throw new Exception("Unexpexted Error obtaining PUID for file: " + fileName, ex);
}
}
else
{
Debug.WriteLine("genpuid.exe not found");
return "";
}
}