QueryString Validation Problem - c#

Whenever I access my page directly (mypage.aspx) it returns an error:
Object not set to object not set to an instance of an object.
If I add a querystring (mypage.aspx?sr=true) it works but I am checking to make sure that before it evaluates that it has a value, and it should not have a value. So why am I getting the error when I access the page directly?
if (!IsPostBack)
{
string qu1 = "";
string qu2 = "";
string qu3 = "";
if (Request.QueryString["qu1"] != null)
{
qu1 = Request.QueryString["qu1"].ToString();
if (qu1 != "")
{
qu1DropDownList.SelectedValue = industry;
}
}
if (Request.QueryString["qu2"] != null)
{
qu2 = Request.QueryString["qu2"].ToString();
if (qu2 != "")
{
qu2DropDownList.SelectedValue = category;
}
}
fillDropDownList();
if (Request.QueryString["qu3"] != null)
{
qu3 = Request.QueryString["qu3"].ToString();
if (qu3 != "")
{
qu3tDropDownList.SelectedValue = product;
}
}
}
string search = "";
string qu1value = IndustryDropDownList.SelectedValue;
string qu2value = ProductCategoryDropDownList.SelectedValue;
string qu3value = ProductDropDownList.SelectedValue;
using (SPSite site = new SPSite("SITE"))
using (SPWeb oWebsiteRoot = site.OpenWeb())
{
SPList oList = oWebsiteRoot.Lists["SpacesInfo"];
SPListItemCollection items = null;
if (Request.QueryString["sr"] != "" && Request.QueryString["sr"] != null)
{
search = Request.QueryString["sr"].ToString();
if (search == "true")
{
if (indvalue == "select" & catvalue == "select")
{
items = oList.Items;
}
else if (indvalue != "select" & catvalue != "select" & provalue != "select")
{
SPQuery query = new SPQuery();
query.Query = "MYQUERY";
items = oList.GetItems(query);
}
else if (indvalue != "select" & catvalue != "select" & provalue == "select")
{
SPQuery query = new SPQuery();
query.Query = "MYQUERY";
items = oList.GetItems(query);
}
else if (indvalue != "select" & catvalue == "select")
{
SPQuery query = new SPQuery();
query.Query = "<Where><Eq><FieldRef Name='Industry' /><Value Type='Choice'>" + indvalue +
"</Value></Eq></Where>";
items = oList.GetItems(query);
}
else if (indvalue == "select" & catvalue != "select" & provalue == "select")
{
SPQuery query = new SPQuery();
query.Query = "MYQUERY";
items = oList.GetItems(query);
}
else if (indvalue == "select" & catvalue != "select" & provalue != "select")
{
SPQuery query = new SPQuery();
query.Query = "MYQUERY";
items = oList.GetItems(query);
}
else
{
errorLabel.Text = "Please contact the administrator.";
items = oList.Items;
}
}
else
{
items = oList.Items;
}
}
DataTable table = new System.Data.DataTable();
table = items.GetDataTable();
spacerepeater.DataSource = table;
spacerepeater.DataBind();
}

Change the order of this if statement:
if (Request.QueryString["sr"] != "" && Request.QueryString["sr"] != null)
should be
if (Request.QueryString["sr"] != null && Request.QueryString["sr"] != "")
The issue is this, in your code it looks for the empty string ("") and fails because the object is null. In my version it will see the value is null and fail out of the if statement without checking the second one.
This is often called short circuit evaluation.
ref http://en.wikipedia.org/wiki/Short-circuit_evaluation

Use:
if (!String.IsNullOrEmpty(Request.QueryString["sr"]))
{
//Do stuff
}

Related

How to convert System.Web.Mvc.SelectListItem to list

I want to display data using datatable so my hard coded System.Web.Mvc.SelectListItem value and text collect and make a list using linq but get error System.Linq.Enumerable+WhereSelectListIterator`2[System.Web.Mvc.SelectListItem,System.String]
var parentkeylist = clsDataCache.GetPriorityList().ToList();
var parentkeylist = clsDataCache.GetPriorityList().ToList();//this is SelectListItem
List data = this.GetAllStpOrganizationEntityData(input);
foreach (stp_organizationentityEntity obj in data)
{
if (obj.parentkey != null)
{
obj.priotytext = parentkeylist.Where(x => x.Value == obj.parentkey.ToString()).Select(x => x.Text).Cast<string>().ToString();//not cast Text value get error System.Linq.Enumerable+WhereSelectListIterator`2[System.Web.Mvc.SelectListItem,System.String]
}
else
{
obj.priotytext = "Root";
}
}
if (data != null && data.Count > 0)
{
long totalRecords = data.FirstOrDefault().RETURN_KEY;
var tut = (from t in data
select new
{
t.entityname,
t.organizationkey,
t.priotytext,
t.entirytypekey,
t.entitylevel,
//t.seqfirstindex,
//t.seqfullindex,
// t.entitycpde,
//t.description,
t.isactive,
ex_nvarchar1 = objSecPanel.genButtonPanel(t.entitykey.GetValueOrDefault(-99), "entitykey", this.HttpContext.User.Identity as ClaimsIdentity,
"StpOrganizationEntity/StpOrganizationEntityUpdate", "EditStpOrganizationEntity", "StpOrganizationEntity/StpOrganizationEntityDelete", "DeleteStpOrganizationEntity",
"StpOrganizationEntity/StpOrganizationEntityDetails", "StpOrganizationEntityDetails")
}).ToList();
}
var parentkeylist = clsDataCache.GetPriorityList().ToList();
var parentkeylist = clsDataCache.GetPriorityList().ToList();//this is SelectListItem
List data = this.GetAllStpOrganizationEntityData(input);
foreach (stp_organizationentityEntity obj in data)
{
if (obj.parentkey != null)
{
obj.priotytext = parentkeylist.Where(x => x.Value == obj.parentkey.ToString()).Select(x => x.Text).Cast<string>().ToString();//not cast Text value get error System.Linq.Enumerable+WhereSelectListIterator`2[System.Web.Mvc.SelectListItem,System.String]
}
else
{
obj.priotytext = "Root";
}
}
if (data != null && data.Count > 0)
{
long totalRecords = data.FirstOrDefault().RETURN_KEY;
var tut = (from t in data
select new
{
t.entityname,
t.organizationkey,
t.priotytext,
t.entirytypekey,
t.entitylevel,
//t.seqfirstindex,
//t.seqfullindex,
// t.entitycpde,
//t.description,
t.isactive,
ex_nvarchar1 = objSecPanel.genButtonPanel(t.entitykey.GetValueOrDefault(-99), "entitykey", this.HttpContext.User.Identity as ClaimsIdentity,
"StpOrganizationEntity/StpOrganizationEntityUpdate", "EditStpOrganizationEntity", "StpOrganizationEntity/StpOrganizationEntityDelete", "DeleteStpOrganizationEntity",
"StpOrganizationEntity/StpOrganizationEntityDetails", "StpOrganizationEntityDetails")
}).ToList();
}enter image description here

How to filter DataRow column containing url in c#

I am using below query
DataRow[] oFilteredRows =
oTrgFTPTrigList.Select($"ftpPath='{oSrcRow["ftpPath"]}'
and ftpUserName='{oSrcRow["ftpUserName"]}'");
But it fails since ftpPath is url ftp://testURL/
I need to filter and get records with same data as of source (Comparing target and source DataBases)
Here is the answer.
I have converted data like below.
string ftpPath = Uri.EscapeUriString(oSrcRow["ftpPath"].ToString());
Here is the full code sample.
public DataTable compareFTPTriggers(string targetConnectionString)
{
DataTable oFTPTriggerTableDiffs = new DataTable("oFTPTriggerDiffs");
oFTPTriggerTableDiffs.Columns.Add("oFTPTriggerID");
oFTPTriggerTableDiffs.Columns.Add("oFTPTriggerName");
oFTPTriggerTableDiffs.Columns.Add("Comments");
try
{
deFTPTrigger oSrcFTPTrigger = new deFTPTrigger(m_connectString, m_externalUserID);
DataTable oSrcFTPTrigList = oSrcFTPTrigger.getAllFTPTriggers();
string systemUserID = clsSettings.systemUserID(targetConnectionString);
deFTPTrigger oTrgFTPTrigger = new deFTPTrigger(targetConnectionString, systemUserID);
DataTable oTrgFTPTrigList = oTrgFTPTrigger.getAllFTPTriggers();
foreach (DataRow oSrcRow in oSrcFTPTrigList.Rows)
{
string ftpPath = Uri.EscapeUriString(oSrcRow["ftpPath"].ToString());
DataRow[] oFilteredRows = oTrgFTPTrigList.Select($"ftpPath= '{ftpPath}' and ftpUserName='{oSrcRow["ftpUserName"]}'");
string sKey = $"{oSrcRow["ftpPath"]} - {oSrcRow["ftpUserName"]}";
if (oFilteredRows.Length == 0)
{
oFTPTriggerTableDiffs.Rows.Add(oSrcRow["ftpTriggerID"], sKey, "Addition");
}
else
{
if (
oSrcRow["ftpPassword"].ToString() != oFilteredRows[0]["ftpPassword"].ToString() ||
oSrcRow["waitTime"].ToString() != oFilteredRows[0]["waitTime"].ToString() || oSrcRow["waitType"].ToString() != oFilteredRows[0]["waitType"].ToString() ||
oSrcRow["definitionID"].ToString() != oFilteredRows[0]["definitionID"].ToString() || oSrcRow["variableName"].ToString() != oFilteredRows[0]["variableName"].ToString() ||
oSrcRow["enabled"].ToString() != oFilteredRows[0]["enabled"].ToString() || oSrcRow["globalName"].ToString() != oFilteredRows[0]["globalName"].ToString()
)
{
oFTPTriggerTableDiffs.Rows.Add(oSrcRow["ftpTriggerID"], sKey, "Properties are different");
}
}
}
}
catch (Exception ex)
{
// m_oErrorProvider.writeError(ex.Message);
}
DataView dvSorted = oFTPTriggerTableDiffs.DefaultView;
dvSorted.Sort = "oFTPTriggerName ASC";
oFTPTriggerTableDiffs = dvSorted.ToTable();
return (oFTPTriggerTableDiffs);
}

Error while using ToString("Format") method

I have one my_Account page. and for data retrieving i'm using ToString("DD/MM/yyyy") format and i'm also checking in advanced if null but there is one compile time error occurred like
Error 48 No overload for method 'ToString' takes '1' arguments F:\EasyWeb\EndUser\My_Account.aspx.cs 59 55 F:\EasyWeb\
here is my code:
using (DataClassesDataContext db = new DataClassesDataContext())
{
var query = from u in db.Users
where u.Username == user_id
select u;
foreach (var item in query)
{
Session["Username"] = user_id;
hidden_profile_id.Value = item.Id.ToString();
lbl_user_id.Text = item.Username.ToString();
Bind_DDL_Title();
ListItem item1 = drp_title.Items.FindByText(item.Title);
if (item1 != null)
{
item1.Selected = true;
}
txtf_name.Text = item.First_name.ToString();
txt_lname.Text = item.Last_name.ToString();
dob.Text = item.Birth_date.ToString("DD/MM/yyyy");
if (item.Anniversary_date != null)
{
//Line 48 No Overload for method 'ToString' takes '1' argument...
txt_adate.Text = item.Anniversary_date.ToString("DD/MM/yyyy");
}
Bind_DDL_Status();
ListItem item2 = DDL_StatusList.Items.FindByValue(item.status_id.ToString());
if (item2 != null)
{
item2.Selected = true;
}
txt_email.Text = item.email.ToString();
txt_mno.Text = item.mobile_no.ToString();
txt_phoneno.Text = item.phone_no ?? "".ToString();
txt_address.Text = item.Address ?? "".ToString();
Bind_DDL_Countries();
ListItem item3 = DDL_CountryNames.Items.FindByValue(item.country_id.ToString());
if (item3 != null)
{
item3.Selected = true;
}
Bind_DDL_States();
ListItem item4 = DDL_StateNames.Items.FindByValue(item.state_id.ToString());
if (item4 != null)
{
item4.Selected = true;
}
txt_city.Text = item.city_name ?? "".ToString();
txt_zip.Text = item.pin_code ?? "".ToString();
CompareValidator1.ValueToCompare = item.password.ToString();
}
}
Please help me...
You Can use ToString("DD/MM/yyyy") in DateTime or Date Object only not all objects.
Try like this
dob.Text = Convert.ToDateTime(item.Birth_date.ToString()).ToString("yyyy-MM-dd");

Multimode Search in Entity Framework

The code is listed below , is my code for multimode search in ado.net , i use now entity framework and i dont know how write this perfectly with less code
string query = '"SELECT id From user";
if(filter1 != "" || filter2 != "")
{
query += "where ";
}
if(filter1 != "")
{
query += "name='" + filter1 + "'";
if(filter2 != "")
query += " and "
}
if(filter2 != "")
query += "name" + filter2;
Try this:
var result = (from s in db.user
select s).AsQueryable();
if (filter1 != "")
{
result = result.Where(x=>x.name == filter1);
}
if (filter2 != "")
{
result = result.Where(x=>x.name == filter2);
}
var output = result.ToList();
Sample:
YourIQueryableResults.Where(x => filter1!="" && (x.Name == filter1))
or
if (filter1!="") { YourIQueryableResults = YourIQueryableResults.Where(x => x.Name == filter1)}

Writing to incidents in C#

I am using CRM 4 and the SDK to grab cases like so:
public List<Case> GetCases()
{
List<Case> cases = new List<Case>();
#region Retrieve Resolved Cases
try
{
InitSession();
RetrieveMultipleRequest req = new RetrieveMultipleRequest();
req.ReturnDynamicEntities = true;
//QueryExpression says what entity to retrieve from, what columns we want back and what criteria we use for selection
QueryExpression qe = new QueryExpression();
qe.EntityName = EntityName.incident.ToString();
List<string> attributes = new string[] {
"incidentid","title" ,"description", "ticketnumber", "statuscode",
"kez_allocatedhours",
"customerid",
"casetypecode"
}.ToList();
//columns to retireve
ColumnSet AvailabilityColumnSet = new ColumnSet();
AvailabilityColumnSet.Attributes = attributes.ToArray();
qe.ColumnSet = AvailabilityColumnSet;
//filter
FilterExpression fe = new FilterExpression();
fe.FilterOperator = LogicalOperator.And;
//condtion for filter
ConditionExpression isResolved = new ConditionExpression();
isResolved.AttributeName = "statuscode";
isResolved.Operator = ConditionOperator.NotEqual;
isResolved.Values = new string[] { "5" };
fe.Conditions = new ConditionExpression[] { isResolved }; //Add the conditions to the filter
qe.Criteria = fe; //Tell the query what our filters are
req.Query = qe; //Tell the request the query we want to use
//retrieve entities
RetrieveMultipleResponse resp = svc.Execute(req) as RetrieveMultipleResponse;
if (resp != null)
{
BusinessEntity[] rawResults = resp.BusinessEntityCollection.BusinessEntities;
List<DynamicEntity> castedResults = rawResults.Select(r => r as DynamicEntity).ToList();
foreach (DynamicEntity result in castedResults)
{
string id = GetProperty(result, "incidentid");
string title = GetProperty(result, "title");
string description = GetProperty(result, "description");
string ticket = GetProperty(result, "ticketnumber");
string customer = GetProperty(result, "customerid");
int statuscode = -1;
string statusname = "";
double estHours = 0.0;
string casetype = "";
int casetypecode = -1;
Property prop = result.Properties.Where(p => p.Name == "statuscode").FirstOrDefault();
if (prop != null)
{
StatusProperty status = prop as StatusProperty;
if (status != null)
{
statuscode = status.Value.Value;
statusname = status.Value.name;
}
}
prop = result.Properties.Where(p => p.Name == "kez_allocatedhours").FirstOrDefault();
if (prop != null)
{
CrmFloatProperty fl = prop as CrmFloatProperty;
if (fl != null)
{
estHours = fl.Value.Value;
}
}
prop = result.Properties.Where(p => p.Name == "casetypecode").FirstOrDefault();
if (prop != null)
{
PicklistProperty fl = prop as PicklistProperty;
if (fl != null)
{
casetype = fl.Value.name;
casetypecode = fl.Value.Value;
}
}
Case c = new Case();
c.ID = id;
c.Title = title;
c.Description = description;
c.StatusCode = statuscode;
c.StatusName = statusname;
c.TicketNumber = ticket;
c.CustomerName = customer;
c.EstimatedHours = estHours;
c.Type = casetype;
c.TypeCode = casetypecode;
bool allowedThroughStat = true;
bool allowedThroughType = true;
var userStatuses = SettingsManager.Get("CRMUserStatusReasons").Split(';').ToList().Where(p => p.Length > 0).ToList();
var userTypes = SettingsManager.Get("CRMUserCaseTypes").Split(';').ToList().Where(p => p.Length > 0).ToList();
if(userStatuses.Count > 0 && !userStatuses.Contains(c.StatusCode.ToString()))
{
allowedThroughStat = false;
}
if (userTypes.Count > 0 && !userTypes.Contains(c.TypeCode.ToString()))
{
allowedThroughType = false;
}
if(allowedThroughStat && allowedThroughType)
cases.Add(c);
}
}
}// end try
catch (Exception)
{
return null;
// The variable 'e' can access the exception's information.
// return "Error Message: " + e.Message.ToString() + " | Stack Trace: " + e.StackTrace.ToString();
}
return cases;
#endregion
}
However, now I need to be able to change the status and title of a case from C# given its incidentid.
Ive looked at the SDK docs and cannot find an example of this.
Anyone work with this before?
Thanks
Simply put, above is code to read an incident. Could I get an example of writing an incident field, Just one. Ex: How could I change the title of an incident.
You can call the Update method on the CrmService. Here is the SDK article.
Case c = new Case();
c.ID = id;
c.Title = title;
svc.Update(c);
To change the state of an entity you use the setstaterequest. If you want to do it to a dynamic entity there's a description in this blog

Categories

Resources