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}");
}
}
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
This is my code in form1:
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.IO;
using Google.GData.Client;
using Google.GData.Extensions;
using Google.GData.YouTube;
using Google.GData.Extensions.MediaRss;
using Google.YouTube;
namespace YouTube_Manager
{
public partial class Form1 : Form
{
YouTubeRequestSettings settings;
YouTubeRequest request;
string username = "myusername", password = "mypass", devkey = "mydevkey";
string filename, filetype, filemime;
public string Devkey
{
get { return devkey; }
set { devkey = value; }
}
public string Password
{
get { return password; }
set { password = value; }
}
public string Username
{
get { return username; }
set { username = value; }
}
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
Devkey = devkey;
Password = password;
Username = username;
settings = new YouTubeRequestSettings("YouTube_Manager", devkey, username, password);
request = new YouTubeRequest(settings);
if (cmbCat.Items.Count > 0)
{
cmbCat.SelectedIndex = 0;
}
if (cmbPrivacy.Items.Count > 0)
{
cmbPrivacy.SelectedIndex = 0;
}
}
public void UploadVideo()
{
Video video = new Video();
video.Title = txtTitle.Text;
video.Tags.Add(new MediaCategory(cmbCat.SelectedItem.ToString(), YouTubeNameTable.CategorySchema));
video.Keywords = txtKeyWords.Text;
if (cmbPrivacy.SelectedIndex == 1)
video.Private = true;
else
video.Private = false;
GetFileMime();
video.MediaSource = new MediaFileSource(filename, filemime);
request.Upload(video);
MessageBox.Show("Successfully uploaded");
}
public void GetFileMime()
{
switch (filetype)
{
case "flv": filemime = "video/x-flv"; break;
case "avi": filemime = "video/avi"; break;
case "3gp": filemime = "video/3gpp"; break;
case "mov": filemime = "video/quicktime"; break;
default: filemime = "video/quicktime"; break;
}
}
private void btnChoosefile_Click(object sender, EventArgs e)
{
string tmp;
choosefile.ShowDialog();
tmp = choosefile.FileName;
txtFilepath.Text = tmp;
string[] title = tmp.Split('\\');
int i = title.GetUpperBound(0);
string temp = title[i];
string[] title1 = temp.Split('.');
txtTitle.Text = title1[0];
filename = tmp.Replace("\\", "\\\\");
filetype = title1[1];
}
private void button1_Click(object sender, EventArgs e)
{
DialogResult result = MessageBox.Show("By clicking 'upload,' " +
"you certify that you own all rights to the content or that you are authorized" +
"by the owner to make the content publicly available on YouTube, and that it otherwise" +
"complies with the YouTube Terms of Service located at http://www.youtube.com/t/terms", "Aggrement",
MessageBoxButtons.YesNo, MessageBoxIcon.Question);
if (result == DialogResult.Yes)
{
UploadVideo();
}
}
private void button2_Click(object sender, EventArgs e)
{
this.Close();
}
}
}
The exception is on the line:
request.Upload(video);
In the google development site i created application called it Youtube Uploader.
And the key i'm using in my c# app is the Client Id ending with: apps.googleusercontent.com
But i'm not sure this is the right key.
As for a user name i'm using my gmail email that i use to log in to youtube.
And the password.
In my code cmbCat and cmbPrivacy are comboBoxes.
This is the exception message:
Google.GData.Client.InvalidCredentialsException was unhandled
HResult=-2146233088
Message=Invalid credentials
Source=Google.GData.Client
StackTrace:
at Google.GData.Client.Utilities.QueryClientLoginToken(GDataCredentials gc, String serviceName, String applicationName, Boolean fUseKeepAlive, IWebProxy proxyServer, Uri clientLoginHandler)
at Google.GData.Client.GDataGAuthRequest.QueryAuthToken(GDataCredentials gc)
at Google.GData.Client.GDataGAuthRequest.EnsureCredentials()
at Google.GData.Client.GDataRequest.EnsureWebRequest()
at Google.GData.Client.GDataGAuthRequest.EnsureWebRequest()
at Google.GData.Client.GDataGAuthRequest.CopyRequestData()
at Google.GData.Client.GDataGAuthRequest.Execute(Int32 retryCounter)
at Google.GData.Client.GDataGAuthRequest.Execute()
at Google.GData.Client.MediaService.EntrySend(Uri feedUri, AtomBase baseEntry, GDataRequestType type, AsyncSendData data)
at Google.GData.Client.Service.Insert(Uri feedUri, AtomEntry newEntry, AsyncSendData data)
at Google.GData.Client.Service.Insert[TEntry](Uri feedUri, TEntry entry)
at Google.GData.YouTube.YouTubeService.Upload(String userName, YouTubeEntry entry)
at Google.YouTube.YouTubeRequest.Upload(String userName, Video v)
at Google.YouTube.YouTubeRequest.Upload(Video v)
at YouTube_Manager.Form1.UploadVideo() in d:\C-Sharp\YouTube_Manager\YouTube_Manager\YouTube_Manager\Form1.cs:line 81
at YouTube_Manager.Form1.button1_Click(Object sender, EventArgs e) in d:\C-Sharp\YouTube_Manager\YouTube_Manager\YouTube_Manager\Form1.cs:line 122
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 YouTube_Manager.Program.Main() in d:\C-Sharp\YouTube_Manager\YouTube_Manager\YouTube_Manager\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.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()
InnerException:
ClientLogin (login and password) was deprecated as of April 20, 2012 and turned off on May 26 2015. This code will not longer work you need to switch to using Oauth2.
I would like to also recomed you use the new Google client library
Install-Package Google.Apis.YouTube.v3
I am using an open file dialog which I dragged from the toolbox onto my form. The file dialog was working fine until recently.
I've searched high and low for an answer online but none of them work. I started the project on my home computer and then copied the whole project folder to my work computer so that I can work on it both at home and at work.
The file dialog works fine even now on my work computer but after I make changes to the code (at work) and copy the new project folder to my home computer the issue occurs. This is not managed in TFS or any other shared location. This is a private project that I am working on. The code where the issue occurs is as below:
Thread th;
private void btnUploadToDB_Click(object sender, EventArgs e)
{
try
{
openFileDialog1.Title = "Select new data file";
openFileDialog1.Filter = "Excel Files |*.xlsx";
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
string filePath = openFileDialog1.FileName;
}
else if (DialogResult == DialogResult.None)
{
return;
}
th = new Thread(uploadToDB);
Control.CheckForIllegalCrossThreadCalls = false;
th.Start();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
GC.Collect();
}
}
The stack trace when the error occurs is as below:
System.AccessViolationException was unhandled
Message=Attempted to read or write protected memory. This is often an indication that other memory is corrupt.
Source=System.Windows.Forms
StackTrace:
at System.Windows.Forms.FileDialogNative.IFileDialog.Show(IntPtr parent)
at System.Windows.Forms.FileDialog.RunDialogVista(IntPtr hWndOwner)
at System.Windows.Forms.FileDialog.RunDialog(IntPtr hWndOwner)
at System.Windows.Forms.CommonDialog.ShowDialog(IWin32Window owner)
at System.Windows.Forms.CommonDialog.ShowDialog()
at Form1.Form1.btnUploadData_Click(Object sender, EventArgs e) in C:\Users\User1\Documents\Visual Studio 2010\Projects\C#_Projects\C# Projects\Solution 1\Solution 1\Form1.cs:line 458
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 Form1.Program.Main() in C:\Users\User1\Documents\Visual Studio 2010\Projects\C#_Projects\C# Projects\Solution 1\Solution 1\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:
Further, I tried creating an empty project on my home computer where the issue occurs and added an openfiledialog in the same manner and it works fine. The issue seems to be with only this application and that too when it is on my home machine.
I am adding the updateToDB method as requested. I have modified some values so there might be lines that don't make sense, however, I believe it is not relevant to the issue at hand.
private void uploadToDB()
{
try
{
string values = "";
string excelConString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source='" +
filePath + "'; Extended Properties='Excel 12.0 Xml;HDR=Yes;IMEX=1;'";
string excelSql = "select * from [Sheet1$]";
string accessConString = GlobalOleDBCommands.DBconString;
string accessSql = "delete from table1";
GlobalOleDBCommands.CommandExecuteNonQuery(accessSql, accessConString);
using (OleDbDataAdapter adap = new OleDbDataAdapter(excelSql, excelConString))
{
using (DataTable dt = new DataTable())
{
adap.Fill(dt);
using (OleDbConnection accessCon = new OleDbConnection(accessConString))
{
accessCon.Open();
for (int i = 0; i < dt.Rows.Count - 1; i++)
{
for (int j = 0; j <= dt.Columns.Count - 1; j++)
{
values = values.Trim() + dt.Rows[i][j] + ",";
}
values = Strings.Left(values, (Strings.Len(values) - 1));
string value1 = SplitAndReturnText(values, ",", 0);
string value2 = SplitAndReturnText(values, ",", 1);
string value3 = SplitAndReturnText(values, ",", 2);
string value4 = SplitAndReturnText(values, ",", 3);
accessSql = "insert into table1 (value1,value2,value3,value4) values(#value1,#value2,#value3,#value4)";
using (OleDbCommand dtToAccessCmd = new OleDbCommand(accessSql, accessCon))
{
dtToAccessCmd.Parameters.AddWithValue("#value1", value1);
dtToAccessCmd.Parameters.AddWithValue("#value2", value2);
dtToAccessCmd.Parameters.AddWithValue("#value3", System.Threading.Thread.CurrentThread.CurrentCulture.TextInfo.ToTitleCase(value3.ToLower()));
dtToAccessCmd.Parameters.AddWithValue("#value4", value4);
try
{
dtToAccessCmd.ExecuteNonQuery();
}
catch (Exception)
{
}
this.lblProgress.Text = (i + "/" + ((dt.Rows.Count) - 1)).ToString();
this.lblProgress.Refresh();
}
// Reset value variable to null.
values = "";
}
}
}
}
accessSql = "select max(end_time) from table1 where user_name='" +
Environment.UserName + "'";
DateTime start_time = Convert.ToDateTime(GlobalOleDBCommands.
CommandExecuteScalar(accessSql, GlobalOleDBCommands.DBconString));
DateTime end_time = DateTime.Now;
double total_time = (end_time - start_time).TotalMinutes;
string fieldValues = "start_time, end_time, user_name, task_name, total_time,task_count";
accessSql = "insert into table1 (" + fieldValues + ") values ('" +
start_time + "','" + DateTime.Now + "','" + Environment.UserName +
"','Update to DB','" + total_time + "','1')";
GlobalOleDBCommands.CommandExecuteNonQuery(accessSql, GlobalOleDBCommands.DBconString);
MessageBox.Show("New data added ");
this.lblProgress.Text = "";
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
Could someone please advise what is causing this issue as I am not able to work on changes to the code at home for the fear that it would not work when I transfer to my work machine.
To run code on a deploy computer one of two things must occur
1) The exact same version of Net library must be on both computers including updates.
2) You must publish the application on the build computer and then run the setup.exe folder that is created on the build computer on the deploy computer.
You simply can't copy the exe from one computer to another.
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