EventLogQuery not pulling results - c#

Edit: ok I know the query is incorrect. When I remove the TimeCreated part I get results back. What is the proper way to pull all events for that given day?
startTime = DateTime.Now.Date
string query = "*[System/Level=1 or System/Level=2] and TimeCreated[#SystemTime >= '" + startTime + "']";
using (EventLogSession session = new EventLogSession(serverName))
{
EventLogQuery eventQuery = new EventLogQuery(logName, PathType.LogName, query);
eventQuery.Session = session;
using (EventLogReader reader = new EventLogReader(eventQuery))
{
for (EventRecord eventDetail = reader.ReadEvent(); eventDetail != null; eventDetail = reader.ReadEvent())
{
entries.Add(eventDetail);
}
}
}
I have tired the following as well
"*[System/Level=1 or System/Level=2] and *[System/TimeCreated[#SystemTime >= '" + startTime + "']]";
"*[System[(Level=1) or System[(Level=2)] and TimeCreated[#SystemTime >= '" + startTime.ToUniversalTime().ToString("o") + "']]";

Here I made a helper to retrieve log from the event viewer, you can parametrized it quite easily
public static void WriteEventViewerHistoryByTypes(IList<EventViewerCriticalityLevel> levelTypes, string logType, string filePath, IList<string> sources, DateTime? startDate = new System.Nullable<DateTime>(), DateTime? endDate = new System.Nullable<DateTime>())
{
if (levelTypes == null || levelTypes.Count == 0)
levelTypes = new List<EventViewerCriticalityLevel> { EventViewerCriticalityLevel.Comment, EventViewerCriticalityLevel.Error, EventViewerCriticalityLevel.Fatal, EventViewerCriticalityLevel.Info, EventViewerCriticalityLevel.Warning };
StringBuilder sb = new StringBuilder();
sb.Append("<QueryList>");
sb.AppendFormat("<Query Id=\"0\" Path=\"{0}\">", logType);
sb.AppendFormat(" <Select Path=\"{0}\">", logType);
sb.AppendFormat(" *[System[(");
sb.AppendFormat("({0})", string.Join(" or ", levelTypes.Select(lev =>
{
if (lev == EventViewerCriticalityLevel.Info)
return string.Format("Level={0} or Level=0", (int)lev);
else
return string.Format("Level={0}", (int)lev);
})));
if (sources != null && sources.Count > 0)
{
sb.AppendFormat(" or ");
sb.AppendFormat("(Provider[{0}])", string.Join(" or ", sources.Select(el => "#Name='" + el + "'")));
}
sb.AppendFormat(")");
if (startDate.HasValue)
{
sb.AppendFormat(" and TimeCreated[#SystemTime >= '{0}']", startDate.Value.ToString("o"));
}
if (endDate.HasValue)
{
sb.AppendFormat(" and TimeCreated[#SystemTime <= '{0}']", endDate.Value.ToString("o"));
}
sb.AppendFormat("]]");
sb.AppendFormat(" </Select>");
sb.AppendFormat("</Query>");
sb.Append("</QueryList>");
try
{
EventLogSession sess = new EventLogSession();
sess.ExportLogAndMessages(logType, PathType.LogName, sb.ToString(), filePath, true, CultureInfo.CurrentCulture);
}
catch (Exception ex)
{
throw ex;
}
}
And here the enum
public enum EventViewerCriticalityLevel
{
Fatal = 1,
Error = 2,
Warning = 3,
Info = 4,
Comment = 5
}
It will generate evtx files that you can read with the event viewer console.
Hope it helps !

Related

Excel data reading from Stream and save to the database

In my asp.net MVC application, There is an option to upload data from an excel file. For that, I have used this on my controller.
public ActionResult ImportEmpDetails(HttpPostedFileBase excelFile)
{
try
{
if (excelFile.ContentLength == 0 || excelFile == null)
{
ViewBag.Error = "Please select the excel file";
return View("EmpDetails");
}
else
{
if (excelFile.FileName.EndsWith("xls") || excelFile.FileName.EndsWith("xlsx"))
{
string path = Server.MapPath("~/ExcelFile/" + excelFile.FileName);
if (System.IO.File.Exists(path)) System.IO.File.Delete(path);
excelFile.SaveAs(path);
ExcelPath = Server.MapPath("~/ExcelFile/") + path;
Microsoft.Office.Interop.Excel.Application application = new Microsoft.Office.Interop.Excel.Application();
Microsoft.Office.Interop.Excel.Workbook workbook = application.Workbooks.Open(path);
Microsoft.Office.Interop.Excel.Worksheet worksheet = workbook.ActiveSheet;
Microsoft.Office.Interop.Excel.Range range = worksheet.UsedRange;
List<EmpDetailsVM> xcel = new List<EmpDetailsVM>();
for (int i = 2; i <= range.Rows.Count; i++)
{
try
{
EmpDetails emp = new EmpDetails();
int EmpNo = int.Parse(((Microsoft.Office.Interop.Excel.Range)range.Cells[i, 1]).Text);
var EmpId = (from c in db.CreateEmployee where c.EmpNo == EmpNo select c.Id).First();
emp.EmpID = EmpId;
emp.YearOfService = decimal.Parse(((Microsoft.Office.Interop.Excel.Range)range.Cells[i, 2]).Text);
emp.BasicSalary = decimal.Parse(((Microsoft.Office.Interop.Excel.Range)range.Cells[i, 3]).Text);
emp.EmpCatagory = ((Microsoft.Office.Interop.Excel.Range)range.Cells[i, 4]).Text;
emp.EmpGrade = ((Microsoft.Office.Interop.Excel.Range)range.Cells[i, 5]).Text;
int SupervisorId = int.Parse(((Microsoft.Office.Interop.Excel.Range)range.Cells[i, 6]).Text);
var SupId = (from h in db.CreateEmployee where h.EmpNo == SupervisorId select h.Id).First();
emp.SupervisorId = SupId;
EmpDetailsVM data = new EmpDetailsVM();
data.EmpID = emp.EmpID;
data.YearOfService = emp.YearOfService;
data.BasicSalary = emp.BasicSalary;
data.EmpCatagory = emp.EmpCatagory;
data.EmpGrade = emp.EmpGrade;
data.SupervisorId = emp.SupervisorId;
xcel.Add(data);
}
catch (Exception ex)
{
ViewBag.Error = "Error in " + i + " record";
return View("EmpDetails");
}
}
if (xcel != null)
{
try
{
foreach (var item in xcel)
{
int empID = item.EmpID;
decimal yearOfService = item.YearOfService;
decimal basicSalary = item.BasicSalary;
string catagory = item.EmpCatagory;
string grade = item.EmpGrade;
int supId = item.SupervisorId;
var isEmployeeExists = (from e in dbs.EmpDetails where e.EmpID == empID select e.Id).ToList();
int EmpCount = isEmployeeExists.Count();
if (EmpCount == 0)
{
EmpDetails e = new EmpDetails();
e.EmpID = empID;
e.YearOfService = yearOfService;
e.BasicSalary = basicSalary;
e.EmpCatagory = catagory;
e.EmpGrade = grade;
e.SupervisorId = supId;
dbs.EmpDetails.Add(e);
dbs.SaveChanges();
}
else
{
EmpDetails EmpDetails = dbs.EmpDetails.Where(x => x.EmpID == empID).First();
EmpDetails.YearOfService = yearOfService;
EmpDetails.BasicSalary = basicSalary;
EmpDetails.EmpCatagory = catagory;
EmpDetails.EmpGrade = grade;
EmpDetails.SupervisorId = supId;
db.SaveChanges();
}
}
}
catch (Exception ex)
{
ViewBag.Error = "Error " + ex;
}
TempData["msg"] = "success";
return View("EmpDetails", xcel);
}
else
{
}
return View("EmpDetails");
}
else
{
ViewBag.Error = "Selected excel file not supported";
return View("EmpDetails");
}
}
}
catch (Exception ex)
{
string message = string.Format("<b>Message:</b> {0}<br /><br />", "You do not have access to this view");
message += string.Format("<b>StackTrace:</b> {0}<br /><br />", ex.StackTrace.Replace(Environment.NewLine, string.Empty));
message += string.Format("<b>Source:</b> {0}<br /><br />", ex.Source.Replace(Environment.NewLine, string.Empty));
message += string.Format("<b>TargetSite:</b> {0}", ex.TargetSite.ToString().Replace(Environment.NewLine, string.Empty));
ModelState.AddModelError("Id", message);
}
return View("EmpDetails");
}
This is working properly when I debug the code and run from it using VS. When I applied to the live version, can't upload the excel file there is an exception triggering You do not have access to this view
Want to know how to prevent this or how to do same using stream ?

Issues starting an Async Method from the OnCreate Overriden Method

Within OnCreate()
new Thread(new ThreadStart(() => {
this.RunOnUiThread(async () =>
{
await SetData(TodaysDate); ;
//await FindNotesForDay(TodaysDate, TodaysDate.AddDays(+6));
progress.Dismiss();
});
})).Start();
private async Task SetData(DateTime date)
{
await Task.Run(() =>
{
dicMyMap = null;
dicMyMap = new Dictionary<string, List<ClassInstance>>();
List<string> group = new List<string>();
group.Add("Monday");
group.Add("Tuesday");
group.Add("Wednesday");
group.Add("Thursday");
group.Add("Friday");
dicMyMap.Add(group[0], ListsPopulation(date.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture)));
date = date.AddDays(+1);
dicMyMap.Add(group[1], ListsPopulation(date.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture)));
date = date.AddDays(+1);
dicMyMap.Add(group[2], ListsPopulation(date.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture)));
date = date.AddDays(+1);
dicMyMap.Add(group[3], ListsPopulation(date.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture)));
date = date.AddDays(+1);
dicMyMap.Add(group[4], ListsPopulation(date.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture)));
myAdapater = new ExpandableListViewAdapter(this, group, dicMyMap);
expandableListView.SetAdapter(myAdapater);
});
}
private List<ClassInstance> ListsPopulation(String date)
{
string sql = "SELECT * FROM lectures join groupConvert using (Groups) where StartDate = '" + date + "' AND Cohort = '" + User.Cohort + "' AND Year = '" + User.IntakeYear + "';";
List<ClassInstance> Temp = new List<ClassInstance>();
//Insert Header
Temp.Add(new ClassInstance("Start Time", "End Time", "Subject", "Location", "", ""));
using (MySqlCommand cmd = new MySqlCommand(sql, Connect.GetConnection()))
{
MySqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
ClassInstance c = new ClassInstance(reader["StartTime"].ToString(), reader["EndTime"].ToString(), reader["Theme"].ToString(), reader["Location"].ToString(), reader["Essential"].ToString(), reader["Notes"].ToString());
Temp.Add(c);
}
}
if (Temp.Count == 1)
{
Temp.Clear();
Temp.Add(new ClassInstance("No Classes", "", "", "", "", ""));
}
return Temp;
}
Hello
I am currently attempting to populate a ListView from a database hosted on AWS. As you can imagine It takes a bit of time to load. My issue is my current code is throwing an error. The error thrown is ambiguous and not helpful just states the program has crashed.
In essence what i want to do is quite simple, I basically want to just display a dialog while these methods are loading.
Any advice regarding my code would be excellent.
Edit: I have narrowed the error message down to this area of the code. Prior to attempting to use threads I was able to load this Activity however due to the fact there wasn't a loading message it would appear to the user that the activity had frozen rather than the fact it was loading.
Thanks,
Joe
So i managed to fix the code above to run correctly.
If you have any feedback or comments let me know and i hope someone finds this helpful.
I was using the Async methods completely incorrectly, you are also unable to call a Async method from the oncreate as i'm sure you are aware. Part of my solution was to change all the methods which i had made Async incorrectly back to void (Meaning they were synchronous).
I then created a thread to run the commands and they are now finally running in the correct order :).
Its important to note within the Thread any elements affected by the UI will required them to be run using the main UI thread, this applies to the methods they called as well.
Below is the area of code which i created to fix the issue i had
// Try catch attempt to catch all errors, the error dialog thrown within
//the catch is fairly simple
try
{
//Start loading spinner
var LoadingProgressDialog = ProgressDialog.Show(this, "Loading", "Loading", false);
//Start loading thread, this thread will carry out the functions
// in the order you requested
Thread LoadingThread = new Thread(() =>
{
//Line below only relevant to my code
StartMonday.Text = "Week Commencing On " + TodaysDate.ToLongDateString();
// Call this method first
SetData(TodaysDate);
// call this method second
FindNotesForWeek(TodaysDate, 7);
//Update the UI on the main thread but call third this will close the loading dialog message
RunOnUiThread(() => LoadingProgressDialog.Hide());
// End of thread
});
//Run the thread
LoadingThread.Start();
}
catch (Exception e)
{
var ErrorMessageDialog = ProgressDialog.Show(this, "Loading", e.ToString(), false);
}
Below is my complete class for reference for another user. I have not doced this code as its large enough within this comment
namespace MedicalHubApplication
{
[Activity(Label = "TimeTable", NoHistory = true)]
public class TimeTable : Activity
{
ClassInstance populateClass = new ClassInstance();
UserInstance User = new UserInstance();
GetConnectionClass Connect = new GetConnectionClass();
Dictionary<string, List<ClassInstance>> dicMyMap;
TextView DateHeaderTV;
TextView NoteHeaderTV;
ExpandableListViewAdapter myAdapater;
ExpandableListView expandableListView;
// Need Instance of List
NotesListViewAdapter myNoteAdapater;
ListView NotesListView;
ScrollView ScrollViewList;
TextView StartMonday;
Button SelectDateButton;
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
// Create your application here
SetContentView(Resource.Layout.TimeTable);
expandableListView = FindViewById<ExpandableListView>(Resource.Id.ListViewExpanded);
StartMonday = FindViewById<TextView>(Resource.Id.TextViewStartDateMonday);
SelectDateButton = FindViewById<Button>(Resource.Id.SelectDateButton);
NotesListView = FindViewById<ListView>(Resource.Id.NotesListView);
DateHeaderTV = FindViewById<TextView>(Resource.Id.DateHeader);
NoteHeaderTV = FindViewById<TextView>(Resource.Id.NoteHeader);
ScrollViewList = FindViewById<ScrollView>(Resource.Id.ScrollView);
// Populate User
User = JsonConvert.DeserializeObject<UserInstance>(Intent.GetStringExtra("User"));
//Find Monday
DateTime TodaysDate = DateTime.Now;
while (TodaysDate.DayOfWeek != DayOfWeek.Monday) TodaysDate = TodaysDate.AddDays(-1);
try
{
var LoadingProgressDialog = ProgressDialog.Show(this, "Loading", "Loading", false);
Thread LoadingThread = new Thread(() =>
{
StartMonday.Text = "Week Commencing On " + TodaysDate.ToLongDateString();
SetData(TodaysDate);
FindNotesForWeek(TodaysDate, 7);
RunOnUiThread(() => LoadingProgressDialog.Hide());
});
LoadingThread.Start();
}
catch (Exception e)
{
var ErrorMessageDialog = ProgressDialog.Show(this, "Loading", e.ToString(), false);
}
SelectDateButton.Click += delegate
{
DateSelectOnClick();
};
}
private void DateSelectOnClick()
{
DatePickerFragment frag = DatePickerFragment.NewInstance(delegate (DateTime SelectedDate)
{
while (SelectedDate.DayOfWeek != DayOfWeek.Monday) SelectedDate = SelectedDate.AddDays(-1);
try
{
var LoadingProgressDialog = ProgressDialog.Show(this, "Loading", "Loading", false);
Thread LoadingThread = new Thread(() =>
{
RunOnUiThread(() => StartMonday.Text = "Week Commencing On " + SelectedDate.ToLongDateString());
SetData(SelectedDate);
FindNotesForWeek(SelectedDate, 7);
RunOnUiThread(() => LoadingProgressDialog.Hide());
});
LoadingThread.Start();
}
catch (Exception e)
{
var ErrorMessageDialog = ProgressDialog.Show(this, "Loading", e.ToString(), false);
}
});
frag.Show(FragmentManager, DatePickerFragment.TAG);
}
private void SetData(DateTime date)
{
dicMyMap = null;
dicMyMap = new Dictionary<string, List<ClassInstance>>();
List<string> group = new List<string>();
group.Add("Monday");
group.Add("Tuesday");
group.Add("Wednesday");
group.Add("Thursday");
group.Add("Friday");
dicMyMap.Add(group[0], ListsPopulation(date.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture)));
date = date.AddDays(+1);
dicMyMap.Add(group[1], ListsPopulation(date.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture)));
date = date.AddDays(+1);
dicMyMap.Add(group[2], ListsPopulation(date.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture)));
date = date.AddDays(+1);
dicMyMap.Add(group[3], ListsPopulation(date.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture)));
date = date.AddDays(+1);
dicMyMap.Add(group[4], ListsPopulation(date.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture)));
myAdapater = new ExpandableListViewAdapter(this, group, dicMyMap);
RunOnUiThread(() => expandableListView.SetAdapter(myAdapater));
}
private List<ClassInstance> ListsPopulation(String date)
{
string sql = "SELECT * FROM lectures join groupConvert using (Groups) where StartDate = '" + date + "' AND Cohort = '" + User.Cohort + "' AND Year = '" + User.IntakeYear + "';";
List<ClassInstance> Temp = new List<ClassInstance>();
//Insert Header
Temp.Add(new ClassInstance("Start Time", "End Time", "Subject", "Location", "", ""));
using (MySqlCommand cmd = new MySqlCommand(sql, Connect.GetConnection()))
{
MySqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
ClassInstance c = new ClassInstance(reader["StartTime"].ToString(), reader["EndTime"].ToString(), reader["Theme"].ToString(), reader["Location"].ToString(), reader["Essential"].ToString(), reader["Notes"].ToString());
Temp.Add(c);
}
}
if (Temp.Count == 1)
{
Temp.Clear();
Temp.Add(new ClassInstance("No Classes", "", "", "", "", ""));
}
return Temp;
}
private void FindNotesForWeek(DateTime StartDate, int DaysInMonth)
{
List<NotesInstance> WeekNotes = new List<NotesInstance>();
WeekNotes.AddRange(FindNotesForDay(StartDate, StartDate.AddDays(+DaysInMonth)));
if (WeekNotes.Count != 0)
{
RunOnUiThread(() => NoteHeaderTV.Visibility = ViewStates.Visible);
RunOnUiThread(() => NotesListView.Visibility = ViewStates.Visible);
RunOnUiThread(() => DateHeaderTV.Text = "Date:");
myNoteAdapater = new NotesListViewAdapter(this, WeekNotes);
RunOnUiThread(() => NotesListView.Adapter = myNoteAdapater);
}
else
{
RunOnUiThread(() => NoteHeaderTV.Visibility = ViewStates.Invisible);
RunOnUiThread(() => NotesListView.Visibility = ViewStates.Invisible);
RunOnUiThread(() => DateHeaderTV.Text = "No Notifications");
}
// Set up Adapter
myNoteAdapater = new NotesListViewAdapter(this, WeekNotes);
RunOnUiThread(() => NotesListView.Adapter = myNoteAdapater);
}
private List<NotesInstance> FindNotesForDay(DateTime StartDate, DateTime EndDate)
{
string sql = "SELECT * FROM Notes WHERE dates between '" + StartDate.ToString("yyyy-MM-dd") + "' AND '" + EndDate.ToString("yyyy-MM-dd") + "' AND yearGroup = '" + User.IntakeYear.ToString() + "';";
List<NotesInstance> Temp = new List<NotesInstance>();
using (MySqlCommand cmd = new MySqlCommand(sql, Connect.GetConnection()))
{
MySqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
NotesInstance c = new NotesInstance(reader.GetDateTime("dates").ToString("dd-MM-yyyy"), reader["Notes"].ToString());
Temp.Add(c);
}
}
return Temp;
}
}
}

How to implement "apply credit" to existing invoices if credits are available for that customer via .Net C# code by using Interop.QBFC13Lib.dll?

I got stuck when trying to implement the "apply credit" functionality of Quickbooks to existing invoices if credit is available for that customer. I am able to do it via Quickbooks Desktop UI but not getting the way to implement it via a .Net integrated app, written in C#. Can any one please guide on this.
Code which I am using to implement "apply credit" to Quickbooks via C# code.
I am getting the error: "QuickBooks found an error when parsing the provided XML text stream." with below code.
public void ApplyCreditsOnPrePayInvoices()
{
// open connection and begin session before data fetch - intentionally skipped this code
IMsgSetRequest msgset = null;
ICreditMemoQuery creditMemoQuery = null;
string sCustomerName = string.Empty;
if (this.GetConnectedToQB()) //this is the method call to login to quickbooks desktop
{
try
{
// during data fetch
msgset = m_sessionManager.CreateMsgSetRequest("US", 8, 0);
creditMemoQuery = msgset.AppendCreditMemoQueryRq();
creditMemoQuery.ORTxnQuery.TxnFilter.ORDateRangeFilter.ModifiedDateRangeFilter.FromModifiedDate.SetValue(new DateTime(2012, 3, 31), false);
IMsgSetResponse msgRes = m_sessionManager.DoRequests(msgset);
IResponseList responseList = msgRes.ResponseList;
if (responseList.Count > 0)
{
IResponse response = responseList.GetAt(0);
ICreditMemoRetList creditMemoList = response.Detail as ICreditMemoRetList;
if (creditMemoList == null)
{
return;
}
for (int i = 0; i <= creditMemoList.Count - 1; i++)
{
ICreditMemoRet qbCreditMemo = creditMemoList.GetAt(i);
if (this.GetQBCustomerListId(qbCreditMemo.CustomerRef.FullName.GetValue()) != string.Empty)
{
m_requestMsgSet.ClearRequests();
m_requestMsgSet.Attributes.OnError = ENRqOnError.roeContinue;
IInvoiceAdd invoiceAddRq = m_requestMsgSet.AppendInvoiceAddRq();
invoiceAddRq.CustomerRef.FullName.SetValue(qbCreditMemo.CustomerRef.FullName.GetValue());
ISetCredit SetCredit1 = invoiceAddRq.SetCreditList.Append();
SetCredit1.CreditTxnID.SetValue(qbCreditMemo.TxnID.GetValue());
SetCredit1.AppliedAmount.SetValue(qbCreditMemo.TotalAmount.GetValue());
IMsgSetResponse responseSetInvoice = m_sessionManager.DoRequests(m_requestMsgSet);
DataSet dsInvoice = this.GetExtractResponseFromQB(responseSetInvoice);
string sQueryResponse = Stringcl.GetValue(dsInvoice.Tables["InvoiceAddRs"].Rows[0]["statusMessage"]);
if (sQueryResponse == "Status OK")
{
Console.WriteLine("Credit no.:" + qbCreditMemo.TxnID.GetValue() + " Customer:" + qbCreditMemo.CustomerRef.FullName.GetValue() + " Total:" + qbCreditMemo.TotalAmount.GetValue());
}
}
}
}
}
catch (Exception ex)
{
string ss = ex.Message;
//handle exception here
}
finally
{
if (msgset != null)
{
Marshal.FinalReleaseComObject(msgset);
}
if (creditMemoQuery != null)
{
Marshal.FinalReleaseComObject(creditMemoQuery);
}
}
}
// end session and close connection after data fetch - intentionally skipped this code
}
Thanks in advance!!
I got solution by using below function:-
public void ApplyCreditsOnPrePayInvoices(string sMonth, string sYear)
{
IMsgSetRequest IMsgSetRequestToQB = null;
ICreditMemoQuery ICreditMemoQueryToQB = null;
string sInvoiceTxnId = string.Empty;
string sInvoiceNumber = string.Empty;
if (this.GetConnectedToQB())
{
try
{
IMsgSetRequestToQB = m_sessionManager.CreateMsgSetRequest("US", 8, 0);
ICreditMemoQueryToQB = IMsgSetRequestToQB.AppendCreditMemoQueryRq();
ICreditMemoQueryToQB.ORTxnQuery.TxnFilter.ORDateRangeFilter.ModifiedDateRangeFilter.FromModifiedDate.SetValue(DateTimecl.GetValue("1." + sMonth + sYear), true);
IMsgSetResponse IMsgSetResponseFromQB = m_sessionManager.DoRequests(IMsgSetRequestToQB);
IResponseList ICreditListMemoAvailable = IMsgSetResponseFromQB.ResponseList;
if (ICreditListMemoAvailable.Count > 0)
{
string sCustomerListIdQB = string.Empty;
string sCustomerAccountNumber = string.Empty;
string sQBImportPrepayAccounts = Path.Combine(Environment.CurrentDirectory, sMonth + sYear, "Step11_QBImport_PrepayAccounts.csv");
DataTable dtQBImportPrepayAccounts = Utilcl.GetDataTableFromCSVFile(sQBImportPrepayAccounts);
IResponse ICreditMemoAvailable = ICreditListMemoAvailable.GetAt(0);
ICreditMemoRetList iCreditMemoList = ICreditMemoAvailable.Detail as ICreditMemoRetList;
if (iCreditMemoList != null)
{
for (int iCtr = 0; iCtr <= iCreditMemoList.Count - 1; iCtr++)
{
ICreditMemoRet ICreditMemo = iCreditMemoList.GetAt(iCtr);
DataRow[] drInvoiceNos = dtQBImportPrepayAccounts.Select("RefNumber = '" + ICreditMemo.RefNumber.GetValue() + "'");
if (drInvoiceNos.Length > 0)
{
sInvoiceNumber = Stringcl.GetValue(drInvoiceNos[0]["RefNumber"]);
m_requestMsgSet.ClearRequests();
m_requestMsgSet.Attributes.OnError = ENRqOnError.roeContinue;
IReceivePaymentAdd IReceivePayment = m_requestMsgSet.AppendReceivePaymentAddRq();
sInvoiceTxnId = this.GetQBInvoiceTxnIDList(ICreditMemo.CustomerRef.FullName.GetValue()); //To get the Transaction ID of Invoice
IReceivePayment.CustomerRef.FullName.SetValue(Stringcl.GetValue(ICreditMemo.CustomerRef.FullName.GetValue()));
IAppliedToTxnAdd IAppliedToTxnAddress = IReceivePayment.ORApplyPayment.AppliedToTxnAddList.Append();
IAppliedToTxnAddress.TxnID.SetValue(sInvoiceTxnId);
ISetCredit ISetCreditToInvoice = IAppliedToTxnAddress.SetCreditList.Append();
ISetCreditToInvoice.CreditTxnID.SetValue(ICreditMemo.TxnID.GetValue());
ISetCreditToInvoice.AppliedAmount.SetValue(ICreditMemo.TotalAmount.GetValue());
IMsgSetResponse responseApplyCredit = m_sessionManager.DoRequests(m_requestMsgSet);
DataSet dsInvoice = this.GetExtractResponseFromQB(responseApplyCredit);
string sQueryResponse = Stringcl.GetValue(dsInvoice.Tables["ReceivePaymentAddRs"].Rows[0]["statusMessage"]);
if (sQueryResponse != "Status OK")
{
Utilcl.LogMessage("QB Credit Memo Query Response: " + sQueryResponse);
}
}
}
}
}
}
catch (Exception ex)
{
Utilcl.LogMessage(ex);
}
finally
{
if (IMsgSetRequestToQB != null)
{
Marshal.FinalReleaseComObject(IMsgSetRequestToQB);
}
if (ICreditMemoQueryToQB != null)
{
Marshal.FinalReleaseComObject(ICreditMemoQueryToQB);
}
}
}
}

Is my PLINQ code threadsafe?

I have the following code:
static void Main(string[] args)
{
DateTime currentDay = DateTime.Now;
List<Task> taskList = new List<Task>();
List<string> markets = new List<string>() { "amex", "nasdaq", "nyse", "global" };
Parallel.ForEach(markets, market =>
{
Downloads.startInitialMarketSymbolsDownload(market);
}
);
Console.WriteLine("All downloads finished!");
}
public static void startInitialMarketSymbolsDownload(string market)
{
try
{
object valueTypeLock = new object();
List<string> symbolList = new List<string>() { "GOOG", "YHOO", "AAP" }
var historicalGroups = symbolList.AsParallel().Select((x, i) => new { x, i })
.GroupBy(x => x.i / 100)
.Select(g => g.Select(x => x.x).ToArray());
historicalGroups.AsParallel().ForAll(g => {
lock (valueTypeLock) {
getHistoricalStockData(g, market);
}
});
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
Console.WriteLine(ex.StackTrace);
}
}
public static void getHistoricalStockData(string[] symbols, string market)
{
// download data for list of symbols and then upload to db tables
Uri uri;
string url, line;
decimal open = 0, high = 0, low = 0, close = 0, adjClose = 0;
DateTime date;
Int64 volume = 0;
string[] lineArray;
List<string> symbolError = new List<string>();
Dictionary<string, string> badNameError = new Dictionary<string, string>();
System.Net.ServicePointManager.DefaultConnectionLimit = 1000;
Parallel.ForEach(symbols, symbol =>
{
url = "http://ichart.finance.yahoo.com/table.csv?s=" + symbol + "&a=00&b=1&c=1900&d=" + (DateTime.Now.Month - 1) + "&e=" + DateTime.Now.Day + "&f=" + DateTime.Now.Year + "&g=d&ignore=.csv";
uri = new Uri(url);
using (ooplesfinanceEntities entity = new ooplesfinanceEntities())
using (WebClient client = new WebClient())
using (Stream stream = client.OpenRead(uri))
using (StreamReader reader = new StreamReader(stream))
{
entity.Database.Connection.Open();
while (reader.EndOfStream == false)
{
line = reader.ReadLine();
lineArray = line.Split(',');
// if it isn't the very first line
if (lineArray[0] != "Date")
{
switch (market)
{
case "amex":
DailyAmexData amexData = new DailyAmexData();
var amexQuery = from r in entity.DailyAmexDatas.AsParallel().AsEnumerable()
where r.Date == date
select new StockData { Close = r.AdjustedClose };
List<StockData> amexResult = amexQuery.AsParallel().ToList();
if (amexResult.AsParallel().Count() > 0) // **never hits this breakpoint line**
{
// add the row to the table if it isn't there
// now checks for stock splits and updates if necessary
if (amexResult.AsParallel().FirstOrDefault().Close != adjClose)
{
// this means there is a stock split so it needs to have the other adjusted close prices updated
amexResult.AsParallel().FirstOrDefault().Close = adjClose;
}
else
{
continue;
}
}
else
{
// set the data then add it
amexData.Symbol = symbol;
entity.DailyAmexDatas.Add(amexData);
}
break;
default:
break;
}
}
}
// now save everything
entity.SaveChanges();
Console.WriteLine(symbol + " added to the " + market + " database!");
}
}
);
}
Everything starts fine and I get no exceptions but I'm getting no results and the code gets stuck one the line that I marked and the memory keeps shooting up. I figured the problem was with the above code because maybe I was doing something wrong. I just don't know where to start as this is my first time dealing with plinq/parallel processing and the tutorials don't show anything this complex.

How to make meeting (in calendar) in outlook 2007 using C#?

How to make meeting (in calendar) in outlook 2007 using C# ?
thank's in advance
This code sample from MSDN should get you started:
private void SetRecipientTypeForAppt()
{
Outlook.AppointmentItem appt =
Application.CreateItem(
Outlook.OlItemType.olAppointmentItem)
as Outlook.AppointmentItem;
appt.Subject = "Customer Review";
appt.MeetingStatus = Outlook.OlMeetingStatus.olMeeting;
appt.Location = "36/2021";
appt.Start = DateTime.Parse("10/20/2006 10:00 AM");
appt.End = DateTime.Parse("10/20/2006 11:00 AM");
Outlook.Recipient recipRequired =
appt.Recipients.Add("Ryan Gregg");
recipRequired.Type =
(int)Outlook.OlMeetingRecipientType.olRequired;
Outlook.Recipient recipOptional =
appt.Recipients.Add("Peter Allenspach");
recipOptional.Type =
(int)Outlook.OlMeetingRecipientType.olOptional;
Outlook.Recipient recipConf =
appt.Recipients.Add("Conf Room 36/2021 (14) AV");
recipConf.Type =
(int)Outlook.OlMeetingRecipientType.olResource;
appt.Recipients.ResolveAll();
appt.Display(false);
}
MSDN
Create object of outlook app using:
private Microsoft.Office.Interop.Outlook.Application outlookApp =
new Microsoft.Office.Interop.Outlook.Application();
and replace Application.CreateItem in code provided by Kyle Rozendo, with outlookApp.
Hope this will help.
This is probably a bit of an overkill but, here is a method that handles Adding, Updating, Deleting events. It also uses almost every calendar event function possible (recurrence by various types, attendees, responses etc.). If you're interested, let me know, I can explain more. It should work off the bat, but I could have missed something, typing this really fast
////BEGIN OUTLOOK DECLARATIONS
public static dynamic objOutlook = Activator.CreateInstance(Type.GetTypeFromProgID("Outlook.Application"));
public static int appointmentItem = 1;
public static int mailItem = 0;
public static int inboxItem = 6;
public static dynamic mapiNamespace = objOutlook.GetNamespace("MAPI");
public static dynamic inboxFolder = mapiNamespace.GetDefaultFolder(inboxItem);
public static dynamic mailObject = objOutlook.CreateItem(mailItem);
public static dynamic appointmentObject = objOutlook.CreateItem(appointmentItem);
public static string defaultEmail = mapiNamespace.DefaultStore.DisplayName; //mapiNamespace.CurrentUser.DefaultStore.DisplayName;
////END OUTLOOK DECLARATIONS
public static string CreateAppointmentOutlookDirect(char StatusType, int ID, string EventID, string EventIDRef, string Subject, string Description, string Location, DateTime EventStart, DateTime EventEnd, string TimeZone, int Duration,
string Recepients, bool isAllDayEvent, bool hasReminder, string ReminderType, int ReminderMinutes, bool isRecurring, int RecurrenceType, string RecurrenceDesc, DateTime RecurrenceStart, DateTime RecurrenceEnd,
DateTime CreatedDate, DateTime ModifiedDate)
{
RefreshOutlookConstants();
//ITEM TYPES
var olMailItem = 0;
var olAppointmentItem = 1;
//
//FOLDER TYPES
var olFolderCalendar = 9;
//
int RecurrenceMask = 0;
var objAppointment = objOutlook.CreateItem(olAppointmentItem);
var objMail = objOutlook.CreateItem(olMailItem);
var OlNamspace = objOutlook.GetNamespace("MAPI");
var AppointmentFolder = OlNamspace.GetDefaultFolder(olFolderCalendar);
var StoreID = AppointmentFolder.StoreID;
AppointmentFolder.Items.IncludeRecurrences = true;
string StatusTypeDesc = "";
string[] Attendees = Recepients.Split(';');
//UPDATE YEARLY RECURRENCE TYPE - BECAUSE THE NUMBER 4 DOES NOT EXIST ACCORDING TO MICROSOFT ( -_-)
if (RecurrenceType == 3)
{
RecurrenceType = 5;
}
//GET DAY OF WEEK
if (RecurrenceDesc.Trim().ToUpper() == "MONDAY")
{
RecurrenceMask = 32;
}
else if (RecurrenceDesc.Trim().ToUpper() == "TUESDAY")
{
RecurrenceMask = 4;
}
else if (RecurrenceDesc.Trim().ToUpper() == "WEDNESDAY")
{
RecurrenceMask = 8;
}
else if (RecurrenceDesc.Trim().ToUpper() == "THURSDAY")
{
RecurrenceMask = 16;
}
else if (RecurrenceDesc.Trim().ToUpper() == "FRIDAY")
{
RecurrenceMask = 32;
}
else if (RecurrenceDesc.Trim().ToUpper() == "SATURDAY")
{
RecurrenceMask = 64;
}
else if (RecurrenceDesc.Trim().ToUpper() == "SUNDAY")
{
RecurrenceMask = 1;
}
else
{
RecurrenceMask = 0;
}
//CHECK ALL DAY EVENT
if (isAllDayEvent)
{
EventStart = Convert.ToDateTime(EventStart.ToString("dd/MM/yyyy") + " 12:00 AM");
EventEnd = Convert.ToDateTime(EventEnd.AddDays(1).ToString("dd/MM/yyyy") + " 12:00 AM");
}
//--RESOLVE EVENT START - END - DURATION
GetEventDates(EventStart, EventEnd, Duration, out EventEnd, out Duration);
if (EventStart == null)
{
return EventID + "#FAIL";
}
//ADD - DELETE - UPDATE MEETING ACCORDINGLY
if (StatusType == 'D')
{
var aObject = OlNamspace.GetItemFromID(EventID, StoreID);
aObject.MeetingStatus = 5;
aObject.Save();
if (Recepients.Trim() != "")
{
foreach (string attendee in Attendees)
{
if (attendee.Trim() != "")
{
string NewAttendee = ExtractEmail(attendee);
aObject.Recipients.Add(NewAttendee.Trim());
}
}
aObject.Send();
}
aObject.Delete();
aObject = null;
}
else
{
if (StatusType == 'U')
{
foreach (var aObject in AppointmentFolder.Items)
{
var EntryID = aObject.EntryID;
if (Convert.ToString(EntryID) == EventID.Trim())
{
aObject.MeetingStatus = 5;
aObject.Save();
if (Recepients.Trim() != "")
{
foreach (string attendee in Attendees)
{
string NewAttendee = ExtractEmail(attendee);
if (NewAttendee.Trim() != "")
{
aObject.Recipients.Add(NewAttendee.Trim());
}
}
aObject.Send();
}
aObject.Delete();
}
}
}
objAppointment.MeetingStatus = 1;
objAppointment.Subject = Subject;
objAppointment.Body = Description;
objAppointment.Location = Location;
if (Recepients.Trim() != "")
{
foreach (string attendee in Attendees)
{
string NewAttendee = ExtractEmail(attendee);
if (NewAttendee.Trim() != "")
{
objAppointment.Recipients.Add(NewAttendee.Trim());
}
}
}
if (isAllDayEvent)
{
objAppointment.AllDayEvent = isAllDayEvent;
}
else
{
objAppointment.Start = EventStart;
objAppointment.End = EventEnd; //Optional if Event has Duration
objAppointment.Duration = Duration; //Optional if Event has Start and End
}
objAppointment.ReminderSet = hasReminder;
if (hasReminder)
{
objAppointment.ReminderMinutesBeforeStart = ReminderMinutes;
}
objAppointment.Importance = 2;
objAppointment.BusyStatus = 2;
if (isRecurring)
{
var pattern = objAppointment.GetRecurrencePattern();
pattern.RecurrenceType = RecurrenceType;
if (RecurrenceType == 1)
{
pattern.DayOfWeekMask = RecurrenceMask;
}
else if (RecurrenceType == 4)
{
pattern.MonthOfYear = RecurrenceMask;
}
if (DateTime.Compare(RecurrenceStart, DateTime.Now) > 1)
{
pattern.PatternStartDate = DateTime.Parse(RecurrenceStart.ToString("dd/MM/yyyy"));
}
if (DateTime.Compare(RecurrenceEnd, DateTime.Now) > 1)
{
pattern.PatternEndDate = DateTime.Parse(RecurrenceEnd.ToString("dd/MM/yyyy"));
}
}
objAppointment.Save();
if (Recepients.Trim() != "")
{
objAppointment.Send();
}
EventID = objAppointment.EntryID;
}
objAppointment = null;
//objOutlook = null;
// CREATE--UPDATE--DELETE EVENT OR APPOINTMENTS
StatusTypeDesc = GetStatusType(StatusType).Trim();
if (StatusTypeDesc == "")
{
clsGlobalFuncs.WriteServiceLog(String.Format("Error Creating Outlook Event: Unknown Status Type [{0}]. Event was Treated as a new event and may contain errors", StatusType));
return EventID + "#FAIL";
}
clsGlobalFuncs.WriteServiceLog(String.Format("Outlook Event Succesfully {2}. [EventID: {0}] ][EventRef: {1}]", EventID, EventIDRef, StatusTypeDesc));
return EventID + "#PASS";
}
public static void SendEmail(string Recepients, string CC, string BCC, string Subject, string Body, string Attachment)
{
RefreshOutlookConstants();
string[] EmailArr = Recepients.Split(';');
foreach (string email in EmailArr)
{
if (email.IndexOf('#') == -1)
{
WriteServiceLog(String.Format("EMAIL ERROR: Invalid Email Address:- [{0}]. This email will be skipped", email));
Recepients = Recepients.Replace(email + ";", "");
Recepients = Recepients.Replace(email, "");
}
}
if (Recepients.Trim() == "")
{
WriteServiceLog(String.Format("Error Sending Email. No recpients were found in string [{0}]", Recepients));
return;
}
try
{
Recepients = StringClean(Recepients);
// SEND EMAIL WITH ATTACHMENT
mailObject.To = Recepients;
if (CC.Trim() != "") { mailObject.CC = CC; }
if (BCC.Trim() != "") { mailObject.BCC = BCC; }
mailObject.Subject = Subject;
mailObject.HTMLBody = Body;
mailObject.Importance = 2;
if (Attachment.Trim() != "")
{
string[] attachmentList = Attachment.Split(';');
foreach (string attachmentFile in attachmentList)
{
if (attachmentFile.Trim() != "")
{
mailObject.Attachments.Add(attachmentFile.Trim());
}
}
}
mailObject.Send();
//objEmail.Display(false);
WriteServiceLog(String.Format("Email Sent [{0}] TO [{1}]", Subject, Recepients));
}
catch (Exception ex)
{
WriteServiceLog("Error sending email");
WriteErrorLog(ex);
}
}
public static string GetStatusType(char StatusCode)
{
string returnValue = "";
if (StatusCode == 'A')
{
returnValue = "Created";
}
else if (StatusCode == 'U')
{
returnValue = "Updated";
}
else if (StatusCode == 'D')
{
returnValue = "Deleted";
}
return returnValue;
}
public static string GetRecurData(bool RecurFlag, string EventType, int RecurrenceType, string RecurrenceDesc, DateTime RecurrenceStart, DateTime RecurrenceEnd, DateTime EventStart)
{
string returnValue = String.Format("RRULE:FREQ=DAILY;UNTIL={0:yyyyMMdd};", EventStart);
if (RecurFlag == true)
{
returnValue = "";
if (RecurrenceType == 0)
{
returnValue = String.Format("{0}RRULE:FREQ=DAILY;", returnValue);
}
else if (RecurrenceType == 1)
{
returnValue = returnValue + "RRULE:FREQ=WEEKLY;";
}
else if (RecurrenceType == 2)
{
returnValue = returnValue + "RRULE:FREQ=MONTHLY;";
}
else
{
returnValue = returnValue + "RRULE:FREQ=YEARLY;";
}
if (RecurrenceEnd != null)
{
returnValue = String.Format("{0}UNTIL={1:yyyyMMdd}T{2:HHmmss}Z;", returnValue, RecurrenceEnd, RecurrenceEnd);
}
if (EventType == "GM")
{
if (RecurrenceType == 1)
{
if ((RecurrenceDesc != null) && (RecurrenceDesc.Trim() != ""))
{
returnValue = String.Format("{0}BYDAY={1};", returnValue, RecurrenceDesc.Substring(0, 2).ToUpper());
}
}
if (RecurrenceType == 3)
{
int i = DateTime.ParseExact(RecurrenceDesc, "MMMM", System.Globalization.CultureInfo.InvariantCulture).Month;
if ((RecurrenceDesc != null) && (RecurrenceDesc.Trim() != ""))
{
returnValue = String.Format("{0}BYMONTH={1};", returnValue, i);
}
}
}
}
return returnValue;
}
public static string GetReminderType(bool ReminderFlag, string EventType, string ReminderCode)
{
string returnValue = "NONE";
if (ReminderFlag == true)
{
if (ReminderCode.Trim() == "PROMPT")
{
if (EventType == "GM")
{
returnValue = "popup";
}
else if (EventType == "OC")
{
returnValue = "DISPLAY";
}
}
else
{
returnValue = "email";
if (EventType == "OC") { returnValue = returnValue.ToUpper(); }
}
}
return returnValue;
}
public static void GetEventDates(DateTime EventStart, DateTime EventEnd, int Duration, out DateTime EventEnd_Ret, out int Duration_Ret)
{
EventEnd_Ret = EventEnd;
Duration_Ret = 0;
if (!(EventStart == null))
{
if (((EventEnd == null) || (DateTime.Compare(EventEnd, EventStart) < 1)) && (Duration > 0))
{
EventEnd_Ret = EventStart.AddMinutes(Duration);
}
else if ((Duration_Ret <= 0) && ((EventEnd != null) && (DateTime.Compare(EventEnd, EventStart) >= 0)))
{
Duration_Ret = Convert.ToInt32((EventEnd - EventStart).TotalMinutes);
}
if ((Duration_Ret <= 0) || ((EventEnd_Ret == null) || (DateTime.Compare(EventEnd_Ret, EventStart) < 1)))
{
WriteServiceLog(String.Format("ERROR UPDATING EVENT - COULD NOT RESOLVE WHEN THE EVENT MUST END USING [END DATE: {0:dd/MM/yyyy HH:mm}] OR [DURATION: {1}] - PLEASE SPECIFY A VALID END DATE OR DURATION", EventEnd, Duration));
}
}
else
{
WriteServiceLog("ERROR UPDATING EVENT - START DATE NOT FOUND");
}
}
public static string StringClean(string StringValue)
{
StringValue = StringValue.Replace(':',' ');
StringValue = StringValue.Replace('[', ' ');
StringValue = StringValue.Replace(']', ' ');
StringValue = StringValue.Replace('\'', ' ');
StringValue = StringValue.Replace('<', ' ');
StringValue = StringValue.Replace('>', ' ');
return StringValue.Trim();
}
And to call it, use this
CreateAppointmentOutlookDirect
(
'A', //'A' = ADD, 'U' = UPDATE, 'D' = DELETE
0,
"EVENT SUBJECT",
"OUTLOOK",
"",
"WHAT IS IT ABOUT",
"EVENT DESCRIPTION",
"EVENT LOCATION",
DateTime.Now,
DateTime.Now.AddMinutes(60),
TimeZone.CurrentTimeZone.StandardName,
0,
"attendee1#email.com; attendee2#email.com",
false,
true,
"PROMPT",
30,
false,
0,
"",
DateTime.Now,
DateTime.Now,
false,
'A',
"APPOINTMENT TEST SYSTEM"
);

Categories

Resources