How to convert session to int, when using sql - c#

I am using C# and have a login session.
The site will only view the news (nyhet) that the journalist have written. (It's a site where the journalist can edit the news)
protected void FyllNyhetDropDownList()
{
using (NyhetAdminDataContext dbKobling = new NyhetAdminDataContext())
{
Journalist brukernavn = (from journalist in dbKobling.Journalists
where journalist.JournalistId = Convert.ToInt16(Session["bruker"].ToString())
select journalist).SingleOrDefault();
List<Nyhet> nyhetliste = (from nyhet in dbKobling.Nyhets
select nyhet).ToList();
if (nyhetliste.Count() > 0)
{
NyhetDropDowwnList.DataTextField = "Tittel";
NyhetDropDowwnList.DataValueField = "NyhetId";
NyhetDropDowwnList.DataSource = nyhetliste;
NyhetDropDowwnList.DataBind();
}
}
}
It's here all go wrong. Can anyone help?
where journalist.JournalistId = Convert.ToInt16(Session["bruker"].ToString())
I get the error message
Cannot implicitly convert type 'int' to 'bool'
Thanks for any help!

Shouldn't you be using ==?
where journalist.JournalistId == Convert.ToInt16(Session["bruker"].ToString())

try below
Journalist brukernavn = dbKobling.Journalists.SingleOrDefault(x => x.JournalistId ==
Convert.Int16(Session["bruker"].ToString()));

Related

Using Except keyword in c#

I am using the except keyword in c# for the first time and I have been struggling a lot with this. If possible could you please have a look into my function and let me know where I am wrong.
I need to return the string of arrays. indivEmails1 and indivEmails2 contains an array of email id's. I need to return an email id's which are not in indivEmails2 but not in indivEmails1. But it has to be string of array.
public string[] getNewCCEmailsIDs(WorkOrderModel model)
{
string[] emailids = null;
var result = _db.WorkOrders
.Where(w => w.idWorkOrder == model.idWorkOrder && w.idCompany == model.idCompany)
.Select(w => new {w.Status, w.ExternalEmails});
if (dbItem.Status == (int) WorkOrderStatus.Approved )
{
string NewCCEmail = "";
var comEmails1 = dbItem.ExternalEmails.Trim(';');
string[] indivEmails1 = comEmails1.Split(';');
string comEmails2 = model.ExternalEmails.Trim(';');
string[] indivEmails2 = comEmails2.Split(';');
IEnumerable<string> emailsToAdd = indivEmails2.Except(indivEmails1);
//NewCCEmail = emailsToAdd;
}
if (NewCCEmail != "") // when client delete an email id from CC and press save.
emailids = NewCCEmail.Split(';');
}
return emailids;
}
I am getting below error. I have looked eveywhere but no luck.
Error 54 Cannot implicitly convert type 'System.Collections.Generic.IEnumerable<string>' to 'string[]'. An explicit conversion exists (are you missing a cast?) C:\Users\Bakul\Documents\GitHub\Maxpanda\Maxpanda\Controllers\WorkOrderController.cs 930 25 Maxpanda
Any help will be very much appreciated.
Thanks.
Use ToList()
List<string> emailsToAdd = indivEmails2.Except(indivEmails1).ToList();
Thank you every one. Changed code to below and it worked.
string[] emailsToAdd = indivEmails2.Except(indivEmails1).ToArray();

Searching database with Linq

I am trying to search for data in my datagrid using the code sample below. I have had it working with the code looking a bit different, but I am now going to use async in my coding and I have tried to do so with the sample below, but have no idea how to change the code to work correctly.
private async Task btnSearchSysproStock_Click(object sender, RoutedEventArgs e)
{
using (DataEntities DE = new DataEntities())
{
List<SSData> stockSearch = await (from a in DE.tblSysproStocks where
(a => txtSearchSysproStock.Text == string.Empty || a.StockCode.Contains(txtSearchSysproStock.Text)) //The error is in this line
select new SSData
{
SID = a.StockID,
SCode = a.StockCode,
SDescription = a.StockDescription,
SConvFactAltUom = (float)a.ConvFactAltUom,
...
}).ToListAsync();
dgSysproStock.ItemsSource = stockSearch;
}
}
I am getting the following error:
Cannot convert lamba expression to type 'bool' because it is not a delegate type
Can anyone please help me to get this code that I am using to work. Thanks in advance! :)
LINQ where clause expects bool expression, you don't need lambda here :
from a in ...
where txtSearchSysproStock.Text == string.Empty ||
a.StockCode.Contains(txtSearchSysproStock.Text)
select ...

where clause in LINQ to Entites DataBind

I'm trying to add a where clause to an existing LINQ DataBind but nothing I do works. The where clause I want to add checks if in the table refAuthSigner the column IsActive == 1.
Here's my existing Query:
// populates Authorized Signer dropdownlist
using (dbPSREntities10 myEntities = new dbPSREntities10())
{
var allSigners = from refAuthSigner in myEntities.refAuthSigners <--- where clause somewhere around here??
select new
{
refAuthSignerID = refAuthSigner.refAuthSignerID,
refAuthSignerName = refAuthSigner.refAuthSignerFirst + " " + refAuthSigner.refAuthSignerLast
};
ddlAuthSigners.DataSource = allSigners;
ddlAuthSigners.DataValueField = "refAuthSignerID";
ddlAuthSigners.DataTextField = "refAuthSignerName";
ddlAuthSigners.DataBind();
}
I want to add a where clause which is something like:
var allSigners = from refAuthSigner in myEntities.refAuthSigners
where refAuthSigner.IsActive == 1
This code isn't right and just wondering how I would incorporate the where clause into the code. Thanks!
Simply use:
where refAuthSigner.IsActive
Since it's a boolean value you cannot compare it to an integer. It is true or false, not 1 or 0. (Some langauges conflate the two, C# is not one of them.)
There is no need to compare IsActive to anything. where needs a boolean value, and IsActive is a boolean value. You already have exactly what you need.
You could make the statement:
var allsigners = refAuthSigner.Where(x => x.refAuthSigner.IsActive)
Try this:
var allSigners = from refAuthSigner in myEntities.refAuthSigners
where refAuthSigner.IsActive
select new
{
refAuthSignerID = refAuthSigner.refAuthSignerID,
refAuthSignerName = refAuthSigner.refAuthSignerFirst + " " + refAuthSigner.refAuthSignerLast
};
Operator of '==' cannot be applied to operands of type 'bool' and 'int'. IsActive is type bit in SqlServer
If this is the error you are getting try using Any instead of Where as it returns bool
// populates Authorized Signer dropdownlist
using (dbPSREntities10 myEntities = new dbPSREntities10())
{
var allSigners = from refAuthSigner in myEntities.refAuthSigners
where refAuthSigner.IsActive
select new
{
refAuthSignerID = refAuthSigner.refAuthSignerID,
refAuthSignerName = refAuthSigner.refAuthSignerFirst + " " + refAuthSigner.refAuthSignerLast
};
ddlAuthSigners.DataSource = allSigners;
ddlAuthSigners.DataValueField = "refAuthSignerID";
ddlAuthSigners.DataTextField = "refAuthSignerName";
ddlAuthSigners.DataBind();
}

how to convert int to string in Linq to entities

My Db column in a string (varchar) and i need to assign it to a int value.
I am using linq to query.Though the code compiles am getting an error at the run time .
Thanks in advance.
PFB my query :
var vlauesCap = from plan in entities.PA_RTM_CAP_Group
select new Business.PartnerProfile.LookUp
{
Id =Convert.ToInt32(plan.cap_group_code),
//(Int32)plan.cap_group_code,
Value = plan.cap_group_name
};
return vlauesCap.ToList();
The EF provider does not know how to translate Convert.ToInt() into SQL it can run against the database. Instead of doing the conversion on the server, you can pull the results back and do the conversion using linq to objects:
// the ToList() here causes the query to be executed on the server and
// the results are returned in a list of anonymous objects
var results = (from plan in entities.PA_RTM_CAP_Group
select new
{
Code = plan.cap_group_code,
Name = plan.cap_group_name
}).ToList();
// the conversion can now be done here using Linq to Objects
var vlauesCap = from r in results
select new Business.PartnerProfile.LookUp
{
Id = Convert.ToInt32(r.Code),
Value = r.Name
};
return vlauesCap.ToList();
You can't do this directly, what you can do is declare a private variable to handle your "mapped" value, and expose the unmapped property...
[Column(Name = "cap_group_code", Storage = "m_cap_group_code")]
private string m_cap_group_code;
public int cap_group_code {
get
{
return Int32.Parse(m_cap_group_code);
}
set
{
m_cap_group_code = value.ToString();
}
}
Try this:
var vlauesCap = from plan in entities.PA_RTM_CAP_Group
select new Business.PartnerProfile.LookUp
{
Id =Convert.ToInt32(plan.cap_group_code),
Convert.ToInt32(plan.cap_group_code),
Value = plan.cap_group_name
};
return vlauesCap.ToList();
Why aren't you using casting for such a purpose, which is a more effective way of achieving this.
Just replace Convert.ToInt32(plan.cap_group_code) with (int)plan.cap_group_code
Do remember, there should be a value in the string and is int, else it will show Exception. If you are not sure about it, then you can further expand the casting to use null coalesciting operator

how can I access an attribute by name, rather than by integer?

I must be missing something, but I can't seem to figure out how to get an Attribute by Name/String, only by an Integer, which is likely to change (the Attribute Name is not).
Could you explain how I get Attributes by name/string? The string "active" attempt produces this error:
Error 82 The best overloaded method match for 'System.Collections.Generic.List<Amazon.SimpleDB.Model.Attribute>.this[int]' has some invalid argumens
Thank you!
Hairgami
using (sdb = AWSClientFactory.CreateAmazonSimpleDBClient(accessKeyID, secretAccessKeyID))
{
String selectExpression = string.Format("select * from apps where appid = '{0}'", appID);
SelectRequest selectRequestAction = new SelectRequest().WithSelectExpression(selectExpression);
SelectResponse selectResponse = sdb.Select(selectRequestAction);
if (selectResponse.IsSetSelectResult())
{
SelectResult selectResult = selectResponse.SelectResult;
foreach (Item item in selectResult.Item)
{
//Works fine
Amazon.SimpleDB.Model.Attribute id = item.Attribute[1];
//How can I do this:
Amazon.SimpleDB.Model.Attribute id = item.Attribute["active"];
}
}
else
{
}
}
You're trying to access a System.Collections.Generic.List<T> like it's an associative array, which it's not. The Enumerable.FirstOrDefault method could be used to achieve something similar:
Amazon.SimpleDB.Model.Attribute id =
item.Attribute.FirstOrDefault(attr => attr.Name == "active");

Categories