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!!!
Related
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!
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.
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();
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 );
}
}
}
Im trying to convert an object (Lead) to a reduced form of the same object (ApiLead)
The object contains a list of objects (OtherInHousehold) which also needs to be reduced (ApiOtherInHousehold):
result = leads.Select(lead => new ApiLead()
{
UserId = lead.UserId,
DepartmentId = lead.DepartmentId,
CompanyId = lead.CompanyId,
CPR_number = lead.CPR_number,
CVR_number = lead.CVR_number,
Name = (lead.FirstName == "[virksomhed]" ? "" : lead.FirstName + " ") + lead.LastName,
Address = (lead.Street + " " + lead.StreetNumber + " " + lead.Floor + " " + lead.Side).Trim(),
Zipcode = lead.Zipcode,
City = (lead.PlaceName + " " + lead.City).Trim(),
Phonenumber = ("Fastnet: " + lead.Phonenumber + " Mobil: " + lead.Cellphonenumber),
Email = lead.Email,
BestReached = lead.BestReached,
**OthersInHousehold = lead.OthersInHousehold.Select(oih => new ApiOtherInHousehold(){ CPR_number = oih.CPR_number, Name = oih.Name }).ToList()**,
WantsVisit = lead.WantsVisit,
WantsPhonecall = lead.WantsPhonecall,
WantsInsuranceImmediately = lead.WantsInsuranceImmediately,
ExistingInsurance = lead.ExistingInsurance,
CurrentInsuranceCompany = lead.CurrentInsuranceCompany,
OtherInfo = lead.OtherInfo,
Status = lead.Status,
CreationDate = lead.CreationDate
}).ToList();
But this throws an
Cannot implicitly convert type 'System.Collections.Generic.List<LeadsApp.ApiModels.ApiLead>' to
'System.Collections.Generic.List<LeadsApp.Models.Lead>'
Is this not possible or am I doing it wrong?
Thanks, guys.
At the linq statement, you are returning List<ApiLead>. But result variable is List<Lead>. You have to declare your result variable as List<ApiLead>.
Hope helps,