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.
Related
I know there is a bunch of threads on seemingly the same issue but I cannot for the life of me figure this out after 3 hours so I really need some help.
I understand that I am getting this error because the system does not have access to the file. I have tried setting permissions to full and a few other code snippets to solve my issue but none have worked.
This is a windows 10 app using Xaramin,
I am trying to populate a listbox with contact from an XML file. I have the list box itemsSource set to "Data Context" and path "myList". The XML build action is set to "Content" and the Copy to Output Directory Set to "Copy Always".
I have attempted to follow the tutorial from my course from the beginner 3 times and always get the same error.
Here is the error I am getting
Below is the entire code on the page.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using System.Xml;
using System.Xml.Linq;
using Windows.Storage;
using System.Collections.ObjectModel;
// The Blank Page item template is documented at https://go.microsoft.com/fwlink/?LinkId=402352&clcid=0x409
namespace ContactsApp
{
/// <summary>
/// An empty page that can be used on its own or navigated to within a Frame.
/// </summary>
public sealed partial class MainPage : Page
{
string TEMPFILEPATH = "";
string TARGETFILEPATH = "";
private ObservableCollection<string> lstd = new ObservableCollection<string>();
public ObservableCollection<string> myList { get { return lstd; } }
public MainPage()
{
this.InitializeComponent();
}
private void Grid_Loading(FrameworkElement sender, object args)
{
Windows.ApplicationModel.Package package = Windows.ApplicationModel.Package.Current;
StorageFolder installedLocation = package.InstalledLocation;
StorageFolder targetLocation = ApplicationData.Current.LocalFolder;
TEMPFILEPATH = installedLocation.Path.ToString() + "\\Contacts.xml";
TARGETFILEPATH = targetLocation.Path.ToString() + "\\Contacts.xml";
File.Move(TEMPFILEPATH, TARGETFILEPATH);
loadContacts();
}
private void loadContacts()
{
XmlReader xmlReader = XmlReader.Create(TARGETFILEPATH);
while (xmlReader.Read())
{
if (xmlReader.Name.Equals("ID") && (xmlReader.NodeType == XmlNodeType.Element))
{
lstd.Add(xmlReader.ReadElementContentAsString());
}
}
DataContext = this;
xmlReader.Dispose();
}
}
}
I will be eternally grateful for any help regarding the matter. :)
You should not try to access restricted paths in constrained environments (like Windows Phone).
Instead, if you really need to embed this file with your application, change the build action to Embedded Resource and to Do not copy for your xml file, and then retrieve the resource inside your code as an Embedded Resource:
public void LoadContacts()
{
const string fileName = "Contacts.xml";
var assembly = typeof(MainPage).GetTypeInfo().Assembly;
var path = assembly.GetManifestResourceNames()
.FirstOrDefault(n => n.EndsWith(fileName, StringComparison.OrdinalIgnoreCase));
if(path == null)
throw new Exception("File not found");
using (var stream = assembly.GetManifestResourceStream(path))
using (var reader = XmlReader.Create(stream))
{
while (reader.Read())
{
if (reader.Name.Equals("ID") && (reader.NodeType == XmlNodeType.Element))
{
lstd.Add(reader.ReadElementContentAsString());
}
}
}
DataContext = this; // better to move this inside the constructor
}
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.
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);
}
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.
Is it possible to write a simple and fast function in C# that will execute arbitrary methods from a string? For example, if I set MyString="MessageBox.Show("Some Message")" and then call ExecuteString(MyString), a message box would pop up with "Some Message" in it.
(I've probably made some sort of error in the above code. I don't yet know C#; I'm trying to evaluate whether it would be appropriate for a specific project.)
You should be able to use this and wrap the code required to run a string into a function.
Essentially what you're doing is wrapping the small bit of C# code in a Program.Mainstyle function, referencing some assemblies for basic functionality (maybe including your own assembly) then run the compiled program in memory.
It's likely a bit of more overhead than you need to simply run one or two lines of code mind you.
http://support.microsoft.com/kb/304655
what you appear to be looking for is CS-Script
Alas, C# is not a dynamic language in that way. You can't really do this easily, and if it's really something you need to do, consider using a .Net language more in line with your needs, like IronPython or IronRuby.
Your best available alternative is to use the CodeDom namespace, as this truly convoluted and heinous example from this forum thread shows:
using System;
using System.CodeDom;
using System.CodeDom.Compiler;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Linq;
using System.Reflection;
using System.Reflection.Emit;
using System.Text;
using System.Windows.Forms;
namespace TestApp
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
SampleLib.SampleType test = new SampleLib.SampleType();
private void button1_Click(object sender, EventArgs e)
{
// Dynamically build and call the method
label1.Text = test.MyText;
}
private void button2_Click(object sender, EventArgs e)
{
StringBuilder DynamicCode = new StringBuilder();
DynamicCode.Append("namespace TestDynamic");
DynamicCode.Append("{");
DynamicCode.Append("public class DynamicCode");
DynamicCode.Append("{");
DynamicCode.Append("public static void EditText(SampleLib.SampleType t)");
DynamicCode.Append("{");
DynamicCode.Append("t.MyText = \"Goodbye!\";");
DynamicCode.Append("}");
DynamicCode.Append("}");
DynamicCode.Append("}");
string CodeString = DynamicCode.ToString();
System.IO.FileInfo fi = new System.IO.FileInfo(Application.ExecutablePath);
CodeDomProvider provider = CodeDomProvider.CreateProvider("C#");
CompilerParameters CompileParams = new CompilerParameters(new string[] { fi.DirectoryName + "\\SampleLib.dll" },
fi.DirectoryName + "\\Dynamic.dll");
CompileParams.MainClass = "DynamicCode";
CompileParams.GenerateExecutable = false;
//CompileParams.GenerateInMemory = true;
CompilerResults r = provider.CompileAssemblyFromSource(CompileParams, new string[] {CodeString});
foreach (CompilerError er in r.Errors)
{
Console.WriteLine(er.ErrorText);
}
}
private void button3_Click(object sender, EventArgs e)
{
// Dynamically call assembly
System.IO.FileInfo fi = new System.IO.FileInfo(Application.ExecutablePath);
Assembly dynAsm = Assembly.LoadFile(fi.DirectoryName + "\\Dynamic.dll");
if (dynAsm != null)
{
object o = dynAsm.CreateInstance("TestDynamic.DynamicCode", true);
Type t = dynAsm.GetType("TestDynamic.DynamicCode");
t.GetMethod("EditText").Invoke(o, new object[]{test});
}
}
}
}