Loop troguh appointments in outlook stops at first match - c#

I am using Microsoft.Office.Interop.Outlook and I am trying to loop trough all the appointments that match a particular set of conditions:
To reduce the items I limit the search between two knows maximum dates
It has to contain an "ID"
Beside the additional regex that I don't know if it can be fitted in the .Restrict, the foreach loop interrupts at the first entry
DateTime start = DateTime.Now.AddDays(-1);
string filter1 = "[Start] >= '" + start.ToString("g") + "' AND [End] <= '" + DateTime.MaxValue.ToString("g") + "'";
Outlook.Items calendarItems = personalCalendar.Items.Restrict(filter1);
calendarItems.IncludeRecurrences = true;
calendarItems.Sort("[Start]", Type.Missing);
string filter3 = "#SQL=" + "\"" + "urn:schemas:httpmail:subject" + "\"" + " LIKE '%" + AppCode + "%'";
Outlook.Items restrictedItems = calendarItems.Restrict(filter3);
bool error_free = true;
foreach (Outlook.AppointmentItem apptItem in restrictedItems)
{
MessageBox.Show(apptItem.Subject);
try
{
if (Regex.IsMatch(apptItem.Subject, #"^.*##ManaOrdini\d{1,}##.*$"))
{
apptItem.Move(newCalendarFolder);
}
}
catch (System.Exception ex)
{
MessageBox.Show("Si è verificato un errore durante la creazione dell'appuntamento. Errore: " + ex.Message);
error_free = false;
}
}
Can anybody explain me why? Do I have to add a goto method to iterate untill no entry found?
EDIT
The variable restrictedItems contains the following entries:
Subject "Reminder Ordine Numero:1\t##ManaOrdini1#" System.String
Subject "Reminder Ordine Numero:1\t##ManaOrdini##" System.String
Subject "Reminder Ordine Numero:1\t##ManaOrdini1222##" System.String
Subject "Reminder Ordine Numero:1\t##ManaOrdini1##" System.String
EDIT 2
Ended up with this, basically I had to split in two parts:
Clone the results of the filters
Loop and move
DateTime start = DateTime.Now.AddDays( - 2);
string filter1 = "[Start] >= '" + start.ToString("g") + "' AND [End] <= '" + DateTime.MaxValue.ToString("g") + "'";
Outlook.Items calendarItems = personalCalendar.Items.Restrict(filter1);
calendarItems.IncludeRecurrences = true;
calendarItems.Sort("[Start]", Type.Missing);
string filter3 = "#SQL=" + "\"" + "urn:schemas:httpmail:subject" + "\"" + " LIKE '%" + AppCode + "%'";
Outlook.Items restrictedItems = calendarItems.Restrict(filter3);
bool error_free = true;
int c = 0;
List < Outlook.AppointmentItem > listaApp = new List < Outlook.AppointmentItem > ();
foreach(Outlook.AppointmentItem apptItem in restrictedItems) {
if (Regex.IsMatch(apptItem.Subject, #"^.*##ManaOrdini\d{1,}##.*$")) {
listaApp.Add(apptItem);
c++;
}
}
for (int i = 0; i < c; i++) {
try {
listaApp[i].Move(newCalendarFolder);
}
catch(System.Exception ex) {
MessageBox.Show("Si è verificato un errore durante la creazione dell'appuntamento. Errore: " + ex.Message);
error_free = false;
}
}

Related

High CPU usage with system.Threading.LowLevelLifoSemaphore.WaitForSignal(int) in C# asp.net core 6 MVC

I'm working with C# asp.net core 6 MVC and I'm having high CPU usage.
I've been using dotnet-trace and it seems to be system.Threading.LowLevelLifoSemaphore.WaitForSignal(int) the responsable for this. I understand that this has to do with graphics. Which could be right because in my app when I ran the dotnet-trace I had multiple uploads of images.
I will left below an image and the code in C# that saves the images that I get.
application functionality: The user send us images from a mobile app and we save the images and data into the server (Linux server) and database.
C# code:
[Route("routToWeb")]
public async Task<string> saveImages()
{
try
{
string[] dividirFilePath, fechaSinPunto;
string dir = DateTime.Now.ToString("yyyy/MM/dd");
string ruta, consulta, strCompleta;
List<PedidoViewModel> verificarDato;
var dirPath = System.IO.Path.Combine(Directory.GetCurrentDirectory(), "wwwroot/imgAndroid/", dir);
if (!Directory.Exists(dirPath))
{
Directory.CreateDirectory(dirPath);
}
string[] dividir, remitoDeVuelta;
int cont = 0;
while ((cont + 1) <= this.Request.Form.Files.Count)
{
try
{
var fileName = this.Request.Form.Files[cont].FileName;
if (fileName.Contains("/Pictures/"))
{
dividirFilePath = fileName.Split("Pictures/");
fileName = dividirFilePath[1];
}
strCompleta = dir + "/" + fileName;
var filePath = System.IO.Path.Combine(Directory.GetCurrentDirectory(), "wwwroot/imgAndroid/", strCompleta);
if (filePath.Contains("/Pictures/"))
{
dividirFilePath = filePath.Split("/storage/emulated/0/Pictures/");
filePath = dividirFilePath[0] + dividirFilePath[1];
}
dividir = fileName.Split("_");
// dividir[2] = dividir[2].Remove(4);
remitoDeVuelta = dividir[2].Split("-");
verificarDato = new List<PedidoViewModel>();
consulta = "SELECT p.Pedido, p.Entrega, p.Remito FROM Pedido p WHERE Remito = '" + remitoDeVuelta[0] + remitoDeVuelta[1] + "' AND Entrega = '" + dividir[1] + "';";
verificarDato = VerificarDato(consulta);
if (verificarDato.Count == 0)
{
consulta = "INSERT INTO Pedido (Pedido, Entrega, Remito) VALUES " + " ('" + dividir[0] + "','" + dividir[1] + "','" + remitoDeVuelta[0] + remitoDeVuelta[1] + "');";
if (!InsertConexionMySql(consulta)) return "fallo en la subida BD";
}
ruta = "/imgAndroid/" + strCompleta;
fechaSinPunto = dividir[4].Split(".");
consulta = "INSERT INTO Entrega (Entrega, Path, Fecha, NombreUsuario, GrupoUsuario) VALUES" + " ('" + dividir[1] + "','" + ruta + "','" + dividir[3] + " " + fechaSinPunto[0] + "','-','-');";
if (!InsertConexionMySql(consulta)) return "fallo en la subida BD";
using (var stream = System.IO.File.Create(filePath))
{
await this.Request.Form.Files[cont].CopyToAsync(stream);
}
cont++;
}
catch (Exception ex)
{
Logger.Error(ex.Message + " || Funcion: Post() 1er catch");
return "Subida fallida." + ex.ToString();
}
}
Logger.Debug("Posteo de imagenes subida exitosa || Funcion: Post()");
return "Subida exitosa";
}
catch (Exception ex)
{
Logger.Error(ex.Message + " || Funcion: Post() 2do catch");
return "fallo en la subida.";
}
}
Someone know how could I resolve this? Or tell me where to look please? Thank you very much!

Results in descending order

I've got a block of code which sums up time togged for various tasks in a project and returns the total hours logged per project (intMinutesLogged). How do I get my results n descending order?
static async void NotifyEntriesByWorkSpace(Dictionary<string, List<TimeEntry>> dicEntriesByWorkspace, string strChatURL)
{
string strMessage = "";
foreach (var kvpEntry in dicEntriesByWorkspace)
{
var lstTimeEntries = kvpEntry.Value;
string strTitle = "";
var intMinutesLogged = 0;
var intMinutesBillable = 0;
var intMinutesNonBillable = 0;
foreach (var objTimeEntry in lstTimeEntries)
{
if (objTimeEntry.Billable)
{
intMinutesBillable += objTimeEntry.TimeInMinutes;
}
else
{
intMinutesNonBillable += objTimeEntry.TimeInMinutes;
}
}
strTitle = Workspaces.getWorkspaceFromCache(kvpEntry.Key).Title;
//Console.WriteLine(intMinutesLogged + ": " + strTitle + "m");
intMinutesLogged = intMinutesBillable + intMinutesNonBillable;
Console.WriteLine(TimeLoggedMessage(intMinutesLogged) + ": " + strTitle + " " + "(Billable: " + TimeLoggedMessage(intMinutesBillable) + ";" + " " + "Non-Billable: " + TimeLoggedMessage(intMinutesNonBillable) + ")");
strMessage += TimeLoggedMessage(intMinutesLogged) + ": " + strTitle + " " + "(Billable: " + TimeLoggedMessage(intMinutesBillable) + ";" + " " + "Non-Billable: " + TimeLoggedMessage(intMinutesNonBillable) + ")" + "\n";
}
await SendMessage(strChatURL, strMessage);
}
static string TimeLoggedMessage(int intMinutesLogged)
{
return intMinutesLogged / 60 + "h" + " " + intMinutesLogged % 60 + "m";
}
You could use LINQ for this: https://learn.microsoft.com/en-us/dotnet/api/system.linq.enumerable.orderbydescending?view=net-6.0
You could create a simple class or anonymous type to hold the integer values you're summing up (total minutes, billable minutes, non-billable minutes). Then you could populate a collection of this type within the code you shared and afterwards call OrderByDescending on it. You could order based on any of the three integer values.

Keep int variables values from dataReader c#

I don't have much experience with C# but I am trying to make a simple windows forms app with personal finances.
So, I have 2 dataReader (I am using the Oracle provider), and the sql (oracle table) commands that select only 2 columns from a table, only with 1 value, mainly income 1 and income2 and the sum of all values from a specific month.
the sql strings look like this:
strSQL_sel_income1 = "select DISTINCT categorie,SUM(suma) from financiar where main_categ='income' and categorie IN ('income1') and EXTRACT(month FROM data)=" + luna_income + " Group by categorie";
strSQL_sel_income2 = "select DISTINCT categorie,SUM(suma) from financiar where main_categ='income' and categorie IN ('Income2') and EXTRACT(month FROM data)=" + luna_income + " Group by categorie";
the "luna_income" value is taken from a combobox where I select a specific month.
The problem is when I try to declare an Int variable from the values I get with data reader and these variables are not kept outside the while statement... dr_income1/2 being the dataReader
if (dr_income1.HasRows)
{
while (dr_income1.Read())
{
label26.Text = dr_income1.GetString(0) + ": " + dr_income1.GetInt32(1) + "\n";
int suma_income1 = dr_incomei1.GetInt32(1);
}
}
else
{
label26.Text = "No info;
}
so, I have two similar data readers and two int variables suma_income1 and suma_income2. If I try to make a sum of them, outside the WhIle codes, I get a zero value. Where should I declare the two variables and how to keep their values?
int suma_income_total = suma_income1 + suma_income2;
label29.Text = "Income total: " + suma_income_total;
The suma_income_total is ZERO!!!
dr_income1 = cm1.ExecuteReader();
dr_income2 = cm2.ExecuteReader();
label26.Text = "";
label28.Text = "";
if (dr_income1.HasRows)
{
while (dr_income1.Read())
{
label26.Text = dr_income1.GetString(0) + ": " + dr_income1.GetInt32(1) + "\n";
int suma_income1 = dr_income1.GetInt32(1);
}
}
else
{
label26.Text = "No info";
}
if (dr_income2.HasRows)
{
while (dr_income2.Read())
{
label28.Text = dr_income2.GetString(0) + ": " + dr_income2.GetInt32(1) + "\n";
int suma_income2 = dr_income2.GetInt32(1);
}
}
else
{
label28.Text = "no info";
}
int suma_income_total = suma_income1 + suma_income2;
label29.Text = "income total: " + suma_income_total;
dr_income2.Close();
dr_income1.Close();
I put some changes in your code. It is not ideal since there are several much simple ways. But it is ok as workaround:
dr_income1 = cm1.ExecuteReader();
dr_income2 = cm2.ExecuteReader();
label26.Text = "";
label28.Text = "";
var suma_income1 =0;
var suma_income2 =0;
if (dr_income1.HasRows)
{
while (dr_income1.Read())
{
label26.Text = dr_income1.GetString(0) + ": " + dr_income1.GetInt32(1) + "\n";
suma_income1 += dr_income1.GetInt32(1);
}
}
else
{
label26.Text = "No info";
}
if (dr_income2.HasRows)
{
while (dr_income2.Read())
{
label28.Text = dr_income2.GetString(0) + ": " + dr_income2.GetInt32(1) + "\n";
suma_income2 += dr_income2.GetInt32(1);
}
}
else
{
label28.Text = "no info";
}
int suma_income_total = suma_income1 + suma_income2;
label29.Text = "income total: " + suma_income_total;
dr_income2.Close();
dr_income1.Close();

Ho to set timeout for dataset in C#

when i run this code after 30 second give me error 'time out expire' . error comming exactly after fill dataset . by the way i add connection time out = 0 to my app config but still the problem is the same . so how i can set connection time out for this dataset
public void ExportInvoicesAccount()
{
var q = from h in hmsdb.TransHdrs
where h.Account.AccountsContracts.First().AccountsMain.ID == _mainaccid
&& h.PayMethod == "R"
&& h.CancelDate == null
&& h.TransDate >= _fromdate
&& h.TransDate <= _todate
group h by new
{
amID = h.Account.AccountsContracts.First().AccountsMain.ID,
amcode = h.Account.AccountsContracts.First().AccountsMain.Code,
amName = h.Account.AccountsContracts.First().AccountsMain.EngName,
acccode = h.AccountCode,
accid = h.AccountID,
accname = h.Account.EngName
} into qg
select new
{
amID = qg.Key.amID,
amCode = qg.Key.amcode,
amName = qg.Key.amName,
acccode = qg.Key.acccode,
accid = qg.Key.accid,
accname = qg.Key.accname
};
if (_facccode != "" && _taccccode == "")
{
q = q.Where(f => f.acccode == _facccode);
}
if (_facccode != "" && _taccccode != "")
{
q = q.Where(f => Convert.ToInt32(f.acccode) >= Convert.ToInt32(_facccode) && Convert.ToInt32(f.acccode) <= Convert.ToInt32(_taccccode) && f.acccode != "C" && f.acccode != "10281501مكرر ");
}
foreach (var x in q)
{
try
{
ClaimDS ds = new ClaimDS();
SP_EClaims_StatmentOfAccountGeneralTableAdapter adapt = new SP_EClaims_StatmentOfAccountGeneralTableAdapter();
ds.EnforceConstraints = false;
adapt.Fill(ds.SP_EClaims_StatmentOfAccountGeneral, x.amID, x.accid, 0, _fromdate, _todate, _inout,0,0,0, 0);
if (ds.SP_EClaims_StatmentOfAccountGeneral.Rows.Count != 0)
{
InvoicesByAcc rptinv = new InvoicesByAcc();
rptinv.SetDataSource(ds);
ExportOptions expop = new ExportOptions();
DiskFileDestinationOptions dfdo = new DiskFileDestinationOptions();
PdfRtfWordFormatOptions pdfop = new PdfRtfWordFormatOptions();
FolderPath = _path + x.amCode + " - " + x.amName + "\\";
bool exists = System.IO.Directory.Exists(FolderPath);
if (!exists)
System.IO.Directory.CreateDirectory(FolderPath);
fpath = FolderPath;
rptinv.ExportOptions.ExportFormatType = ExportFormatType.PortableDocFormat;
rptinv.ExportOptions.ExportDestinationType = ExportDestinationType.DiskFile;
DiskFileDestinationOptions objDiskOpt = new DiskFileDestinationOptions();
if (_inout == "O")
{
objDiskOpt.DiskFileName = FolderPath + "\\" + x.acccode + "-" + "0000" + "-0000" + "-" + "001" + "-OUT" + ".pdf";
}
else if (_inout == "I")
{
objDiskOpt.DiskFileName = FolderPath + "\\" + x.acccode + "-" + "0000" + "-0000" + "-" + "001" + "-IN" + ".pdf";
}
else
{
objDiskOpt.DiskFileName = FolderPath + "\\" + x.acccode + "-" + "0000" + "-0000" + "-" + "001" + "-ALL" + ".pdf";
}
rptinv.ExportOptions.DestinationOptions = objDiskOpt;
rptinv.Export();
rptinv.Dispose();
rptinv.Close();
}
GC.Collect();
ds.Dispose();
ds.Clear();
}
catch (Exception ex)
{
string logpath = FolderPath + "E_Claim_ErrorLog.txt";
// This text is added only once to the file.
if (!File.Exists(logpath))
{
// Create a file to write to.
using (StreamWriter sw = File.CreateText(logpath))
{
//sw.WriteLine(ex.Message + "( " + "AccountMainID: " + x.amID + " - " + "AccountID: " + x.accid + " - "+ "ConsID: " + x.consid + " - " + "MRN: " + x.mrn + " )");
}
}
// This text is always added, making the file longer over time
// if it is not deleted.
using (StreamWriter sw = File.AppendText(logpath))
{
sw.WriteLine(ex.Message + " SP_EClaims_StatmentOfAccountGeneral" + "ExportInvoicesAccount" + "( " + "AccountMainID: " + x.amID + " - " + "AccountID: " + x.accid + " - " + "ConsID: " + "0" + " - " + "MRN: " + "0" + " )");
}
//MessageBox.Show(ex.Message + "AccountMainID: " + x.amID + "-"+ "AccountID: " + x.accid + "ConsID: " + x.consid + "MRN: " + x.mrn );
}
}
}

Doesn't parse updated row from LinqToSQLDataClass to Database LINQ C# WPF

I'm building an Edit/Update system in my program using Linq in C# WPF.
My problem is that my code does submit to the LinqToSQLDatacontex but doesn't parse it through to the actual Database.
The result of that is that the datarow is updated in Runtime but in fact isn't updated in the actual Database.
this is the code I use for Updating my rows.
private void dgUsers_MouseUp(object sender, MouseButtonEventArgs e)
{
try
{
item = dgUsers.SelectedItem;
this.name = (dgUsers.SelectedCells[0].Column.GetCellContent(item) as TextBlock).Text;
var query =
from t in db.tbl_Users
where t.Name == name
select t;
foreach (var q in query)
{
tbMoreName.Text = q.Name;
tbMoreRights.Text = q.Rights;
tbMoreTag.Text = q.Operatortag;
checkMoreActive.IsChecked = q.Active;
tbMoreCardCode.Text = q.CardCode;
}
var table =
from q in db.tbl_UserProfiles
where q.Userprofile == tbMoreRights.Text
select q;
}
catch (Exception exc)
{
MessageBox.Show("NOPE");
}
}
private void btnSaveUser_Click(object sender, RoutedEventArgs e)
{
switch (saveType)
{
case "Edit":
#region save Edit User
var edit =
(from t in db.tbl_Users
where t.Name == name
select t).First();
MessageBox.Show(edit.Id.ToString() + " " + edit.Name.ToString() + " " + edit.Operatortag.ToString() + " " + edit.Rights.ToString() + " " + edit.Active.ToString());
edit.Id = edit.Id;
edit.Name = tbName.Text;
edit.Operatortag = tbOperatortag.Text;
edit.Rights = cbRights.Text;
edit.Active = checkActive.IsChecked.Value;
edit.CardCode = tbCardcode.Text;
MessageBox.Show(edit.Id.ToString() + " " + edit.Name.ToString() + " " + edit.Operatortag.ToString() + " " + edit.Rights.ToString() + " " + edit.Active.ToString() + " " + edit.CardCode.ToString());
db.SubmitChanges();
#endregion
saveType = "";
break;
}
var refresh =
(from q in db.tbl_Users
select new { Name = q.Name, Rights = q.Rights, Operatortag = q.Operatortag, Active = q.Active, Cardcode = q.CardCode }).ToList();
dgUsers.ItemsSource = null;
dgUsers.ItemsSource = refresh;
MessageBox.Show(refresh[0].ToString() + " " + refresh[1].ToString() + " " + refresh[2].ToString() + " " + refresh[3].ToString() + " " + refresh[4].ToString());
}
I hope that one of you guys can help me.
Thanks in advance!!!

Categories