C# XML Query to display Exception Error [duplicate] - c#

This question already has answers here:
What is a NullReferenceException, and how do I fix it?
(27 answers)
Closed 6 years ago.
I attempting to display some XML results based on a user submitted xml document and user submitted XPath syntax into a rich text box. My issue is a I keep getting the error:
An unhandled exception of type 'System.NullReferenceException' occurred in WindowsFormsApplication1.exe
Additional information: Object reference not set to an instance of an object.
Here is my code below.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Xml;
using System.Collections.Generic;
using System.ComponentModel;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
OpenFileDialog ofd = new OpenFileDialog();
ofd.Filter = "XML |*.xml";
if (ofd.ShowDialog() == DialogResult.OK)
{
XmlDocument xDoc = new XmlDocument();
xDoc.Load(ofd.FileName);
richTextBox1.Text = xDoc.SelectSingleNode(textBox1.Text).InnerText;
}
}
}
}

Change this line
richTextBox1.Text = xDoc.SelectSingleNode(textBox1.Text).InnerText;
to
XmlNode node = xDoc.SelectSingleNode(textBox1.Text);
if(node != null)
richTextBox1.Text = node.InnerText;
And investigate why node is null.

Related

How can I extract a specific text from a string? [duplicate]

This question already has answers here:
What is the best way to parse html in C#? [closed]
(15 answers)
Get a value of an attribute by HtmlAgilityPack
(5 answers)
HTML Agility Pack get all anchors' href attributes on page
(1 answer)
Closed 2 years ago.
I need to find the part of the string between the two tags :
First tag <h3><a href="/questions/
Last tag " class
I'm trying to use indexof and substring but what should I do with the substring ?
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace MyString
{
public partial class Form1 : Form
{
private string htmlCode = "";
public Form1()
{
InitializeComponent();
var myString = GetSources();
int index = myString.IndexOf("<h3><a href=") + 11;
string restulr = myString.Substring(index, )
// <h3><a href="/questions/
// " class
}
private string GetSources()
{
using (WebClient client = new WebClient()) // WebClient class inherits IDisposable
{
htmlCode = client.DownloadString("https://myStringTest.com");
}
return htmlCode;
}
private void Form1_Load(object sender, EventArgs e)
{
}
}
}
Use RegEx to separate HTML or use the Html Agility Pack (HAP).

How to fetch specific data from XML using C#

I'm trying to fetch specific data from a Xml file to display in a textbox. My Xml file name as "test.xml" has following code
<?xml version="1.0" encoding="utf-8" ?>
<Body>
<Context>
<PageNo>a87</PageNo>
<Verse>"Do it right"</Verse>
</Context>
</Body>
My C# code is below: Edited to reflect recent chnages
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Xml;
namespace learn2
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
pageid1();
}
private void pageid1()
{
textBox1.Clear();
XmlDocument doc = new XmlDocument();
doc.Load("C:\\test.xml");
var pagenoNodeList = doc.SelectNodes("Body/Context/PageNo");
var pageNoNode = pagenoNodeList[0]; // To select the first node
var text = pageNoNode.InnerText; // Gets the text value inside the node
textBox1.Text = text;
} }
}
I highly appreciate any help. Thanks
You need to identify the node you are looking for, as SelectNodes returns a System.Xml.XmlNodeList, and then get the value of InnerText:
var pagenoNodeList = doc.SelectNodes("Body/Context/PageNo");
var pageNoNode = pagenoNodeList[0]; // To select the first node
var text = pageNoNode.InnerText; // Gets the text value inside the node
textBox1.Text = text;

COMException C# Microsoft.Office.Interop.Excel

I am trying to solve an issue I am having with a COMException. This is my code:
The error occurs at Workbook Original = new Workbook(result[0]);
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using MahApps.Metro.Controls;
using MahApps.Metro;
using Microsoft.Win32;
using System.Windows.Forms;
using System.Data;
using Microsoft.Office.Interop.Excel;
namespace KPI_Generator_v3
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : MetroWindow
{
string [] result;
Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog();
public MainWindow()
{
InitializeComponent();
}
private void exit_Click(object sender, RoutedEventArgs e)
{
this.Close();
}
private void browse_Click(object sender, RoutedEventArgs e)
{
// Create OpenFileDialog
instructionslbl.Visibility = Visibility.Hidden;
dlg.Multiselect = true;
dlg.ShowDialog();
result = dlg.FileNames;
dlg.DefaultExt = ".xls";
dlg.Filter = "XLS Files (*.xls)|*.xls";
foreach (string fileName in result)
{
displayFilesBox.Text += fileName + System.Environment.NewLine;
}
SelectedFileslbl.Visibility = Visibility.Visible;
displayFilesBox.Visibility = Visibility.Visible;
generateBtn.Visibility = Visibility.Visible;
}
private void generate_Click(object sender, RoutedEventArgs e)
{
Workbook Original = new Workbook(result[0]);
for (int i = 1; i <= result.Length; i++)
{
Workbook next = new Workbook(result[i]);
Worksheet newOGsheet = Original.Worksheets.Add();
Worksheet nextSheet = next.Worksheets[0];
nextSheet.Copy(newOGsheet);
}
}
}
}
Now.. Although the above code will probably not work I am getting an error that states
'System.Runtime.InteropServices.COMException' occurred in mscorlib.dll
with additional information saying
HRESULT: 0x80040154 (REGDB_E_CLASSNOTREG))
After googling for quite some time I have downloaded dependency walker and have the following output:
I have no idea what I am doing and some help would be much appreciated! Thank you
EDIT: REGEDIT picture of HKEY CLASSES_ROOT (if needed)
EDIT2: Picture of error
This error is a COM interop flaw unfortunately. Otherwise, you would be getting a compile error, since Workbook is an interface and doesn't have a constructor. This interface isn't meant to be instantiated, which is why you are getting this exception. (Not sure why you're passing in the filename here as well...)
To fix this, use Microsoft.Office.Interop.Excel.Application:
using Microsoft.Office.Interop.Excel;
Application excelApp = new Application();
excelApp.Workbooks.Open(result[0]);
Other notes:
You should call dlg.ShowDialog() last - that way, your filters will take effect.
For your filter, I suggest adding an option for .xlsx files, to support newer Excel files
Add result.Length > 0 before using it, just to make sure the user actually opened something.
Change your for loop condition to i < result.Length; otherwise, you'll get an IndexOutOfRangeException
Also, just to add more information: you may be asking: "but wait, ryrich, Application is an interface too! How come I can instantiate it but not Workbook??"
I wondered this too. Apparently this works because it is decorated with a CoClassAttribute (and some other attributes). For more detailed information about this, see this stack overflow post.

How to give Common path to video

I am working in project in which I have used vlc plugin v2. the path for my video is
axVLC.playlist.add(#"D:\My Project\Science\Resources\myvideo.mp4");
axVLC.playlist.play();
now the problem is when I build the project and give it to someone and he/she install it on his/her computer , it show exception that video path is wrong. I am sure that path is not suitable as my the video path in my project is D:... and he/she installed it on C.
So my question is that is there any way to give it common path by which user don`t face such kind of error
Import IO
Using System.IO;
then declare a string that will reference to your video folder
string AbsoluteRef;
use this code in your form load
if (System.Diagnostics.Debugger.IsAttached)
{
AbsoluteRef = Path.GetFullPath(Application.StartupPath + "\\..\\..\\Resources\\");
}
else
{
AbsoluteRef = Application.StartupPath + "\\Resources\\";
}
Now declare a string for your video or which ever file like
string vlcvideo;
now add the two together
vlcvideo = AbsoluteRef & "myvideo.mp4";
Finnally add all this into your vlc plugin
axVLC.playlist.add(vlcvideo);
Complete Code looks like so.
using Microsoft.VisualBasic;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Windows.Input;
using yournamespace.Forms;
using System.IO;
namespace yourNameSpace
{
public partial class frmMain : Form
{
public frmMain()
{
InitializeComponent();
}
string AbsoluteRef = null;
private void frmMain_Load(object sender, EventArgs e)
{
if (System.Diagnostics.Debugger.IsAttached)
{
AbsoluteRef = Path.GetFullPath(Application.StartupPath + "\\..\\..\\Resources\\");
}
else
{
AbsoluteRef = Application.StartupPath + "\\Resources\\";
}
string vlcVideo = AbsoluteRef + "myvideo.mp4";
axVLC.playlist.add(vlcvideo);
}

Server unable to execute EWS autodiscover

On our testing server, EWS autodiscover does not work. To eliminate an ill-set IIS option from the list of causes, I C&P'ed together a WindowsForms Application (code below) and put it, together with the Microsoft.Exchange.Webservice.dll, into a folder on which I have write permission.
Unfortunately, neither xml nor text file are created. Instead, I get an Unhandled Exception error.
System.NullReferenceException
at System.Windows.Forms.TextBoxBase.AppendText(String text)
This does not happen on my development machine, which is in the same AD domain and on which the test app always returns that autodiscover was successful.
Question: How come no Trace output is generated?
So now, my app code:
Form1.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Microsoft.Exchange.WebServices;
using Microsoft.Exchange.WebServices.Data;
namespace ADDebugWin
{
public partial class Form1 : Form
{
public static string traceData;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
ExchangeService ews = new ExchangeService(ExchangeVersion.Exchange2010);
ews.TraceListener = new TraceListener();
// Optional flags to indicate the requests and responses to trace.
ews.TraceFlags = TraceFlags.EwsRequest | TraceFlags.EwsResponse;
ews.TraceEnabled = true;
ews.UseDefaultCredentials = true;
try {
ews.AutodiscoverUrl("email#mydomain.com");
textBox1.AppendText("AutoDiscover erfolgreich.");
} catch (Exception ex) {
textBox1.AppendText(traceData);
textBox1.AppendText(ex.Message + "\r\n" + ex.StackTrace);
}
}
}
}
TraceListener.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using ADDebugMvc.Controllers;
using Microsoft.Exchange.WebServices.Data;
using System.Xml;
namespace ADDebugMvc.Models
{
class TraceListener : ITraceListener
{
public void Trace(string traceType, string traceMessage)
{
CreateXMLTextFile(traceType, traceMessage.ToString());
HomeController.traceData += traceType + " " + traceMessage.ToString() + "\r\n";
}
private void CreateXMLTextFile(string fileName, string traceContent)
{
// Create a new XML file for the trace information.
try
{
// If the trace data is valid XML, create an XmlDocument object and save.
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(traceContent);
xmlDoc.Save(fileName + ".xml");
}
catch
{
// If the trace data is not valid XML, save it as a text document.
System.IO.File.WriteAllText(fileName + ".txt", traceContent);
}
}
}
}
One should note that
ews.TraceFlags = TraceFlags.EwsRequest | TraceFlags.EwsResponse;
is not returning any Traces during AutoDiscover.
(ews.TraceFlags = TraceFlags.All; does.)
So no string is appended to traceData, which is why traceData==null -> Exception when appending it to a TextBox.

Categories