Datatables Object Reference not set to instance of an object for one variable - asp.net

This is my datatables serverside implementation. FilterInput contains 5 variables:
Level <- string
Message <- string
Exception <-string
StartDate <- DateTime
EndDate <- DateTime
For some reason when I run this code as it is, I will always get this error:
{System.NullReferenceException: Object reference not set to an
instance of an object.
This is referring to this line:
data = data.Where(
u => u.Level.ToString().ToLower().Contains(FilterInput.Level.ToLower()) &&
u.Message.ToString().ToLower().Contains(FilterInput.Message.ToLower()) &&
u.Exception.ToString().ToLower().Contains(FilterInput.Exception.ToLower())
).ToList();
However, if I remove the search for FilterInput.Exception, everything runs fine again. I have tested it with input ("abc") or without input ("") and the results are the same. The other FilterInputs don't have the same error.
public JsonResult Search(SearchViewModels Input, EventLogsSearchViewModel FilterInput)
{
JsonResult result = new JsonResult(null);
try
{
var data = dbContext.EventLogs.ToList();
int totalRecords = data.Count;
var modelStructure = new Dictionary<int, string>();
modelStructure.Add(1, "Level");
modelStructure.Add(2, "TimeStamp");
modelStructure.Add(3, "LogEvent");
modelStructure.Add(4, "Message");
modelStructure.Add(5, "MessageTemplate");
modelStructure.Add(6, "Exception");
modelStructure.Add(7, "Properties");
var StartDate = FilterInput.StartDate != default(DateTime);
var EndDate = FilterInput.EndDate != default(DateTime);
if ((!string.IsNullOrEmpty(FilterInput.Level) && !string.IsNullOrWhiteSpace(FilterInput.Level)) ||
(!string.IsNullOrEmpty(FilterInput.Message) && !string.IsNullOrWhiteSpace(FilterInput.Message)) ||
(!string.IsNullOrEmpty(FilterInput.Exception) && !string.IsNullOrWhiteSpace(FilterInput.Exception)) ||
(StartDate && EndDate))
{
data = data.Where(
u => u.Level.ToString().ToLower().Contains(FilterInput.Level.ToLower()) &&
u.Message.ToString().ToLower().Contains(FilterInput.Message.ToLower()) &&
u.Exception.ToString().ToLower().Contains(FilterInput.Exception.ToLower())
).ToList();
data = data.Where(u => u.TimeStamp >= FilterInput.StartDate && u.TimeStamp <= FilterInput.EndDate).ToList();
}
if (!(string.IsNullOrEmpty(Input.Order) && string.IsNullOrEmpty(Input.OrderDir)))
{
var columnName = modelStructure.FirstOrDefault(f => f.Key == Convert.ToInt32(Input.Order));
data = data.AsQueryable().OrderBy(columnName.Value + " " + Input.OrderDir).ToList();
}
int recFilter = data.Count;
data = data.Skip(Input.StartRec).Take(Input.PageSize).ToList();
var modifiedData = data.Select(u => new EventLogsListViewModel
{
Id = u.Id,
Message = u.Message,
MessageTemplate = u.MessageTemplate,
Level = u.Level,
TimeStamp = u.TimeStamp,
Exception = u.Exception,
Properties = u.Properties,
LogEvent = u.LogEvent
});
result = this.Json(new
{
draw = Convert.ToInt32(Input.Draw),
recordsTotal = totalRecords,
recordsFiltered = recFilter,
data = modifiedData,
order = Input.Order,
orderdir = Input.OrderDir
});
}
catch (Exception e)
{
logger.LogError(e, LoggingGlobals.LoadingException);
}
return result;
}
EDIT: The exception still happens even when FilterInput.Exception is not null

Related

Join two dynamic Linq in Asp.net

I have used linq to store data, below is the code:
var result = (dynamic)null;
var serviceData = (dynamic)null;
var userData = (dynamic)null;
/****Linq 1*****/
serviceData= dtPasscode.AsEnumerable().Select(m => new
{
ACCOUNT_ID = intAccountId,
SUB_ACC_ID = m.Field<string>("ACCOUNT_ID_ALIAS")
});
/**Linq 2**/
userData = DisplyCustomerDetails(Convert.ToInt64(strSubAccountID));
result = serviceData.Concat(userData);
And another linq through function:
/**Function**/
System.Data.EnumerableRowCollection DisplyCustomerDetails(Int64 intAccountId)
{
var result = (dynamic)null;
/** Data Display if no service avaiable **/
IAccount_BL objAccount_BL = new Account_BL();
Customer objCustomer = new Customer();
DataTable dtCustomer = null;
int intErrorCount = 0;
objCustomer.Account_Id = Convert.ToInt64(intAccountId);
dtCustomer = objAccount_BL.GetCustomerDetails(objCustomer, ref intErrorCount);
objAccount_BL = null;
objCustomer = null;
if (intErrorCount == 0)
{
if (dtCustomer != null)
{
if (dtCustomer.Rows.Count > 0)
{
result = dtCustomer.AsEnumerable().Select(m => new
{
ACCOUNT_ID = intAccountId,
SUB_ACC_ID = m.Field<string>("ACCOUNT_ID_ALIAS")
});
}
}
}
return result;
}
I wanted to join both the result of Linq1 & Linq2, I tired Concat & Union, getting below error
'System.Data.EnumerableRowCollection<<>f__AnonymousTypea>' does not contain a definition for 'Concat'
To Concat both enumerables must of the same class; you cannot use anonymous classes. Define a class that has the two fields and change the code to Select them.
Also, don't use ... = (dynamic) null; just assign the variable directly
var serviceData= dtPasscode ...
var userData = DisplyCustomerDetails ...
var result = serviceData.Concat(userData);

web api call performance tuning

I am trying to figure find why my api is taking ~5 secs working on 1000 records,is that good or bad?I want to know what tools are there in asp.net webapi to figure out which piece of code or where its consuming time and fine tune the performance
CODE:-
List<LookaheadRunInfo> lookaheadRunsInfo = new List<LookaheadRunInfo>();
List<lookahead_run> lookaheadRunData = new List<lookahead_run>();
if (!filterCriteria.labeled)
{
lookaheadRunData = bitDB.lookahead_run.Where(x => x.lookahead_run_status == null && x.submission_time != null).OrderByDescending(x => x.submission_time).Skip(filterCriteria.PageNumber * filterCriteria.PageSize).Take(filterCriteria.PageSize).ToList();
}
else
{
lookaheadRunData = bitDB.lookahead_run.OrderByDescending(x => x.submission_time).Skip(filterCriteria.PageNumber * filterCriteria.PageSize).Take(filterCriteria.PageSize).ToList();
}
foreach (var lookaheadRunRow in lookaheadRunData)
{
var lookaheadRunInfo = new LookaheadRunInfo();
var lookaheadRunId = lookaheadRunRow.lookahead_run_id;
lookaheadRunInfo.ECJobLink = lookaheadRunRow.ec_job_link;
lookaheadRunInfo.UserSubmitted = lookaheadRunRow.submitted_by;
lookaheadRunInfo.SubmittedTime = lookaheadRunRow.submission_time.ToString();
lookaheadRunInfo.RunStatus = lookaheadRunRow.lookahead_run_status;
var completionTime = lookaheadRunRow.completion_time;
if (completionTime == null)
{
lookaheadRunInfo.ElapsedTime = (DateTime.UtcNow - lookaheadRunRow.submission_time).ToString();
}
else
{
lookaheadRunInfo.ElapsedTime = (lookaheadRunRow.completion_time - lookaheadRunRow.submission_time).ToString();
}
List<String> gerrits = new List<String>();
List<string> lookaheadRunChangeListIds = new List<string>();
if (!filterCriteria.labeled)
{
lookaheadRunChangeListIds = (from lrcl in bitDB.lookahead_run_change_list
join cl in bitDB.change_lists on lrcl.change_list_id equals cl.change_list_id
where lrcl.lookahead_run_id == lookaheadRunId
//and cl.change_list_id not in (select clcl.change_list_id from component_labels_change_lists as clcl)
//where !(from clcl in bitDB.component_labels_change_lists select clcl.change_list_id).Contains(cl.change_list_id)
where !bitDB.component_labels_change_lists.Any(clcl => clcl.change_list_id == cl.change_list_id)
select cl.change_list.ToString()).ToList();
}
else
{
lookaheadRunChangeListIds = (from lrcl in bitDB.lookahead_run_change_list
join cl in bitDB.change_lists on lrcl.change_list_id equals cl.change_list_id
where lrcl.lookahead_run_id == lookaheadRunId
select cl.change_list.ToString()).ToList();
}
//bitDB.Log = Console.Out;
//lookaheadRunInfo.gerrits = gerrits;
lookaheadRunInfo.gerrits = lookaheadRunChangeListIds;
if (lookaheadRunChangeListIds.Count != 0 && filterCriteria.labeled == false)
{
lookaheadRunsInfo.Add(lookaheadRunInfo);
}
else if (filterCriteria.labeled == true)
{
lookaheadRunsInfo.Add(lookaheadRunInfo);
}
}
return lookaheadRunsInfo;

asp:calendar binds last value to date from database

I have to bind an <asp:calendar> with data fetched from a database using a linq query.
Here is the linq code
public List<AllCalander> SearchCalender(int month, int zip, string type, int cause)
{
var xyz = (from m in DB.Calenders
where(m.DateFrom.Value.Month==month || m.Zip==zip || m.ActivityType==type || m.CauseID==cause)
group m by new { m.DateFrom } into grp
select new
{
caustitle = grp.Select(x => x.Caus.CauseTitle),
datfrm = grp.Key.DateFrom,
total = grp.Count()
})
.ToList()
.Select(m => new AllCalander
{
DateFrom =Convert.ToDateTime(m.datfrm),
CauseTitle = string.Join(",", m.caustitle),
Total = m.total
});
My aspx.cs code is here
List<AllCalander> calnder = calbll.SearchCalender(mnth,ZipString,type,causeString);
foreach (var myItem in calnder)
{
string datetime = myItem.DateFrom.ToString();
Literal myEventNameLiteral = new Literal();
myEventNameLiteral.ID = i + myItem.CauseID.ToString();
// string currentcalanderDate = e.Day.Date.Day.ToString() ;
if (string.Equals(DateTime.Parse(datetime).ToString("MMM dd yyyy"), e.Day.Date.ToString("MMM dd yyyy")))
{
string a = myItem.CauseTitle;
if (a != cause)
cause = a;
coun++;
myEventNameLiteral.Mode = LiteralMode.PassThrough;
myEventNameLiteral.Text = "<br /><span style='font-family:verdana; font-size:10px;'>" + myItem.CauseTitle + "(" + myItem.Total + ")"+ " ";
e.Cell.Controls.Add(myEventNameLiteral);
}
i++;
}
but on output it only shows the last value from database instead of showing all the data.
Can somebody please tell me what's wrong?
Thanks in advance
group m by new { m.DateFrom, m.Caus.CauseTitle } into grp

Conditional to limit .Net webservice results

I'm not sure if this is the right way but I have a web service that returns json. Now I wanted to set a conditional to omit rows returned that have a value of false in cell appearInShowcase. Most of the code is pretty straight forward what it does but the cell that has a true false value is appearInShowcase which is in a table photo. In the ms sql database the appearInShowcase is of type ntext.
public List<wsGalleryPhotos> GetGalleryPhotos(int collectionID)
{
photoDataContext dc = new photoDataContext();
List<wsGalleryPhotos> results = new List<wsGalleryPhotos>();
System.Globalization.CultureInfo ci = System.Globalization.CultureInfo.GetCultureInfo("en-US");
foreach (photo photo in dc.photos.Where(s => s.collectionID == collectionID))
{
if(photo.appearInShowcase == "true")
{
results.Add(new wsGalleryPhotos()
{
photoID = photo.photoID,
collectionID = Convert.ToInt32(photo.collectionID),
name = photo.name,
description = photo.description,
filepath = photo.filepath,
thumbnail = photo.thumbnail
});
}
}
return results;
}
if you want to add a condition, you should do it like this:
public List<wsGalleryPhotos> GetGalleryPhotos(int collectionID)
{
photoDataContext dc = new photoDataContext();
List<wsGalleryPhotos> results = new List<wsGalleryPhotos>();
System.Globalization.CultureInfo ci = System.Globalization.CultureInfo.GetCultureInfo("en-US");
results = dc.photos.Where(s => s.collectionID == collectionID && s.appearInShowcase == "true")
.Select(s => new wsGalleryPhotos
{
photoID = s.photoID,
collectionID = collectionID,
name = s.name,
description = s.description,
filepath = s.filepath,
thumbnail = s.thumbnail
}).ToList();
return results;
}

queries in entity framework

i have written the following query and it is giving error Unable to cast object of type
System.Data.Objects.ObjectQuery'[ITClassifieds.Models.Viewsearch]' to type 'ITClassifieds.Models.Viewsearch'.
my code is as follows
if (zipcode.Contains(","))//opening of zipcode conatins comma
{
do
{
zipcode = zipcode.Replace(" ", " ");
zipcode = zipcode.Replace(", ", ",");
} while (zipcodecity.Contains(" "));
char[] separator = new char[] { ',' };
string[] temparray = zipcode.Split(separator);
var zipcd = (from u in db.ZipCodes1
where u.CityName == temparray[0] && u.StateAbbr == temparray[1] && u.CityType == "D"
select new Viewsearch
{
Zipcode = u.ZIPCode
}).Distinct();
Viewsearch vs = (Viewsearch)zipcd;
if (zipcd.Count() > 0)
{
zipcode = vs.Zipcode;
locations = "";
}
else
{
tempStr = "";
zipcode = "";
}
}
You need to do
If it will always exist:
Viewsearch vs = zipcd.First()
If not use, and then check for null before using
Viewsearch vs = zipcd.FirstOrDefault()
You could also use Single if there will always be 1 or None.
The Distinct method returns an enumerable collection (in your case, and ObjectQuery<T>, which may contain more than one element. You can't typecast that directly to an item in the collection, you need to use one of the IEnumerable methods to get it:
Viewsearch vs = zipcd.SingleOrDefault();
if ( vs != null )
{
zipcode = vs.Zipcode;
locations = String.Empty;
}
else
{
zipcode = String.Empty;
tempStr = String.Empty;
}
SingleOrDefault will throw an exception if there is more than one item in the collection; if that's a problem, you can also use FirstOrDefault to grab the first item, as one example.
Also, unrelated to your question, but you don't need the temporary array variable for your string separators. The parameter to the Split method is a params array so you can just call it like this:
string[] temparray = zipcode.Split(',');
Replace the zipcd query with:
var cityName = temparray[0];
var stateAbbr = temparray[1];
Viewsearch vs = new Viewsearch {
Zipcode = db.ZipCodes1.Where(u.CityName == cityName && u.StateAbbr == stateAbbr && u.CityType == "D").First().ZIPCode
};

Resources