I have a piece of code which requires me to use a process, but i want that to run in background and not open console window.
public uint LaunchProcess(string sIPAddress, string sPort)
{
uint iPid = 0;
try
{
logger.AddLog("LaunchProcess : " + sIPAddress + " " + sPort);
object[] PlugInRunnerInfo = { StaticUtils.GetLocation(AgilentPluginCommonConstants.PlugInRunnerPath) + "\\" + "PlugInRunner.exe" + " " + sIPAddress + " " + sPort, null, null, 0 };
//ManagementClass is a part of Windows Management Intrumentation,namespaces. One of its use is to provides access to manage applications.
//Here this class is used to launch PlugInRunner as detached process.By setting the ManagementClass object's property 'CreateFlags' to value 0x00000008
//we can start the PlugInRunner as detached one.
using (var mgmtObject = new ManagementClass("Win32_Process"))
{
var processStartupInfo = new ManagementClass("Win32_ProcessStartup");
processStartupInfo.Properties["CreateFlags"].Value = 0x00000008;//DETACHED_PROCESS.
var result = mgmtObject.InvokeMethod("Create", PlugInRunnerInfo);
if (result != null)
{
logger.AddLog("Process id " + Convert.ToUInt32(PlugInRunnerInfo[3]));
iPid = Convert.ToUInt32(PlugInRunnerInfo[3]);
}
}
}
catch (Exception ex)
{
logger.AddLog("Exception " + ex.Message);
}
return iPid;
}
Above is my code, can anyone help me run the process in background?
Related
While performing queries against Active Directory Domain Services using one of the .NETs’ reference/namespace i.e., System.DirectoryServices, we are unable to create AD account containing numeric(s) in Display Name or Email Address. It’s a 2 step process, creating the mailbox and then updating all the other attributes. While creating the mailbox we are not getting any error, however while updating the attributes to the same mailbox we are getting an custom error as mailbox / sAMAccountName doesn’t exist.
We are using the same DC throughout the code. Moreover, the code is working fine if the proposing display name and email address doesn’t have numeric(s). Since the Exchange 2016 servers have been upgraded to CU8, we are facing this issue.
We are using the .NET code instead of Exchange to avoid manual intervention. It’s integrated with other systems to auto generate the mail boxes and AD accounts.
It’s a 2 step process because we can’t pass all the other attributes to the New-Mailbox cmdlet. Once the mailbox gets created, we are updating it with the other attributes.
In Event Viewer, the object was created, modified & finally deleted. The deletion is happening automatically which is exceptional.
Code Snippet
//Creating mailbox
DirectorySearcher dSearchUPN = new DirectorySearcher(deCon);
dSearchUPN.Filter = "(UserPrincipalName=" + strUserPrincipalName + ")";
SearchResult sResultUPN = dSearchUPN.FindOne();
if (sResultUPN == null)
{
//Open it
runspace.Open();
using (PowerShell powershell = PowerShell.Create())
{
powershell.Runspace = runspace;
powershell.AddCommand("New-Mailbox");
powershell.AddParameter("Name", strName);
powershell.AddParameter("UserPrincipalName", strUserPrincipalName);
powershell.AddParameter("Alias", strAlias);
powershell.AddParameter("PrimarySmtpAddress", strPrimarySmtpAddress);
powershell.AddParameter("OrganizationalUnit", strOrganizationalUnit);
powershell.AddParameter("Database", strDatabase);
powershell.AddParameter("SamAccountName", strSamAccountName);
powershell.AddParameter("Password", strPassword);
powershell.AddParameter("ResetPasswordOnNextLogon", true);
powershell.AddParameter("DomainController", "ABCDWXYZADC2.corp.cyient.com");
powershell.Invoke();
}
//Logic for Display Name & Email Address for duplicate First Name & Last Name
int i = 1;
while (!string.IsNullOrEmpty(searchEmailAddress(strPrimarySmtpAddress)))
{
i = i + 1;
strName = dr["firstName"].ToString().Replace(".", "") + " " + dr["lastName"].ToString().Replace(".", "") + " " + dr["workerID"].ToString();
strPrimarySmtpAddress = dr["firstName"].ToString().Replace(" ", "").Replace(".", "") + "." + dr["lastName"].ToString().Replace(" ", "").Replace(".", "") + i.ToString() + strSMTPDomain;
}
//Updating mailbox
DirectorySearcher dSearch;
dSearch = new DirectorySearcher(deCon);
//Filtering AccountName with Database Domain
dSearch.Filter = "(sAMAccountName=" + strSamAccountName + ")";
SearchResult sResult = dSearch.FindOne();
if (sResult != null) //Check if the Account is available
{
DirectoryEntry deToUpdate = sResult.GetDirectoryEntry();
if (!string.IsNullOrEmpty(strEmployeeNumber))
{
deToUpdate.Properties["employeeNumber"].Value = strEmployeeNumber;
strToDisplay = strToDisplay + "\r\nEmployee Number: " + strEmployeeNumber;
}
if (!string.IsNullOrEmpty(strEmployeeType))
{
deToUpdate.Properties["employeeType"].Value = strEmployeeType;
strToDisplay = strToDisplay + "\r\nEmployee Type: " + strEmployeeType;
}
if (!string.IsNullOrEmpty(strGivenName))
{
deToUpdate.Properties["givenName"].Value = strGivenName;
strToDisplay = strToDisplay + "\r\nFirst Name: " + strGivenName;
}
if (!string.IsNullOrEmpty(strSurName))
{
deToUpdate.Properties["sn"].Value = strSurName;
strToDisplay = strToDisplay + "\r\nLast Name:" + strSurName;
}
if (!string.IsNullOrEmpty(strTitle))
{
deToUpdate.Properties["title"].Value = strTitle;
strToDisplay = strToDisplay + "\r\nTitle: " + strTitle;
}
if (!string.IsNullOrEmpty(strCompany))
{
deToUpdate.Properties["company"].Value = strCompany;
strToDisplay = strToDisplay + "\r\nCompany: " + strCompany;
}
if (!string.IsNullOrEmpty(strDepartment))
{
deToUpdate.Properties["department"].Value = strDepartment;
strToDisplay = strToDisplay + "\r\nDepartment: " + strDepartment;
}
if (!string.IsNullOrEmpty(strBUDesc))
{
deToUpdate.Properties["physicalDeliveryOfficeName"].Value = strBUDesc;
strToDisplay = strToDisplay + "\r\nBusiness Unit: " + strBUDesc;
}
if (!string.IsNullOrEmpty(strStreetAddress))
{
deToUpdate.Properties["streetAddress"].Value = strStreetAddress;
strToDisplay = strToDisplay + "\r\nAddress: " + strStreetAddress;
}
if (!string.IsNullOrEmpty(strLocation))
{
deToUpdate.Properties["l"].Value = strLocation;
strToDisplay = strToDisplay + "\r\nCity: " + strLocation;
}
if (!string.IsNullOrEmpty(strState))
{
deToUpdate.Properties["st"].Value = strState;
strToDisplay = strToDisplay + "\r\nState:" + strState;
}
if (!string.IsNullOrEmpty(strPostalCode))
{
deToUpdate.Properties["postalCode"].Value = strPostalCode;
strToDisplay = strToDisplay + "\r\nZip Code: " + strPostalCode;
}
if (!string.IsNullOrEmpty(strCountry))
{
deToUpdate.Properties["c"].Value = strCountry;
strToDisplay = strToDisplay + "\r\nCountry/Region:" + strCountry + "";
}
if (!string.IsNullOrEmpty(strExpiryDate))
{
DateTime dtExpiryDate = Convert.ToDateTime(strExpiryDate).AddDays(1);
deToUpdate.Properties["accountExpires"].Value = Convert.ToString((Int64)dtExpiryDate.ToFileTime());
strToDisplay = strToDisplay + "\r\nExpiry Date:" + strExpiryDate + "";
}
if (!string.IsNullOrEmpty(strExtensionAttribute1))
deToUpdate.Properties["extensionAttribute1"].Value = strExtensionAttribute1; //Update Company Code
if (!string.IsNullOrEmpty(strExtensionAttribute2))
deToUpdate.Properties["extensionAttribute2"].Value = strExtensionAttribute2; //Update Location Code
if (!string.IsNullOrEmpty(strExtensionAttribute3))
deToUpdate.Properties["extensionAttribute3"].Value = strExtensionAttribute3; //Update Job Title Code
if (!string.IsNullOrEmpty(strExtensionAttribute4))
deToUpdate.Properties["extensionAttribute4"].Value = strExtensionAttribute4; //Update Management Level Code
if (!string.IsNullOrEmpty(strExtensionAttribute8))
deToUpdate.Properties["extensionAttribute8"].Value = strExtensionAttribute8; //Update Sup Org Code
if (!string.IsNullOrEmpty(strExtensionAttribute10))
deToUpdate.Properties["extensionAttribute10"].Value = strExtensionAttribute10; //Update Department Code
if (!string.IsNullOrEmpty(strExtensionAttribute13))
deToUpdate.Properties["extensionAttribute13"].Value = strExtensionAttribute13; //Update Sup Org
}
catch (Exception exObj)
{
WriteToErrorLog("Error while updating Manager details.\n", " Emp AD ID: " + strAlias + "; Manager ID: " + strManager, "Application Exception");
WriteToErrorLog("Error while updating Manager (" + strManager + ") details of the Employee (" + strAlias + ").\n", "Message: " + exObj.Message + ";\n Method Name: " + exObj.TargetSite, "Application Exception");
}
}
deToUpdate.CommitChanges();
WriteToLog("Account updation succeeded...", "AD Attributes: " + strToDisplay);
}
else
{
WriteToLog("Account creation/updation failed...", "AD Attributes: " + strToDisplay);
strStatusCode = "0";
strStatusDesc = "Account Creation failed.";
}
I am calling following method inside thread. inside method i have written logs which writes some variable values in notepad file.
Problem : Sometime last log of method do not log anything. ie last line not exucuting sometime. i am not able to understand problem. please guide me if there are issue somewhere.
This is web application hosted in iis server.
Function :
public bool ResetEmployeeAssignedCoursesByRole()
{
bool bReturn = false;
DbTransactionHelper dbTransactionHelper = new DbTransactionHelper();
dbTransactionHelper.BeginTransaction();
try
{
// this line execuete fine
ErrorLog.createRoleLog("Method sp_Reset_EmpAssignedCoursesByRole Started " + this.RoleID + " Course ID " + this.CourseID + " External Message " + sMessage);
StringBuilder sbQueryEmployeeCourse = new StringBuilder();
sbQueryEmployeeCourse.Append(" set #roleID = " + roleID + "; ");
sbQueryEmployeeCourse.Append(" set #courseID = " + courseID + "; ");
sbQueryEmployeeCourse.Append(" set #inActiveReason = " + inActiveReason + "; ");
sbQueryEmployeeCourse.Append(" set #lastRecordUpdateSource = " + lastRecordUpdateSource + "; ");
sbQueryEmployeeCourse.Append(" call sp_Reset_EmpAssignedCoursesByRole (#roleID, #courseID, #inActiveReason, #lastRecordUpdateSource); ");
DataTable dtEmployeeCourse = dbTransactionHelper.GetDataTable(BusinessUtility.GetString(sbQueryEmployeeCourse), CommandType.Text, null
);
dbTransactionHelper.CommitTransaction();
bReturn = true;
// this line not execuete sometime.
ErrorLog.createRoleLog("Method sp_Reset_EmpAssignedCoursesByRole Ended " + this.RoleID + " Course ID " + this.CourseID + " External Message " + sMessage);
}
catch (Exception ex)
{
ErrorLog.createRoleLog("Add Role ID " + BusinessUtility.GetString(roleID));
dbTransactionHelper.RollBackTransaction();
ErrorLog.createRoleLog("Add Course ID " + BusinessUtility.GetString(courseID));
ErrorLog.createRoleLog(ex.ToString());
}
return bReturn;
}
Calls method like below :
Thread t = new Thread(ResetEmployeeAssignedCoursesByRole);
t.Start();
FUNCTION createRoleLog :
public static void createRoleLog(string errorMessage, int empHdrID = 0)
{
try
{
//string path = BusinessUtility.GetString(AppConfig.GetAppConfigValue("LogsDiractory")) + "Log" + DateTime.Now.ToString("yyyy-MM-dd") + ".txt";
string path = BusinessUtility.GetString(ErrorLog.ErrorLogPath) + "RoleLog" + DateTime.Now.ToString("yyyy-MM-dd") + ".txt";
if (BusinessUtility.GetString(AppConfig.GetAppConfigValue("LogError")).ToString().ToUpper() == "TRUE")
{
if (!File.Exists(path))
{
StreamWriter sw = File.CreateText(path);
sw.Close();
}
//using (System.IO.StreamWriter sw = System.IO.File.AppendText(path))
//{
// sw.WriteLine("-------- " + DateTime.Now + " --------");
// sw.WriteLine(errorMessage);
// sw.WriteLine("------------------------");
// sw.Close();
//}
if (!IsFileLocked(new FileInfo(path)))
{
using (FileStream stream = new FileStream(path, FileMode.Append, FileAccess.Write, FileShare.ReadWrite))
{
using (System.IO.StreamWriter sw = new StreamWriter(stream))
{
if (empHdrID != 0)
{
sw.WriteLine("-------- [empHdrID: " + empHdrID + "] " + DateTime.Now + " --------");
}
else
{
sw.WriteLine("-------- " + DateTime.Now + " --------");
}
sw.WriteLine(errorMessage);
sw.WriteLine("------------------------");
sw.Close();
}
}
}
else
{
}
}
}
catch (Exception ex)
{
//throw ex;
}
}
Last line of function which not execution sometime is :
** this line not execuete sometime.**
ErrorLog.createRoleLog("Method sp_Reset_EmpAssignedCoursesByRole Ended " + this.RoleID + " Course ID " + this.CourseID + " External Message " + sMessage);
I'm trying to develop a sms sending system using asp.net mvc 4 where I'm using HUAWEI USB 3G modem to send sms. Problem is, when I receive sms, most often the text are coming like this,
AT+CMGF=1 AT+CMGS="+8801671234567" Name: Sample Name Amount1: 1000.....
Here are my codes,
public ActionResult SendSms(int RentId=0)
{
AmountInfo BillTable = db.AmountInfoes.Find(RentId);
var GetName = db.AmountInfoes.Where(a => a.serial.Equals(BillTable.serial)).FirstOrDefault();
string getName = GetName.name;
int getAmount1 = GetName.amount1;
int getAmount2 = GetName.amount2;
int getAmount3 = GetName.amount3;
int getAmount4 = GetName.amount4;
int getAmount5 = GetName.amount5;
int getAmount6 = GetName.amount6;
string getNumber = GetName.phone;
try
{
SP.PortName = "COM8";
SP.Close();
SP.Open();
string ph_no;
string the_no = getNumber;
string txt_msg = "Name: " + getName + " Amount1: " + getAmount1 + " Amount2: " + getAmount2 + " Amount3: " + getAmount3 + " Amount4: " + getAmount4 + " Amount5: " + getAmount5 + " Amount6: " + getAmount6;
ph_no = Char.ConvertFromUtf32(34) + the_no + char.ConvertFromUtf32(34);
SP.Write("AT+CMGF=1" + Char.ConvertFromUtf32(13));
SP.Write("AT+CMGS=" + ph_no + Char.ConvertFromUtf32(13));
SP.Write(txt_msg + Char.ConvertFromUtf32(26) + Char.ConvertFromUtf32(13));
SP.Close();
}
catch (Exception ex)
{
throw ex;
}
return RedirectToAction("RentManager");
}
Is there something wrong in my code? How can I fix this problem where AT commands will not appear in my sms? Need this help badly. Thanks.
I am creating my first windows store app and i have several web service calls during startup and also periodically through the app. However I have noticed that my app will ot start/crashes or just closes down when I don't have internet access because of the web serivice calls. I want my app to start up in normal way with some initial data and seem normal even when there is no internet access. The data I get from webservice are mostly weather data that I show in various textboxes and graphs.
The code below shows the webservice calls in my extended splash screen.
public sealed partial class ExtendedSplashScreen : Page
{
//parameterItem max1DayAgo = new parameterItem();
//parameterItem min1DayAgo = new parameterItem();
public ExtendedSplashScreen()
{
this.InitializeComponent();
}
/// <summary>
/// Invoked when this page is about to be displayed in a Frame.
/// </summary>
/// <param name="e">Event data that describes how this page was reached. The Parameter
/// property is typically used to configure the page.</param>
protected override async void OnNavigatedTo(NavigationEventArgs e)
{
string[] periodSelector = { "1DayAgo", "1WeekAgo", "1MonthAgo" };
string[] modeSelector = { "max", "min" };
string[] parameterSelector = { "umtTemp1", "umtWindSpeed", "umtAdjBaromPress", "umtRainRate" };
//Create a webservice object
ServiceReference.WebServiceSoapClient webServiceObj = new ServiceReference.WebServiceSoapClient();
//First we create an object that holds max data for yesterday
var getMax1DayAgoObj = await webServiceObj.GetSelectedMaxMinDataAsync(parameterSelector, periodSelector[0], modeSelector[0]);
//create an object that holds min data for yesterday
var getMin1DayAgoObj = await webServiceObj.GetSelectedMaxMinDataAsync(parameterSelector, periodSelector[0], modeSelector[1]);
//Save arrayOfValue and arrayOfUnit to a parameterItem object. these objects are created during startup
// and the can be accessed and updated by all methods in this page later we will see that maxMinButton_Click method
//for the maxMinButton will use these data
//create an object that holds max data for last week
var getMax1WekAgoObj = await webServiceObj.GetSelectedMaxMinDataAsync(parameterSelector, periodSelector[1], modeSelector[0]);
//create an object that holds min data for last week
var getMin1WekAgoObj = await webServiceObj.GetSelectedMaxMinDataAsync(parameterSelector, periodSelector[1], modeSelector[1]);
//create an object that holds max data for last month
var getMax1MonthAgoObj = await webServiceObj.GetSelectedMaxMinDataAsync(parameterSelector, periodSelector[2], modeSelector[0]);
//create an object that holds min data for last month
var getMin1MonthAgoObj = await webServiceObj.GetSelectedMaxMinDataAsync(parameterSelector, periodSelector[2], modeSelector[1]);
(App.Current as App).max1DayAgo.arrayOfValue = getMax1DayAgoObj.arrayOfValue;
(App.Current as App).max1DayAgo.arrayOfUnit = getMax1DayAgoObj.arrayOfUnit;
(App.Current as App).min1DayAgo.arrayOfValue = getMin1DayAgoObj.arrayOfValue;
(App.Current as App).min1DayAgo.arrayOfUnit = getMin1DayAgoObj.arrayOfUnit;
(App.Current as App).max1WeekAgo.arrayOfValue = getMax1WekAgoObj.arrayOfValue;
(App.Current as App).max1WeekAgo.arrayOfUnit = getMax1WekAgoObj.arrayOfUnit;
(App.Current as App).min1WeekAgo.arrayOfValue = getMin1WekAgoObj.arrayOfValue;
(App.Current as App).min1WeekAgo.arrayOfUnit = getMin1WekAgoObj.arrayOfUnit;
(App.Current as App).max1MonthAgo.arrayOfValue = getMax1MonthAgoObj.arrayOfValue;
(App.Current as App).max1MonthAgo.arrayOfUnit = getMax1MonthAgoObj.arrayOfUnit;
(App.Current as App).min1MonthAgo.arrayOfValue = getMin1MonthAgoObj.arrayOfValue;
(App.Current as App).min1MonthAgo.arrayOfUnit = getMin1MonthAgoObj.arrayOfUnit;
string[] startupData = new string[13];
startupData[0] = " " + (App.Current as App).max1DayAgo.arrayOfValue[0] + " " + (App.Current as App).max1DayAgo.arrayOfUnit[0]; // maxTemp
startupData[1] = " " + (App.Current as App).max1DayAgo.arrayOfValue[1] + " " + (App.Current as App).max1DayAgo.arrayOfUnit[1]; // maxWindSped
startupData[2] = " " + (App.Current as App).max1DayAgo.arrayOfValue[2] + " " + (App.Current as App).max1DayAgo.arrayOfUnit[2]; // maxAirPressure
startupData[3] = " " + (App.Current as App).max1DayAgo.arrayOfValue[3] + " " + (App.Current as App).max1DayAgo.arrayOfUnit[3];// maxRainfall
startupData[4] = " " + (App.Current as App).min1DayAgo.arrayOfValue[0] + " " + (App.Current as App).min1DayAgo.arrayOfUnit[0]; // minTemp
startupData[5] = " " + (App.Current as App).min1DayAgo.arrayOfValue[1] + " " + (App.Current as App).min1DayAgo.arrayOfUnit[1];// minWindSped
startupData[6] = " " + (App.Current as App).min1DayAgo.arrayOfValue[2] + " " + (App.Current as App).min1DayAgo.arrayOfUnit[2];// minAirPressure
startupData[7] = " " + (App.Current as App).min1DayAgo.arrayOfValue[3] + " " + (App.Current as App).min1DayAgo.arrayOfUnit[3];// minRainfall
// Main fields
// ServiceReference.WebServiceSoapClient webServiceObj = new ServiceReference.WebServiceSoapClient();
var getLatestTempObj = await webServiceObj.GetLatestDataAsync("umtTemp1");
var getLatestWindObj = await webServiceObj.GetLatestDataAsync("umtWindSpeed");
var getLatestwindDirObj = await webServiceObj.GetLatestDataAsync("umtAdjWinDir");
var getLatestairPressureObj = await webServiceObj.GetLatestDataAsync("umtAdjBaromPress");
startupData[8] = " " + getLatestTempObj.Value + " " + getLatestTempObj.Unit;//temperatureMainTxtBlock.Text
startupData[9] = " " + getLatestWindObj.Value + " " + getLatestWindObj.Unit;//temperatureMainTxtBlock.Text
startupData[10] = "" + getLatestwindDirObj.Value; //temperatureMainTxtBlock.Text
startupData[11] = " " + getLatestairPressureObj.Value + " " + getLatestairPressureObj.Unit;//temperatureMainTxtBlock.Text
startupData[12] = "Last update: " + getLatestwindDirObj.Timestamp;//temperatureMainTxtBlock.Text
//save the startup data to the global variables
(App.Current as App).NavigateData = startupData;
this.Frame.SetNavigationState(e.Parameter as string);
this.Frame.Navigate(typeof(MainPage));
}
}
An approach we have in some of our team based apps is prior to any call to return data of the net, the network status is checked. Example:
async Task RefreshFromWeb(...)
{
if (!App.HasInternetAccess)
{
await new Windows.UI.Popups.MessageDialog(Strings.NoInternetWarning).ShowAsync();
return;
}
//attempt access here
}
public static bool HasInternetAccess
{
get
{
var profile = Windows.Networking.Connectivity.NetworkInformation.GetInternetConnectionProfile();
if (profile == null)
return false;
return profile.GetNetworkConnectivityLevel() ==
Windows.Networking.Connectivity.NetworkConnectivityLevel.InternetAccess;
}
}
We also took another approach at times which was very similar but uses await and returns true or false (the same could easily be done above, that approach above just gives the dialog)
public static async System.Threading.Tasks.Task HasInternet()
{
var profile = Windows.Networking.Connectivity.NetworkInformation.GetInternetConnectionProfile();
var hasNetAccess = profile != null;
if (!hasNetAccess)
await new Windows.UI.Popups.MessageDialog(
content: InfoHub.AppHubViewModel.Strings.NoInternetWarning,
title: InfoHub.AppHubViewModel.Strings.NoInternetWarning).ShowAsync();
return hasNetAccess;
}
async void YourControlEvent_Click(object sender, ItemClickEventArgs e)
{
//if net access, do your stuff, otherwise ignore for now
if (await IsInternet())
{
//do net calls here
}
}
You need to implement some exception handling around this line:
ServiceReference.WebServiceSoapClient webServiceObj = new ServiceReference.WebServiceSoapClient();
and implement a fallback that will work in off-line mode, i.e. retrieve data from a cache.
You can use NetworkStatusChanged event in App.xaml.cs and then you can declare one static variable and use it to check whether Internet is available or not. If Internet is available do your desired operation otherwise show error message.
public static bool IsInternetAvailable;
void NetworkInformation_NetworkStatusChanged(object sender)
{
if (NetworkInformation.GetInternetConnectionProfile() != null)
App.IsInternetAvailable = true;
else
App.IsInternetAvailable = false;
}
Always use try catch blocks, when you have probability of exception.
I am fairly new to C# and I have written several functioning programs, but all of them have been single thread applications. This is my first multi-threaded application and I am struggling to resolve this "Cross-thread operation not valid: Control 'cbLogType' accessed from a thread other than the one it was created on" error. My application searches Windows Event viewer for a user defined Event ID in a user defined Event Log Source(cbLogType). I am using a backgroundworker process to do all the work and I am using the worker.reportprogress to update a label, however, I receive the above error when debugging. I have tried several Invoke methods, but none seem to resolve my error. I have also tried removing the combobox and setting the Log Source directly in the code, which works to an extent, but still fails. I have included my code and any help would be greatly appreciated. I suspect that I might not be using the Invoke method correctly. Thanks in advance!
CODE:
private void bgWorker1_DoWork(object sender, DoWorkEventArgs e)
{
BackgroundWorker worker = sender as BackgroundWorker;
{
if (File.Exists(#"C:\Events.log"))
MessageBox.Show("File 'Events.log' already exists. All new data will be appended to the log file!", "Warning!");
string message = string.Empty;
string eventID = (tbEventID.Text);
string text;
EventLog eLog = new EventLog();
Invoke((MethodInvoker)delegate() { text = cbLogType.Text; });
eLog.Source = (this.cbLogType.Text); // I am receiving the error here
eLog.MachineName = ".";
int EventID = 0;
string strValue = string.Empty;
strValue = tbEventID.Text.Trim();
//string message = string.Empty;
EventID = Convert.ToInt32(strValue); // Convert string to integer
foreach (EventLogEntry entry in eLog.Entries)
{
int entryCount = 1;
if (cbDateFilter.Checked == true)
{
if (entry.TimeWritten > dtPicker1.Value && entry.TimeWritten < dtPicker2.Value)
if (entry.InstanceId == EventID)
message = "Event entry matching " + (tbEventID.Text) + " was found in " + (cbLogType.Text);
using (StreamWriter writer = new StreamWriter(#"C:\Events.log", true))
writer.WriteLine("EventID: " + entry.InstanceId +
"\r\nDate Created: " + entry.TimeWritten +
"\r\nEntry Type: " + entry.EntryType +
"\r\nMachinename: " + entry.MachineName +
"\r\n" +
"\r\nMessage: " + entry.Message +
"\r\n");
if (entry.InstanceId != EventID)
message = "No event ids matching " + (tbEventID.Text) + " was found in " + (cbLogType.Text);
}
else
{
if (cbDateFilter.Checked == false)
{
if (entry.InstanceId == EventID)
using (StreamWriter writer = new StreamWriter(#"C:\Events.log", true))
writer.WriteLine("EventID: " + entry.InstanceId +
"\r\nDate Created: " + entry.TimeWritten +
"\r\nEntry Type: " + entry.EntryType +
"\r\nMachinename: " + entry.MachineName +
"\r\n" +
"\r\nMessage: " + entry.Message +
"\r\n");
else if (entry.InstanceId != EventID)
message = "No event ids matching " + (tbEventID.Text) + " was found in " + (cbLogType.Text);
}
bgWorker1.ReportProgress((entryCount) * 10, message);
entryCount++;
}
}
}
}
private void bgWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
lblStat.Text = e.UserState.ToString();
}
You're accessing cbLogType in a non-UI thread.
Change to
eLog.Source = text;