I am uploading and retrieving documents to and from the DB.Uploading works great
But retrieving is what is causing the error
Here's the code for retrieving
DataGridViewRow row = dataGridView1.CurrentRow;
int SelectedplantId = Convert.ToInt32(row.Cells["PId"].Value);
SQLiteConnection conn = new SQLiteConnection(connString);
conn.Open();
string qry = "select Otherdocuments from Plant where PId = #PId";
SQLiteCommand cmd = new SQLiteCommand(qry, conn);
cmd.Parameters.AddWithValue("#PId", SelectedpId);
byte[] buffer = (byte[])cmd.ExecuteScalar();
conn.Close();
//string filename = Application.StartupPath + "\\" + sFileName;
string SaveLocation = "C:" + "\\" + sFileName;
FileStream fs = null;
try
{
fs = new FileStream(SaveLocation,FileMode.Create);
fs.Write(buffer, 0, buffer.Length);
}
finally
{
if (fs != null)
{
((IDisposable)fs).Dispose();
}
}
At fs = new FileStream(SaveLocation,FileMode.Create); is where this exception occurs.
Stack Trace
at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
at System.IO.FileStream.Init(String path, FileMode mode, FileAccess access, Int32 rights, Boolean useRights, FileShare share, Int32 bufferSize, FileOptions options, SECURITY_ATTRIBUTES secAttrs, String msgPath, Boolean bFromProxy, Boolean useLongPath)
at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share, Int32 bufferSize, FileOptions options, String msgPath, Boolean bFromProxy)
at System.IO.FileStream..ctor(String path, FileMode mode)
at RVEST.frmPlant.btnRetrieveDocs_Click(Object sender, EventArgs e) in C:\D_Drive_Stuff\RVESTV2\RVEST\frmPlant.cs:line 169
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 RVEST.Program.Main() in C:\D_Drive_Stuff\RVESTV2\RVEST\Program.cs:line 26
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()
Thank you
Sun
The error message seems obvious, the App does not have permission to write in C:\ and probably not in Application.StartupPath either.
//string filename = Application.StartupPath + "\\" + sFileName;
//string SaveLocation = "C:" + "\\" + sFileName;
string SaveLocation = Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), sFileName);
There are a few other SpecialFolders that might be applicable.
Related
I have an exception and I couldn't find a solution for my problem. I think my whole code is valid c#.
namespace YoutubeDownloader2Form
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private async void button1_Click(object sender, EventArgs e)
{
DownloadUrl DownloadUrl = new DownloadUrl();
List<Class1> FinalLiast = DownloadUrl.DownloadUrlMethod(textBox1.Text);
int i = 0;
foreach (var Urls in FinalLiast)
{
string Authorization = Urls.Author;
IEnumerable<VideoInfo> videoInfos = DownloadUrlResolver.GetDownloadUrls(Urls.Url);
VideoInfo Video = videoInfos.First(info => info.VideoType == VideoType.Mp4 && info.Resolution == 144);
if (Video.RequiresDecryption)
{
DownloadUrlResolver.DecryptDownloadUrl(Video);
}
string path = Directory.CreateDirectory(#"C:\Youtube\" + Authorization).ToString();
var videoDownloader = new VideoDownloader(Video,
Path.Combine((#"C:\youtube\" + path), Video.Title + Video.VideoExtension));
StreamWriter dosya = File.AppendText((#"C:\youtube\" + path) + i + ".txt");
videoDownloader.Execute();
//Thread.Sleep(60000);
i++;
}
}
}
}
public class DownloadUrl
{
public List<Class1> DownloadUrlMethod(string txtboxDeger)
{
VideoSearch Items = new VideoSearch();
List<Class1> ListClass1 = new List<Class1>();
string searchCount =
txtboxDeger + "&sp=EgIYAVAU";
foreach (var Item in Items.SearchQuery(searchCount, 1))
{
Class1 Video = new Class1();
Video.title = Item.Title;
Video.Author = Item.Author;
Video.Url = Item.Url;
IEnumerable<VideoInfo> videos = DownloadUrlResolver.GetDownloadUrls(Video.Url);
ListClass1.Add(Video);
}
return ListClass1;
}
}
The code works fine for three queries, but I have 20. At 3. step, it throws an exception; here's the stack trace:
at System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments, Signature sig, Boolean constructor)
at System.Reflection.RuntimeMethodInfo.UnsafeInvokeInternal(Object obj, Object[] parameters, Object[] arguments)
at System.Delegate.DynamicInvokeImpl(Object[] args)
at System.Windows.Forms.Control.InvokeMarshaledCallbackDo(ThreadMethodEntry tme)
at System.Windows.Forms.Control.InvokeMarshaledCallbackHelper(Object obj)
at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Windows.Forms.Control.InvokeMarshaledCallback(ThreadMethodEntry tme)
at System.Windows.Forms.Control.InvokeMarshaledCallbacks()
at System.Windows.Forms.Control.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 YoutubeDownloader2Form.Program.Main() in C:\Users\Ramazan BIYIK\source\repos\YoutubeDownloader2Form\YoutubeDownloader2Form\Program.cs:line 26>>
You can see from picture where the code throws. I tried asynchronously, and it also throws. I checked the InnerException; it says that the given path's format is not supported. But, it downloaded first three videos successfully. It should work fine for other videos too.
Why is this code throwing an exception?
I followed these tutorials to write this code:
https://www.youtube.com/watch?v=kv63n_rfJwk
https://www.youtube.com/watch?v=TnG3urCD_m0
I have this class where I am selecting two values from the database and comparing it to the textbox values provided by the users. Below is my class.
public void Userlogin(TextBox username, TextBox pwd)
{
int _failedAttempt = 0;
OpenConnection();
command = new OracleCommand();
command.CommandText = "SELECT username, user_pwd FROM dinein_system_users WHERE username:usrname AND user_pwd:pwd";
command.Connection = dbconnect;
command.BindByName = true;
try
{
command.Parameters.Add("usrname", username.Text);
command.Parameters.Add("pwd", pwd.Text);
}
catch (NullReferenceException NRE)
{
MessageBox.Show("Please contact your developer about this error. Thank you " + NRE);
}
_reader = command.ExecuteReader();
if (_reader.Read() != true)
{
_failedAttempt = _failedAttempt + 1;
while (_failedAttempt < 3)
{
MessageBox.Show("Incorrect Username or Password. Please try again " + "Attempts: " + _failedAttempt);
username.ResetText();
pwd.ResetText();
}
}
else
{
MessageBox.Show("Welcome");
}
}
my connection string
this._connectionString = "Data Source=xe;Max Pool Size=50;Min Pool Size=1;Connection Lifetime=120;Enlist=true;User Id=hr;Password=hr";
So when the program is executed I am getting this error
An unhandled exception of type 'Oracle.DataAccess.Client.OracleException' occurred in Oracle.DataAccess.dll
Additional information: External component has thrown an exception. I have been at this for the past hour any help would be appreciated.
Update
Open Connection method
public void OpenConnection()
{
try
{
if (dbconnect == null)
{
dbconnect = new OracleConnection(this._connectionString);
dbconnect.Open();
return;
}
switch (dbconnect.State)
{
case ConnectionState.Closed:
case ConnectionState.Broken:
dbconnect.Close();
dbconnect.Dispose();
dbconnect = new OracleConnection(this._connectionString);
dbconnect.Open();
return;
}
}
catch (OracleException oracleException)
{
MessageBox.Show("Database connectionString is null. Contact your developer! " + oracleException);
}
}
Exception Stack Trace
at Oracle.DataAccess.Client.OracleException.HandleErrorHelper(Int32 errCode, OracleConnection conn, IntPtr opsErrCtx, OpoSqlValCtx* pOpoSqlValCtx, Object src, String procedure, Boolean bCheck)
at Oracle.DataAccess.Client.OracleException.HandleError(Int32 errCode, OracleConnection conn, String procedure, IntPtr opsErrCtx, OpoSqlValCtx* pOpoSqlValCtx, Object src, Boolean bCheck)
at Oracle.DataAccess.Client.OracleCommand.ExecuteReader(Boolean requery, Boolean fillRequest, CommandBehavior behavior)
at Oracle.DataAccess.Client.OracleCommand.ExecuteReader()
at DINEIN.OracleDB_Connection.Userlogin(TextBox username, TextBox pwd) in f:\My Documents\Projects\DINEIN\DINEIN\OracleDB_Connection.cs:line 92
at DINEIN.Login.btn_login_Click(Object sender, EventArgs e) in f:\My Documents\Projects\DINEIN\DINEIN\Login.cs:line 31
at System.Windows.Forms.Control.OnClick(EventArgs e)
at System.Windows.Forms.Button.OnClick(EventArgs e)
at System.Windows.Forms.Button.PerformClick()
at System.Windows.Forms.Form.ProcessDialogKey(Keys keyData)
at System.Windows.Forms.Control.ProcessDialogKey(Keys keyData)
at System.Windows.Forms.Control.PreProcessMessage(Message& msg)
at System.Windows.Forms.Control.PreProcessControlMessageInternal(Control target, Message& msg)
at System.Windows.Forms.Application.ThreadContext.PreTranslateMessage(MSG& msg)
at System.Windows.Forms.Application.ThreadContext.System.Windows.Forms.UnsafeNativeMethods.IMsoComponent.FPreTranslateMessage(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 DINEIN.Program.Main() in f:\My Documents\Projects\DINEIN\DINEIN\Program.cs:line 19
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.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Threading.ThreadHelper.ThreadStart()
Rather than using your separate OpenConnection() method, consider coding with the using() statement. It will ensure that your connection an other database-related objects are always disposed.
For example:
int _failedAttempt = 0;
public void Userlogin(TextBox username, TextBox pwd)
{
try
{
using (var connection = new OracleConnection(_connectionString))
{
connection.Open();
using (var command = new OracleCommand())
{
command.CommandText = "SELECT username, user_pwd FROM dinein_system_users WHERE username= :usrname AND user_pwd= :pwd";
command.Connection = connection;
command.BindByName = true;
command.Parameters.Add("usrname", username.Text);
command.Parameters.Add("pwd", pwd.Text);
using (var reader = command.ExecuteReader())
{
if (reader.Read() != true)
{
_failedAttempt += 1;
if (_failedAttempt < 3)
{
MessageBox.Show("Incorrect Username or Password. " +
"Please try again. " +
$"Attempts: {_failedAttempt}");
username.ResetText();
pwd.ResetText();
}
else
{
// 3 failed attempts
}
}
else
{
_failedAttempt = 0;
MessageBox.Show("Welcome");
}
}
}
}
}
catch(OracleException ex)
{
MessageBox.Show("Error: {ex}");
}
}
I am using a backgroundworker and I think there is a cross thread thing.. But I cant solve it.
my code is here
private void bgworkerGameLoad_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e)
{
var arg = e.Argument.ToString();
var liste = webHelper.ShowGame("http://www.abx.com/" + arg);
txtHowToPlay.Invoke(new Action(() => txtHowToPlay.Text = String.Format("Oyun Bilgi: {0}", liste[0])));
txtInfo.Invoke(new Action(() => txtInfo.Text = String.Format("Nasıl Oynanır: {0}", liste[1])));
bgworkerGameLoad.ReportProgress(0,liste[2]);
}
private void bgworkerGameLoad_RunWorkerCompleted(object sender, System.ComponentModel.RunWorkerCompletedEventArgs e)
{
if (FlashPlayerActive)
UnLoad();
string url="";
Invoke(new MethodInvoker(() =>
{
url= e.UserState.ToString();
Thread.Sleep(2);
}));
axShockwaveFlash1.Movie = url;
LoadFlash();
pbWaitForChannelLoading.Visible = false;
axShockwaveFlash1.Play();
}
the problem is that I cant get the e.UserState.ToString() for my shocwaveplayer. I used a local string variable but its the same result.
it is occured targetofaninvocation exception in program.cs
Application.Run(new FrmMain());;
but that code is in frmMain.cs
this is detail of the exception
System.Reflection.TargetInvocationException was unhandled
Message=Exception has been thrown by the target of an invocation.
Source=mscorlib
StackTrace:
at System.RuntimeMethodHandle._InvokeMethodFast(Object target, Object[] arguments, SignatureStruct& sig, MethodAttributes methodAttributes, RuntimeTypeHandle typeOwner)
at System.RuntimeMethodHandle.InvokeMethodFast(Object target, Object[] arguments, Signature sig, MethodAttributes methodAttributes, RuntimeTypeHandle typeOwner)
at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture, Boolean skipVisibilityChecks)
at System.Delegate.DynamicInvokeImpl(Object[] args)
at System.Windows.Forms.Control.InvokeMarshaledCallbackDo(ThreadMethodEntry tme)
at System.Windows.Forms.Control.InvokeMarshaledCallbackHelper(Object obj)
at System.Threading.ExecutionContext.runTryCode(Object userData)
at System.Runtime.CompilerServices.RuntimeHelpers.ExecuteCodeWithGuaranteedCleanup(TryCode code, CleanupCode backoutCode, Object userData)
at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Windows.Forms.Control.InvokeMarshaledCallback(ThreadMethodEntry tme)
at System.Windows.Forms.Control.InvokeMarshaledCallbacks()
at System.Windows.Forms.Control.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 XXX.Program.Main() in c:\Users..............\Program.cs:line 23
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: System.NullReferenceException
Message=Object reference not set to an instance of an object.
Source=System.Windows.Forms
StackTrace:
at System.Windows.Forms.Control.MarshaledInvoke(Control caller, Delegate method, Object[] args, Boolean synchronous)
at System.Windows.Forms.Control.Invoke(Delegate method, Object[] args)
at System.Windows.Forms.Control.Invoke(Delegate method)
at XXX.FrmMain.bgworkerGameLoad_RunWorkerCompleted(Object sender, RunWorkerCompletedEventArgs e) in c:\Users..........\FrmMain.cs:line 332
at System.ComponentModel.BackgroundWorker.OnRunWorkerCompleted(RunWorkerCompletedEventArgs e)
at System.ComponentModel.BackgroundWorker.AsyncOperationCompleted(Object arg)
InnerException:
what is my mistake? I tried to use delegate but its the same..
It sounds like the problem is as simple as e.UserState being null. You don't even need to use Invoke to get at UserState - you'll see the same problem if you just have:
if (FlashPlayerActive)
UnLoad();
string url = e.UserState.ToString();
Thread.Sleep(2); // This is generally a bad idea anyway, btw...
Where are you setting the UserState? I suspect you're not setting it anywhere, so it's still null, which is why you're getting an exception.
I solved the problem..
I hadnt added axShockwaveFlash1 to my form before set values..
in LoadFlash function, it was
public void LoadFlash()
{
axShockwaveFlash1 = new AxShockwaveFlash();
axShockwaveFlash1.BeginInit();
axShockwaveFlash1.Location = new Point(14, 196);
axShockwaveFlash1.Name = "Test Movie";
axShockwaveFlash1.TabIndex = 0;
axShockwaveFlash1.Movie = liste[2];
axShockwaveFlash1.EmbedMovie = true;
axShockwaveFlash1.AutoSize = true;
axShockwaveFlash1.Size = new Size(640, 480);
axShockwaveFlash1.Visible = true;
axShockwaveFlash1.EndInit();
splitContainerControl.Panel2.Controls.Add(axShockwaveFlash1);
FlashPlayerActive = true;
}
but i changed this code like
public void LoadFlash()
{
axShockwaveFlash1 = new AxShockwaveFlash();
splitContainerControl.Panel2.Controls.Add(axShockwaveFlash1);
axShockwaveFlash1.BeginInit();
axShockwaveFlash1.Location = new Point(14, 196);
...
it works..
if found the solution here
http://forum.fusioncharts.com/topic/2424-how-to-resolve-invalidactivexstateexception-while-loading-chart/#entry8855
thanx
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