Nested Linq conversion (select) - c#

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,

Related

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();

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!!!

How to convert DateTime? to String directly (in c# linq)

i'm making a web-service where i'm calling data-objects who are created directly through linq, i was wondering, how i can convert DateTime? directly to string?, this, because i can't convert the DateTime? to DateTime and then to string through a variable or a what not, because linq don't let me.
Here's the code:
lista = (from p in db.Acciones
select new ItemAcciones
{
ID_Accion = p.ID_Accion,
FechaHora = p.FechaHora != null ? (DateTime)p.FechaHora : DateTime.Now,
//ShowFechaHora = !String.IsNullOrWhiteSpace(((DateTime)p.FechaHora).ToString("HH:mm")) ? ((DateTime)p.FechaHora).ToString("HH:mm") : DateTime.Now.ToString("HH:mm"),
ID_EmpresaNombre = p.Empresas.EmpresaNombre,
ID_ResponsableNombre = p.Responsables.LoginID,
ID_ContactoNombre = p.Contactos.Nombres + " " + p.Contactos.Paterno + " " + p.Contactos.Materno,
ID_AccionTipoNombre = p.AccionTipos.AccionTipoGlosa,
ID_AccionEstadoNombre = p.AccionEstados.AccEstGlosa,
AccionGlosa = p.AccionGlosa,
ID_Empresa = p.ID_Empresa,
AccionDescripcion = p.AccionDescripcion,
ID_Negocio = (int?)p.ID_Negocio ?? 0,
ID_Contacto = p.ID_Contacto,
ID_AccionTipo = p.ID_AccionTipo,
ID_AccionEstado = p.ID_AccionEstado,
ID_ProgFecha = p.ID_ProgFecha != null ? (int)p.ID_ProgFecha : 0,
ShowID_ProgFecha = String.IsNullOrWhiteSpace(p.ID_ProgFecha.ToString()) ?? p.ID_ProgFecha.ToString() : "--/--/----",
//ShowID_ProgFecha = StringAEstilizarComoDate(Convert.ToString(p.ID_ProgFecha)),
ID_ProgHora = p.ID_ProgHora != null ? (int)p.ID_ProgHora : 0,
//ShowID_ProgHora = StringAEstilizarComoHora(Convert.ToString(p.ID_ProgHora)),
ID_EjecFecha = p.ID_EjecFecha != null ? (int)p.ID_EjecFecha : 0,
//ShowID_EjecFecha = StringAEstilizarComoDate(Convert.ToString(p.ID_EjecFecha)),
ID_EjecHora = p.ID_EjecHora != null ? (int)p.ID_EjecHora : 0,
//ShowID_EjecHora = StringAEstilizarComoHora(Convert.ToString(p.ID_EjecHora)),
ID_Responsable = p.ID_Responsable,
EmpresaRUTCompleto = p.Empresas.EmpresaRut.ToString() + "-" + p.Empresas.EmpresaDV,
ID_NegocioNombre = p.Negocios.ProyectoNombre,
}).ToList();
Any question, suggestion or comment to improve the question would be appreciated as well as the answer.
It's a manually solution, but you can use SqlFunctions to handle the string for your Date.
var qqqq = db.YourTable.Select(q => (q.YourDate == null ? "" : (SqlFunctions.DateName("day",q.YourDate) + "/" + SqlFunctions.DateName("month", q.YourDate) + "/" + SqlFunctions.DateName("year", q.YourDate) + " " + SqlFunctions.DateName("hour", q.YourDate) + " " + SqlFunctions.DateName("minute", q.YourDate)))).ToList();
Hope that helps. =)

TFS API - How to obtain the parent of a work item

My ultimate goal is to get the parent of one work item at a time recursively, until there are no more parents in the hierarchy. At the moment, there is nothing recursive yet, I am still at the point of optimizing the way I obtain the parent work item. I have thought of a way of doing this involving a query:
public WorkItem GetParentWorkItem(int id)
{
StringBuilder queryString = new StringBuilder("SELECT [System.Id]" +
" FROM WorkItemLinks " +
" WHERE [Source].[System.WorkItemType] = '" + TFS_TIMESHEET_WORK_ITEM_TYPE + "'" +
" AND [Source].[System.TeamProject] = '" + TFS_TIMESHEET_PROJECT_KEY + "'" +
" AND [Source].[System.Id] = " + id
);
Query wiQuery = new Query(GetWorkItemStore, queryString.ToString());
WorkItemLinkInfo[] wiTrees = wiQuery.RunLinkQuery();
WorkItem wi = GetWorkItemStore.GetWorkItem(wiTrees[1].TargetId);
return wi;
}
The problem with this method is that it gets all the linked work items, including predecessor, successor, child and parents. I knew that wiTrees[1] was the parent work item so I hard coded the index.
I found out a way to get the "parent" WorkItemTypeEnd object from the work item store:
WorkItemLinkTypeEnd linkTypEnd = GetWorkItemStore.WorkItemLinkTypes.LinkTypeEnds["Parent"];
Where do I go from here?
This works on TFS 2013:
var parent_link = work_item.WorkItemLinks.Cast<WorkItemLink> ().FirstOrDefault (x => x.LinkTypeEnd.Name == "Parent");
WorkItem parent_work_item = null;
if (parent_link != null)
parent_work_item = work_item_store.GetWorkItem (parent_link.TargetId);
Found a solution, which returns the parent WorkItem if there is a parent, if not returns null.
public WorkItem GetParentWorkItem(int id)
{
StringBuilder queryString = new StringBuilder("SELECT [System.Id]" +
" FROM WorkItemLinks " +
" WHERE [Source].[System.WorkItemType] = '" + TFS_TIMESHEET_WORK_ITEM_TYPE + "'" +
" AND [Source].[System.TeamProject] = '" + TFS_TIMESHEET_PROJECT_KEY + "'" +
" AND [Source].[System.Id] = " + id
);
Query wiQuery = new Query(GetWorkItemStore, queryString.ToString());
WorkItemLinkInfo[] wiTrees = wiQuery.RunLinkQuery();
int parentLinkId = GetWorkItemStore.WorkItemLinkTypes.LinkTypeEnds["Parent"].Id;
foreach (WorkItemLinkInfo linkInfo in wiTrees)
{
// -2 is the LinkTypeId for parent
if (linkInfo.LinkTypeId == parentLinkId)
{
workItem = GetWorkItemStore.GetWorkItem(linkInfo.TargetId);
break;
}
else
{
workItem = null;
}
}
return workItem;
}

Geting out put from Script Html agility pack

i am having problem that this following script generates Email address when page is loaded and i want to parse that email how can i do that?
tr>
<td align='right' class='generalinfo_left' >Email Address:</td>
<td class='generalinfo_right'><script type="text/javascript">
//<![CDATA[
var o3752aaa9bb29d904adeb88838117fd7c = String.fromCharCode(109);var f03de7e643c296e211edddbc3197b33f6 = String.fromCharCode(97);var k7c3bf82468602c0f8dff4950e4b6ff1e = String.fromCharCode(105);var b3eaa633e44451be8df1fa47d75149934 = 'l';var ma2fa16c3a3f532b780aaf0fa5a5b75c6 = 't';var re0c13fc69c03925782867a0540f8c084 = 'o';var j335f1365672123d1fcaf9a83b76f1b7b = String.fromCharCode(58);var f32820e1c54cbc3fa0d418cd1c195eaec = String.fromCharCode(105);var y8c24ea00a7a1edf1c01f794d487697e3 = String.fromCharCode(110);var bcc0ad4f628e703f9ff6e25b87b77ec34 = 'f';var c985c961c7ee85fe6a25d5a66fb421745 = String.fromCharCode(111);var z5ab4e3bdc353d621cea5babcc5dca417 = String.fromCharCode(64);var s4e087167cd0bac466344e72016511172 = String.fromCharCode(97);var re26f6ae180723793af62bc36d5ab2530 = String.fromCharCode(108);var ye1b53d01de118079a38de5e951586731 = 'c';var g9fc5710c9266ce08afbe4da24702dfdd = String.fromCharCode(105);var k5cd5ea1bac40fdbb8b133b7e356809c6 = String.fromCharCode(118);var fcd6e4771e956e270c6897d24ca51c256 = String.fromCharCode(97);var y9d7854a5921fa2be88c8cd72c7e2884e = String.fromCharCode(114);var xa58bea1ecad6fe7d2c736aab1df2df44 = '.';var e4569f6c98804675f7117a84abb0b8d5c = 'c';var o4d2081e2344020922dcb924690c9972e = 'o';var af150185e5eef8ecd8dc1b0a4977c7d55 = String.fromCharCode(109);document.write("<a href='" + o3752aaa9bb29d904adeb88838117fd7c + f03de7e643c296e211edddbc3197b33f6 + k7c3bf82468602c0f8dff4950e4b6ff1e + b3eaa633e44451be8df1fa47d75149934 + ma2fa16c3a3f532b780aaf0fa5a5b75c6 + re0c13fc69c03925782867a0540f8c084 + j335f1365672123d1fcaf9a83b76f1b7b + f32820e1c54cbc3fa0d418cd1c195eaec + y8c24ea00a7a1edf1c01f794d487697e3 + bcc0ad4f628e703f9ff6e25b87b77ec34 + c985c961c7ee85fe6a25d5a66fb421745 + z5ab4e3bdc353d621cea5babcc5dca417 + s4e087167cd0bac466344e72016511172 + re26f6ae180723793af62bc36d5ab2530 + ye1b53d01de118079a38de5e951586731 + g9fc5710c9266ce08afbe4da24702dfdd + k5cd5ea1bac40fdbb8b133b7e356809c6 + fcd6e4771e956e270c6897d24ca51c256 + y9d7854a5921fa2be88c8cd72c7e2884e + xa58bea1ecad6fe7d2c736aab1df2df44 + e4569f6c98804675f7117a84abb0b8d5c + o4d2081e2344020922dcb924690c9972e + af150185e5eef8ecd8dc1b0a4977c7d55 + "'>" + f32820e1c54cbc3fa0d418cd1c195eaec + y8c24ea00a7a1edf1c01f794d487697e3 + bcc0ad4f628e703f9ff6e25b87b77ec34 + c985c961c7ee85fe6a25d5a66fb421745 + z5ab4e3bdc353d621cea5babcc5dca417 + s4e087167cd0bac466344e72016511172 + re26f6ae180723793af62bc36d5ab2530 + ye1b53d01de118079a38de5e951586731 + g9fc5710c9266ce08afbe4da24702dfdd + k5cd5ea1bac40fdbb8b133b7e356809c6 + fcd6e4771e956e270c6897d24ca51c256 + y9d7854a5921fa2be88c8cd72c7e2884e + xa58bea1ecad6fe7d2c736aab1df2df44 + e4569f6c98804675f7117a84abb0b8d5c + o4d2081e2344020922dcb924690c9972e + af150185e5eef8ecd8dc1b0a4977c7d55 + "</a>")
//]]>;
</script></td>
out put is like this
<td class="generalinfo_right">
<script type="text/javascript">
same above script plus following Line
</script>someID#email.com</td>
I wrote my own custom parser that will read the script and parse Email from it.here goes the code
If this code can be optimized or can be written more neatly please let me know
private string ReadEmail(string EmailScript)
{
string EncriptedEmail = "";
string dataPart = "";
dataPart = EmailScript.Substring(0, EmailScript.IndexOf("document.write")).Replace("//<![CDATA[\r", "").Replace("\"", "").Replace("\r\n","");
EncriptedEmail = EmailScript.Replace("\"","");
EncriptedEmail = EncriptedEmail.Substring(EncriptedEmail.IndexOf("'> + "), EncriptedEmail.IndexOf(" + </a>") - EncriptedEmail.IndexOf("'> +")).Replace("'> +", "").Trim();
string[] requiredVariables = EncriptedEmail.Split('+');
List<string> ExtractedDataFromRaw = new List<string>();
string email = "";
foreach (string variable in requiredVariables)
{
string temp = dataPart.Substring(dataPart.IndexOf(variable),dataPart.Length-dataPart.IndexOf(variable)).Replace(" ","");
string tempValueofVariable = temp.Substring(0, temp.IndexOf(";"));
tempValueofVariable = tempValueofVariable.Substring(tempValueofVariable.IndexOf("="), tempValueofVariable.Length - temp.IndexOf("=")).Replace("=","");
if (tempValueofVariable.Contains("String.fromCharCode"))
{
tempValueofVariable = GetCharacterFromASCII(tempValueofVariable.Replace("String.fromCharCode(", "").Replace(")", ""));
}
ExtractedDataFromRaw.Add(tempValueofVariable.Replace("'",""));
email += tempValueofVariable.Replace("'", "");
}
return email;
}
private string GetCharacterFromASCII(string value)
{
int result = 0;
int.TryParse(value, out result);
return char.ConvertFromUtf32(result);
}
That code is building the email address one character at a time from character codepoints and then assembling it later. I suppose this is an attempt to prevent email spam. Depending on what you need to do, it might be easiest to just pull the email address from the link using jQuery or something. $('a[href^=mailto]').attr('href').substring(7) or something ought to do it.

Categories