I checked around and even utilized/tweaked several solutions including the following, but I keep getting one of two errors. I either get
************** Exception Text **************
System.Runtime.InteropServices.COMException (0x80070422)
at System.Runtime.InteropServices.Marshal.ThrowExceptionForHRInternal(Int32 errorCode, IntPtr errorInfo)
at System.Management.ManagementObject.InvokeMethod(String methodName, ManagementBaseObject inParameters, InvokeMethodOptions options)
at Check_In_Tool.checkInForm.CreateRestorePoint() in C:\Users\Greg\Source\Repos\Check In Tool\Check In Tool\Check In Tool\Form1.cs:line 268
at Check_In_Tool.checkInForm.button1_Click(Object sender, EventArgs e) in C:\Users\Greg\Source\Repos\Check In Tool\Check In Tool\Check In Tool\Form1.cs:line 64
at System.Windows.Forms.Control.OnClick(EventArgs e)
at System.Windows.Forms.Button.OnClick(EventArgs e)
at System.Windows.Forms.Button.OnMouseUp(MouseEventArgs mevent)
at System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons button, Int32 clicks)
at System.Windows.Forms.Control.WndProc(Message& m)
at System.Windows.Forms.ButtonBase.WndProc(Message& m)
at System.Windows.Forms.Button.WndProc(Message& m)
at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
at System.Windows.Forms.NativeWindow.Callback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam))
or
The RPC server is unavailable. (Exception from HRESULT: 0x800706BA)
The code I am using currently is as follows:
try
{
// select local computer
ManagementScope ManScope = new ManagementScope("\\\\localhost\\root\\DEFAULT");
// create system restore point
ManagementPath ManPath = new ManagementPath("SystemRestore");
// select default options
ObjectGetOptions ManOptions = new ObjectGetOptions();
// create management class with previous options
ManagementClass ManClass = new ManagementClass(ManScope, ManPath, ManOptions);
// load function parameters
ManagementBaseObject ManBaseObject = ManClass.GetMethodParameters("CreateRestorePoint");
// description
ManBaseObject["Description"] = "Check-In Tool Restore Point";
// type of the restore point
ManBaseObject["RestorePointType"] = 0;
// type of the event
ManBaseObject["EventType"] = 100;
ManagementBaseObject OutParam = ManClass.InvokeMethod("CreateRestorePoint", ManBaseObject, null);
restLabel.Text = "Restore Point Set: Yes";
}
catch (ManagementException err)
{
restLabel.Text = "Restore Point Set: No - Error";
MessageBox.Show(err.Message);
}
Edit: I updated my code from err.Message to err.ToString() and got some new information. The issue, apparently, lies within this line of code:
ManagementBaseObject OutParam = ManClass.InvokeMethod("CreateRestorePoint", ManBaseObject, null);
Any ideas?
Related
I am using the following method to generate the script:
/// <summary>
/// Create single Table script with Data of specified DataBase and Table.
/// </summary>
/// <param name="dataBaseName">DataBase Name</param>
/// <param name="tableName">Table Name</param>
/// <param name="connectionString">Connection String</param>
public void CreateScriptTable(string dataBaseName, string tableName, string connectionString)
{
SqlConnection con = new SqlConnection(connectionString);
ServerConnection serverConnection = new ServerConnection(con);
Server server = new Server(serverConnection);
Database database = server.Databases["" + dataBaseName + ""];//Here exception coming
if (database != null)
{
Scripter scripter = new Scripter(server);
scripter.Options.ScriptData = true;
scripter.Options.ScriptSchema = true;
scripter.Options.ScriptDrops = false;
var sb = new StringBuilder();
foreach (Table table in database.Tables)
{
if (table.Name.ToLower() == tableName.ToLower())
{
sb.Append("DROP TABLE " + table.Name);
sb.Append(Environment.NewLine);
foreach (string s in scripter.EnumScript(new Urn[] { table.Urn }))
{
sb.Append(s);
sb.Append(Environment.NewLine);
}
string folder = "C:\\temp\\Scripts\\";
string filename = folder + tableName + ".sql";
System.IO.StreamWriter fs = System.IO.File.CreateText(filename);
fs.Write(sb);
fs.Close();
}
}
}
}
references added:
using Microsoft.SqlServer.Management.Common;
using Microsoft.SqlServer.Management.Sdk.Sfc;
using Microsoft.SqlServer.Management.Smo;
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Data.SqlClient;
using System.Text;
using System.Windows.Forms;
Exception:
Method not found: 'Microsoft.SqlServer.Management.Common.ServerConnection Microsoft.SqlServer.Management.Common.ServerConnection.GetDatabaseConnection(System.String)'.
at Microsoft.SqlServer.Management.Smo.Server.GetExecutionManager()
at Microsoft.SqlServer.Management.Smo.Server.get_ExecutionManager()
at Microsoft.SqlServer.Management.Smo.SqlSmoObject.get_DatabaseEngineType()
at Microsoft.SqlServer.Management.Smo.DatabaseCollection.get_Item(String name)
at CreateBatchFile.Form1.CreateScriptTable(String dataBaseName, String tableName, String connectionString) in C:\Test Projects\CreateBatchFile\CreateBatchFile\Form1.cs:line 45
at CreateBatchFile.Form1.btnGenerateBatchFile_Click(Object sender, EventArgs e) in C:\Test Projects\CreateBatchFile\CreateBatchFile\Form1.cs:line 29
at System.Windows.Forms.Control.OnClick(EventArgs e)
at System.Windows.Forms.Button.OnClick(EventArgs e)
at System.Windows.Forms.Button.OnMouseUp(MouseEventArgs mevent)
at System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons button, Int32 clicks)
at System.Windows.Forms.Control.WndProc(Message& m)
at System.Windows.Forms.ButtonBase.WndProc(Message& m)
at System.Windows.Forms.Button.WndProc(Message& m)
at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
at System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg)
at System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(IntPtr dwComponentID, Int32 reason, Int32 pvLoopData)
at System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context)
at System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context)
at System.Windows.Forms.Application.Run(Form mainForm)
at CreateBatchFile.Program.Main() in C:\Test Projects\CreateBatchFile\CreateBatchFile\Program.cs:line 19
References in Solution Explorer:
Please let me know where I am moving in wrong direction.
I'm making a program that register an product. This product have several fields, but only two of them are mandatory to start the registration (they can be edited later). Those informations are putted in a DataGridView, and then i convert it to a DataTable, so i can bulk insert it to a temporary table so i can process and clean all the data in it. Just after the bulk insert, i run a procedure that do all the data treatment and check if the informations are right. In the same procedure, after the checks, i insert the data into the original table.
All this process is ok, everything is running fine in C# and in the SQL Server until it. But there is an error that happens every time when i try to do a MessageBox.Show() or when i try to open another form.
Here is the function that i created to run the procedure. Everything is running fine, the only thing that throws the error is the message box. I commented all of them and runned the program again and it didn't throw anything at the end.
Here is the code:
public void RodarProcedureAddEdit(string procedureName, bool isAdd)
{
string result = String.Empty;
// Variáveis para definir os parâmetros do frmMessageBox.
string message = String.Empty;
string headerText = String.Empty;
bool isError = false;
using (SqlConnection conn = new SqlConnection(Globals.connectionString))
{
try
{
conn.Open();
using (SqlCommand comm = new SqlCommand(procedureName, conn))
{
comm.CommandType = CommandType.StoredProcedure;
if(isAdd) comm.Parameters.AddWithValue("#methodType", "A");
else comm.Parameters.AddWithValue("#methodType", "E");
comm.Parameters.AddWithValue("#userID", user.userID);
if(isAdd) comm.Parameters.AddWithValue("#requestID", 0);
else comm.Parameters.AddWithValue("#requestID", requestID);
comm.Parameters.Add("#responseMessage", SqlDbType.NVarChar, 250).Direction = ParameterDirection.Output;
comm.Parameters.Add("#responsibleUser", SqlDbType.NVarChar, 250).Direction = ParameterDirection.Output;
comm.ExecuteNonQuery();
result = comm.Parameters["#responseMessage"].Value.ToString();
string responsibleUser = comm.Parameters["#responsibleUser"].Value.ToString();
if (result == "OK")
{
if (isAdd)
{
message = "O cadastro foi concluído com sucesso";
headerText = "Cadastro";
isError = false;
//MessageBox.Show("O cadastro foi concluído com sucesso", "Cadastro", MessageBoxButtons.OK, MessageBoxIcon.Information);
this.Close();
}
else
{
// Enviar E-mail quando finalizar a requisição.
if (responsibleUser != string.Empty)
{
try
{
Outlook.Application app = new Outlook.Application();
Outlook.MailItem mailItem = app.CreateItem(Outlook.OlItemType.olMailItem);
mailItem.Subject = $"Requisição nº {requestID} foi finalizada - Product Catalog";
mailItem.To = DAO.User.getMailAddress(responsibleUser);
mailItem.Body = Globals.finalizedMailBody.Replace("$requisicao", requestID.ToString());
mailItem.Send();
}
catch (Exception ex)
{
message = ex.Message;
headerText = "Erro";
isError = true;
//MessageBox.Show(ex.Message, "Erro", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
message = "A alteração foi realizada com sucesso";
headerText = "Alteração";
isError = false;
//MessageBox.Show("A alteração foi realizada com sucesso!", "Cadastro", MessageBoxButtons.OK, MessageBoxIcon.Information);
this.Close();
}
}
message = result;
headerText = "Erro";
isError = true;
//else MessageBox.Show(result, "Erro", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
catch (Exception ex)
{
message = ex.Message;
headerText = "Erro";
isError = true;
//MessageBox.Show(ex.Message, "Erro", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
finally
{
// Isso foi instanciado para conseguir "criar" uma MessageBox, mais detalhes no formulário.
if (message != String.Empty && headerText != String.Empty)
{
frmMessageBox frmMessageBox = new frmMessageBox(message, headerText, isError);
frmMessageBox.ShowDialog();
}
}
}
}
At the end, after investigating a lot i find that the error is throwing because of the index in the DataGridView.
Here is the complete exception:
at System.Collections.ArrayList.get_Item(Int32 index)
at System.Windows.Forms.DataGridViewColumnCollection.get_Item(Int32 index)
at System.Windows.Forms.DataGridView.PositionEditingControl(Boolean setLocation, Boolean setSize, Boolean setFocus)
at System.Windows.Forms.DataGridView.PerformLayoutPrivate(Boolean useRowShortcut, Boolean computeVisibleRows, Boolean invalidInAdjustFillingColumns, Boolean repositionEditingControl)
at System.Windows.Forms.DataGridView.ResetUIState(Boolean useRowShortcut, Boolean computeVisibleRows)
at System.Windows.Forms.DataGridViewRowCollection.OnCollectionChanged_PreNotification(CollectionChangeAction cca, Int32 rowIndex, Int32 rowCount, DataGridViewRow& dataGridViewRow, Boolean changeIsInsertion)
at System.Windows.Forms.DataGridViewRowCollection.OnCollectionChanged(CollectionChangeEventArgs e, Int32 rowIndex, Int32 rowCount)
at System.Windows.Forms.DataGridViewRowCollection.AddInternal(Boolean newRow, Object[] values)
at System.Windows.Forms.DataGridView.AddNewRow(Boolean createdByEditing)
at System.Windows.Forms.DataGridView.OnCurrentCellDirtyStateChanged(EventArgs e)
at System.Windows.Forms.DataGridView.set_IsCurrentCellDirtyInternal(Boolean value)
at System.Windows.Forms.DataGridView.NotifyCurrentCellDirty(Boolean dirty)
at System.Windows.Forms.DataGridViewComboBoxEditingControl.OnSelectedIndexChanged(EventArgs e)
at System.Windows.Forms.ComboBox.WmReflectCommand(Message& m)
at System.Windows.Forms.ComboBox.WndProc(Message& m)
at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
at System.Windows.Forms.UnsafeNativeMethods.SendMessage(HandleRef hWnd, Int32 msg, IntPtr wParam, IntPtr lParam)
at System.Windows.Forms.Control.SendMessage(Int32 msg, IntPtr wparam, IntPtr lparam)
at System.Windows.Forms.Control.ReflectMessageInternal(IntPtr hWnd, Message& m)
at System.Windows.Forms.Control.WmCommand(Message& m)
at System.Windows.Forms.Control.WndProc(Message& m)
at System.Windows.Forms.ScrollableControl.WndProc(Message& m)
at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
at System.Windows.Forms.UnsafeNativeMethods.CallWindowProc(IntPtr wndProc, IntPtr hWnd, Int32 msg, IntPtr wParam, IntPtr lParam)
at System.Windows.Forms.NativeWindow.DefWndProc(Message& m)
at System.Windows.Forms.Control.DefWndProc(Message& m)
at System.Windows.Forms.Control.WmCommand(Message& m)
at System.Windows.Forms.Control.WndProc(Message& m)
at System.Windows.Forms.ComboBox.WndProc(Message& m)
at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
I tried everything, i even created a new form that was exactly like a message box but it throwed the exception in the frmMessageBox.ShowDialog();
I'm using SQL Server as my database.
Can someone help me with it?
Any doubts please feel free to ask! Thanks a lot already!
Edit:
Here is the code of the DataGridView instantiation.
dataMKT = new DataGridView();
dataMKT.Location = new Point(17, 43);
dataMKT.Size = new Size(850, 268);
dataMKT.CellMouseClick += dataGridView_CellMouseClick;
dataMKT.CellEnter += dataGridView_CellEnter;
dataMKT.DataSourceChanged += dataMKT_DataSourceChanged;
dataMKT.DataError += dataMKT_DataError;
dataMKT.CellValueChanged += new DataGridViewCellEventHandler(dataMKT_CellValueChanged);
dataMKT.CurrentCellDirtyStateChanged += new EventHandler(dataMKT_CurrentCellDirtyStateChanged);
dataMKT.CellEndEdit += dataMKT_CellEndEdit;
tpgMKT.Controls.Add(dataMKT);
And Binding.
dataMKT.DataSource = Util.Util.GetView(requestID, viewName);
GetView method:
public static DataTable GetView(int requestID, string viewName)
{
DataTable dataTable = new DataTable();
string queryGetTable = $"SELECT * FROM {viewName} WHERE [Request ID] = {requestID}";
using (SqlConnection conn = new SqlConnection(Globals.connectionString))
{
try
{
conn.Open();
using(SqlDataAdapter adapter = new SqlDataAdapter(queryGetTable, conn))
{
adapter.Fill(dataTable);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Erro", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
return dataTable;
}
I have a code where I set the picturebox.image to the filePath below but when I run the program it throws a memory exeption. The image is a .jpg format. and as you can see in the code, I am not using a stream. Do I need to use I stream so that the exeption doesn't happen? If so then how do I use it?
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.Text.RegularExpressions;
using System.IO;
using System.Net;
using System.Web;
using System.Runtime.InteropServices;
namespace WindowsFormsApp1
{
public partial class Form1 : Form
{
public WebClient web;
public String html;
public Form1()
{
InitializeComponent();
List<string> plants = new List<string>();
web = new WebClient();
html = web.DownloadString("https://bonnieplants.com/how-to-grow/");
MatchCollection m1 = Regex.Matches(html, "(.+?)", RegexOptions.Singleline);
foreach(Match m in m1)
{
string plant = m.Groups[1].Value;
plants.Add(plant);
}
plants.Sort();
comboBox1.Items.AddRange(plants.ToArray());
}
private void button1_Click(object sender, EventArgs e)
{
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
Uri imageUrl = new Uri("https://edge.bonnieplants.com/www/img/products/artichokes-400px-30.jpg");
string fileName = System.IO.Path.GetFileName(imageUrl.LocalPath);
fileName = fileName.Replace("-400px-30", "");
web.DownloadFileAsync(imageUrl, fileName);
string filePath = Application.StartupPath.ToString() + #"\" + fileName;
if(#"C:\Users\user\source\repos\WindowsFormsApp1\WindowsFormsApp1\bin\Debug\artichokes.jpg" == filePath)
{
Console.WriteLine(filePath);
}
pictureBox1.Image = Image.FromFile(Application.StartupPath.ToString() + #"\" + fileName);
}
private void Form1_Load(object sender, EventArgs e)
{
}
}
}
and here is the exeption :
System.OutOfMemoryException
HResult=0x8007000E
Message=Out of memory.
Source=System.Drawing
StackTrace:
at System.Drawing.Image.FromFile(String filename, Boolean useEmbeddedColorManagement)
at System.Drawing.Image.FromFile(String filename)
at WindowsFormsApp1.Form1.comboBox1_SelectedIndexChanged(Object sender, EventArgs e) in C:\Users\user\source\repos\WindowsFormsApp1\WindowsFormsApp1\Form1.cs:line 56
at System.Windows.Forms.ComboBox.OnSelectedIndexChanged(EventArgs e)
at System.Windows.Forms.ComboBox.WmReflectCommand(Message& m)
at System.Windows.Forms.ComboBox.WndProc(Message& m)
at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
at System.Windows.Forms.UnsafeNativeMethods.SendMessage(HandleRef hWnd, Int32 msg, IntPtr wParam, IntPtr lParam)
at System.Windows.Forms.Control.SendMessage(Int32 msg, IntPtr wparam, IntPtr lparam)
at System.Windows.Forms.Control.ReflectMessageInternal(IntPtr hWnd, Message& m)
at System.Windows.Forms.Control.WmCommand(Message& m)
at System.Windows.Forms.Control.WndProc(Message& m)
at System.Windows.Forms.ScrollableControl.WndProc(Message& m)
at System.Windows.Forms.Form.WndProc(Message& m)
at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
at System.Windows.Forms.UnsafeNativeMethods.CallWindowProc(IntPtr wndProc, IntPtr hWnd, Int32 msg, IntPtr wParam, IntPtr lParam)
at System.Windows.Forms.NativeWindow.DefWndProc(Message& m)
at System.Windows.Forms.Control.DefWndProc(Message& m)
at System.Windows.Forms.Control.WmCommand(Message& m)
at System.Windows.Forms.Control.WndProc(Message& m)
at System.Windows.Forms.ComboBox.WndProc(Message& m)
at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
at System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg)
at System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(IntPtr dwComponentID, Int32 reason, Int32 pvLoopData)
at System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context)
at System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context)
at System.Windows.Forms.Application.Run(Form mainForm)
at WindowsFormsApp1.Program.Main() in C:\Users\user\source\repos\WindowsFormsApp1\WindowsFormsApp1\Program.cs:line 19
UPDATE:
I figured out that the actual image is not formatted correctly and does not open in the file explorer. Does anybody know why?
................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................
web.DownloadFileAsync(imageUrl, fileName); downloads in the background, so you have to wait for it to finish before trying to open the picture. You can subscribe to the OnDownloadFileCompleted event to know when the download is finished.
An alternative is just to replace with a synchronous download:
web.DownloadFile(imageUrl, fileName);
However, if you execute that from the main thread, you will freeze the UI while the picture is downloading. So, use with care.
I'm trying to generate excel file using window form. I got error when trying to save the excel.
Method call from buttom
ExportToExcel(dtResult, "C:\\Excel/test.xls");
Code for generate Excel
public void ExportToExcel( DataTable Tbl, string ExcelFilePath = null)
{
try
{
if (Tbl == null || Tbl.Columns.Count == 0)
throw new Exception("ExportToExcel: Null or empty input table!\n");
// load excel, and create a new workbook
Excel.Application excelApp = new Excel.Application();
excelApp.Workbooks.Add();
// single worksheet
Excel._Worksheet workSheet = excelApp.ActiveSheet;
// column headings
for (int i = 0; i < Tbl.Columns.Count; i++)
{
workSheet.Cells[1, (i + 1)] = Tbl.Columns[i].ColumnName;
}
// rows
for (int i = 0; i < Tbl.Rows.Count; i++)
{
// to do: format datetime values before printing
for (int j = 0; j < Tbl.Columns.Count; j++)
{
workSheet.Cells[(i + 2), (j + 1)] = Tbl.Rows[i][j];
}
}
// check fielpath
if (ExcelFilePath != null && ExcelFilePath != "")
{
try
{
workSheet.SaveAs(ExcelFilePath); //throws error here
excelApp.Quit();
MessageBox.Show("Excel file saved!");
}
catch (Exception ex)
{
throw new Exception("ExportToExcel: Excel file could not be saved! Check filepath.\n"
+ ex.Message);
}
}
else // no filepath is given
{
excelApp.Visible = true;
}
}
catch (Exception ex)
{
throw new Exception("ExportToExcel: \n" + ex.Message);
}
}
Error
System.Exception was unhandled
Message=ExportToExcel:
ExportToExcel: Excel file could not be saved! Check filepath.
Microsoft Excel cannot access the file 'C:\//5D95C000'. There are several possible reasons:
• The file name or path does not exist.
• The file is being used by another program.
• The workbook you are trying to save has the same name as a currently open workbook.
Source=Report
StackTrace:
at Report.Form1.ExportToExcel(DataTable Tbl, String ExcelFilePath) in C:\SMARTAG_PROJECT\SUREREACH\EXCEL\Report\Report\Form1.cs:line 84
at Report.Form1.button1_Click(Object sender, EventArgs e) in C:\SMARTAG_PROJECT\SUREREACH\EXCEL\Report\Report\Form1.cs:line 29
at System.Windows.Forms.Control.OnClick(EventArgs e)
at System.Windows.Forms.Button.OnClick(EventArgs e)
at System.Windows.Forms.Button.OnMouseUp(MouseEventArgs mevent)
at System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons button, Int32 clicks)
at System.Windows.Forms.Control.WndProc(Message& m)
at System.Windows.Forms.ButtonBase.WndProc(Message& m)
at System.Windows.Forms.Button.WndProc(Message& m)
at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
at System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg)
at System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(IntPtr dwComponentID, Int32 reason, Int32 pvLoopData)
at System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context)
at System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context)
at System.Windows.Forms.Application.Run(Form mainForm)
at Report.Program.Main() in C:\SMARTAG_PROJECT\SUREREACH\EXCEL\Report\Report\Program.cs:line 18
at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean ignoreSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Threading.ThreadHelper.ThreadStart()
InnerException:
In order to get your file to save you need to make sure that you have a file extension at the end of the file path.
the filepath in your method here ExportToExcel(dtResult, "C:\\Excel/test.xls"); is incorrect
also make sure that you release the excelApp object correctly
instead of excelApp.Quit(); replace it with something like this
System.Runtime.InteropServices.Marshal.ReleaseComObject( excelApp );
I am trying to read a public folder hosted in ExchangeServer 2010 SP1. Well I am able to connect but when I am trying to read the folder I am getting stragne error. Hope somebody will able to share his/her experience. Below is the code what I am executing doing and after that the error SoapException was Unhandled I am getting.
ExchangeServiceBinding serviceBinding = new ExchangeServiceBinding();
serviceBinding.Credentials = new NetworkCredential("XXXXXXXX", "YYYYYY", "zzzzzzzz");
serviceBinding.RequestServerVersionValue = new RequestServerVersion();
serviceBinding.RequestServerVersionValue.Version = ExchangeVersionType.Exchange2010_SP1;
serviceBinding.Url = #"https://the.domain.of.my.work/EWS/exchange.asmx";
DistinguishedFolderIdType publicFolderRoot = new DistinguishedFolderIdType();
publicFolderRoot.Id = DistinguishedFolderIdNameType.publicfoldersroot;
FindFolder(serviceBinding, publicFolderRoot, #"All Public Folders");
private static FolderIdType FindFolder(ExchangeServiceBinding esb, BaseFolderIdType folderId, string folderName)
{
//FindPublicFolderType request = new FindPublicFolderType();
FindFolderType request = new FindFolderType();
request.Traversal = FolderQueryTraversalType.Shallow;
request.FolderShape = new FolderResponseShapeType();
request.FolderShape.BaseShape = DefaultShapeNamesType.AllProperties;
request.ParentFolderIds = new BaseFolderIdType[] { folderId };
//Giving error at this below
FindFolderResponseType response = esb.FindFolder(request);
foreach (ResponseMessageType rmt in response.ResponseMessages.Items)
{
if (rmt.ResponseClass == ResponseClassType.Success)
{
FindFolderResponseMessageType ffResponse = (FindFolderResponseMessageType)rmt;
if (ffResponse.RootFolder.TotalItemsInView > 0)
{
foreach (BaseFolderType subFolder in ffResponse.RootFolder.Folders)
if (subFolder.DisplayName == folderName)
return subFolder.FolderId;
return null;
}
Console.WriteLine("Can't find '" + folderName + "'.");
}
else
{
//Console.WriteLine("Response was: " + rmt.ResponseClass + Environment.NewLine + rmt.MessageText);
MessageBox.Show("Response was: " + rmt.ResponseClass + Environment.NewLine + rmt.MessageText);
}
}
return null;
}
After executing the above code I am facing error mentioned below
System.Web.Services.Protocols.SoapException
System.Web.Services.Protocols.SoapException
was unhandled Message="The mailbox
that was requested doesn't support the
specified RequestServerVersion."
Source="System.Web.Services"
Actor="" Lang="en-US" Node=""
Role="" StackTrace:
at System.Web.Services.Protocols.SoapHttpClientProtocol.ReadResponse(SoapClientMessage
message, WebResponse response, Stream
responseStream, Boolean asyncCall)
at System.Web.Services.Protocols.SoapHttpClientProtocol.Invoke(String
methodName, Object[] parameters)
at RnDExchangePublicFolder.ExchangeWebServices.ExchangeServiceBinding.FindFolder(FindFolderType
FindFolder1) in
E:\Data\VS2008\RnDExchangePublicFolder\RnDExchangePublicFolder\Web
References\ExchangeWebServices\Reference.cs:line
547
at RnDExchangePublicFolder.Form1.FindFolder(ExchangeServiceBinding
esb, BaseFolderIdType folderId, String
folderName) in
E:\Data\VS2008\RnDExchangePublicFolder\RnDExchangePublicFolder\Form1.cs:line
51
at RnDExchangePublicFolder.Form1.btnConnect_Click(Object
sender, EventArgs e) in
E:\Data\VS2008\RnDExchangePublicFolder\RnDExchangePublicFolder\Form1.cs:line
39
at System.Windows.Forms.Control.OnClick(EventArgs
e)
at System.Windows.Forms.Button.OnClick(EventArgs
e)
at System.Windows.Forms.Button.OnMouseUp(MouseEventArgs
mevent)
at System.Windows.Forms.Control.WmMouseUp(Message&
m, MouseButtons button, Int32 clicks)
at System.Windows.Forms.Control.WndProc(Message&
m)
at System.Windows.Forms.ButtonBase.WndProc(Message&
m)
at System.Windows.Forms.Button.WndProc(Message&
m)
at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message&
m)
at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message&
m)
at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr
hWnd, Int32 msg, IntPtr wparam, IntPtr
lparam)
at System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG&
msg)
at System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(Int32
dwComponentID, Int32 reason, Int32
pvLoopData)
at System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32
reason, ApplicationContext context)
at System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32
reason, ApplicationContext context)
at System.Windows.Forms.Application.Run(Form
mainForm)
at RnDExchangePublicFolder.Program.Main()
in
E:\Data\VS2008\RnDExchangePublicFolder\RnDExchangePublicFolder\Program.cs:line
18
at System.AppDomain._nExecuteAssembly(Assembly
assembly, String[] args)
at System.AppDomain.ExecuteAssembly(String
assemblyFile, Evidence
assemblySecurity, String[] args)
at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
at System.Threading.ThreadHelper.ThreadStart_Context(Object
state)
at System.Threading.ExecutionContext.Run(ExecutionContext
executionContext, ContextCallback
callback, Object state)
at System.Threading.ThreadHelper.ThreadStart()
InnerException:
Can somebody share their experience what is causing the issue or to further proceed.?
Thanks