Kendo Grid json string exceeds the value set on the maxJsonLength property - c#

I keep receiving this error when trying to get a json string into my kendo grid. I have set the max size in the web.config
<system.web.extensions>
<scripting>
<webServices>
<jsonSerialization maxJsonLength="2147483644">
</jsonSerialization>
</webServices>
</scripting>
I've also tried adding it directly to the controller. This is how I generate my json string
public ActionResult ChangeRequests_Read([DataSourceRequest] DataSourceRequest request)
{
return Json(GetRequests().ToDataSourceResult(request), JsonRequestBehavior.AllowGet);
}
public static IEnumerable<ChangeRequestsVM> GetRequests()
{
var model = CompanyContextFactory.GetContextPerRequest();
var chrwVM = model.ChangeRequestsHDRs.Where(ch=> ch.CompanyID == GlobalVariables.CompanyID).Select(ch=> new ChangeRequestsVM
{
RequestID = ch.RequestID,
CompanyID = ch.CompanyID,
ClientID = ch.ClientID,
EmployeeID = (string.IsNullOrEmpty(ch.EmployeeID)) ? "NA" : ch.EmployeeID,
AssignmentType = ch.AssignmentType,
Key1 = ch.Key1,
Key2 = ch.Key2,
LogonID = ch.LogonID,
ProcessDate = ch.ProcessDate,
ProcessTime = ch.ProcessTime,
ProcessUserID = ch.ProcessUserID,
RequestDate = ch.RequestDate,
RequestExport = ch.RequestExport,
RequestNote = ch.RequestNote,
RequestOrigin = Convert.ToChar(ch.RequestOrigin),
RequestProcess = ch.RequestProcess,
RequestStatus = ch.RequestStatus,
RequestTime = ch.RequestTime,
RequestType = Convert.ToChar(ch.RequestType),
ResponseNote = ch.ResponseNote,
TableName = ch.TableName,
TransferDate = ch.TransferDate,
TransferTime = ch.TransferTime,
TransferUserID = ch.TransferUserID,
dispOrigin = (Convert.ToChar(ch.RequestOrigin) == ChangeRequestOrigin.System) ? "System" : (Convert.ToChar(ch.RequestOrigin) == ChangeRequestOrigin.Client) ? "Client" : "Employee",
dispRequestType = (Convert.ToChar(ch.RequestType) == ChangeRequestType.Insert) ? "Insert" : (Convert.ToChar(ch.RequestType) == ChangeRequestType.Alter) ? "Change" : "Delete",
dispStatus = FieldTranslation.GetEnumDescription(typeof(enChangeRequestStatus), ch.RequestStatus ?? 0)
}).OrderByDescending(ch=> ch.RequestID);
return chrwVM;
}
This is the full error I'm getting. The string being sent is HUGE but I am not sure how to figure out how big it is. What am I missing to get this JSON string to return without the error?
Error during serialization or deserialization using the JSON JavaScriptSerializer.
The length of the string exceeds the value set on the maxJsonLength property
I've also tried it this way
public ActionResult ChangeRequests_Read([DataSourceRequest] DataSourceRequest request)
{
var result = Json(GetRequests().ToDataSourceResult(request), JsonRequestBehavior.AllowGet);
var serializer = new JavaScriptSerializer();
// For simplicity just use Int32's max value.
// You could always read the value from the config section mentioned above.
serializer.MaxJsonLength = Int32.MaxValue;
var resultData = new { result };
var result1 = new ContentResult
{
Content = serializer.Serialize(resultData),
ContentType = "application/json"
};
return result1;
}
public static IEnumerable<ChangeRequestsVM> GetRequests()
{
var model = CompanyContextFactory.GetContextPerRequest();
var chrwVM = model.ChangeRequestsHDRs.Where(ch=> ch.CompanyID == GlobalVariables.CompanyID).Select(ch=> new ChangeRequestsVM
{
RequestID = ch.RequestID,
CompanyID = ch.CompanyID,
ClientID = ch.ClientID,
EmployeeID = (string.IsNullOrEmpty(ch.EmployeeID)) ? "NA" : ch.EmployeeID,
AssignmentType = ch.AssignmentType,
Key1 = ch.Key1,
Key2 = ch.Key2,
LogonID = ch.LogonID,
ProcessDate = ch.ProcessDate,
ProcessTime = ch.ProcessTime,
ProcessUserID = ch.ProcessUserID,
RequestDate = ch.RequestDate,
RequestExport = ch.RequestExport,
RequestNote = ch.RequestNote,
RequestOrigin = Convert.ToChar(ch.RequestOrigin),
RequestProcess = ch.RequestProcess,
RequestStatus = ch.RequestStatus,
RequestTime = ch.RequestTime,
RequestType = Convert.ToChar(ch.RequestType),
ResponseNote = ch.ResponseNote,
TableName = ch.TableName,
TransferDate = ch.TransferDate,
TransferTime = ch.TransferTime,
TransferUserID = ch.TransferUserID,
dispOrigin = (Convert.ToChar(ch.RequestOrigin) == ChangeRequestOrigin.System) ? "System" : (Convert.ToChar(ch.RequestOrigin) == ChangeRequestOrigin.Client) ? "Client" : "Employee",
dispRequestType = (Convert.ToChar(ch.RequestType) == ChangeRequestType.Insert) ? "Insert" : (Convert.ToChar(ch.RequestType) == ChangeRequestType.Alter) ? "Change" : "Delete",
dispStatus = FieldTranslation.GetEnumDescription(typeof(enChangeRequestStatus), ch.RequestStatus ?? 0)
}).OrderByDescending(ch=> ch.RequestID);
return chrwVM;
}

Related

Best way to populate List<AnyObject> from database in C#

I have 3 classes inherited from same class like
class S1:X{}
class S2:X{}
class S3:X{}
I need to write method to populate List<X> from Sql database. Currently, i am using SqlDataReader to populate. Each class has about 35 properties and db result also about 50K rows. Population is takes too long time. I am curious about the best way to populate large data into List. I am not able to use 3rd party packages because of corporation rules. Is there faster way than SqlDataReader?
Edit:
Modified code sample is below to describe what i am trying. Firstly, may be i should explain some points. SmartSqlReader is inherited from SqlDataReader, AutoMap method is mapper used Reflection.
using(SmartSqlReader reader = db.ExecuteReader(sp)) {
while (reader.Read()) {
bool isFlag1 = reader.GetBool("XX_TO_SEND");
bool isFlag2 = reader.GetBool("YY_TO_SEND");
bool isFlag3 = reader.GetBool("ZZ_TO_SEND");
if (!isFlag1 && !isFlag2 && !isFlag3) {
continue;
}
X x = new X() {
RecordId = reader.GetInt64("RECORD_ID"),
PropCxxx = reader.GetInt64("CXXX"),
PropCxxt = reader.GetInt32("CXXT"),
PropCxxsn = reader.GetString("CXXSN").IsNullOrEmptyOrFullSpace() ? string.Empty : reader.GetString("CXXSN"),
PropCxxn = RemoveDiacritics(reader.GetString("CXXSN").IsNullOrEmptyOrFullSpace() ? string.Empty : reader.GetString("CXXN").ToLower()),
PropCxxmn = reader.GetString("CXXSN2").IsNullOrEmptyOrFullSpace() ? string.Empty : reader.GetString("CXXSN2"),
PropCxxs = reader.GetString("CXXS").IsNullOrEmptyOrFullSpace() ? string.Empty : reader.GetString("CXXS"),
Language = reader.GetString("LANGUAGE").IsNullOrEmptyOrFullSpace() ? string.Empty : reader.GetString("LANGUAGE"),
PropSxxx = reader.GetString("SXXX").IsNullOrEmptyOrFullSpace() ? string.Empty : reader.GetString("SXXX"),
MobilePhone1 = reader.GetString("MobilePhone1").IsNullOrEmptyOrFullSpace() ? string.Empty : reader.GetString("MobilePhone1"),
MobilePhone2 = reader.GetString("MobilePhone2").IsNullOrEmptyOrFullSpace() ? string.Empty : reader.GetString("MobilePhone2"),
Email1 = reader.GetString("EMAIL1").IsNullOrEmptyOrFullSpace() ? string.Empty : reader.GetString("EMAIL1"),
Email2 = reader.GetString("EMAIL2").IsNullOrEmptyOrFullSpace() ? string.Empty : reader.GetString("EMAIL2"),
Profile = reader.GetString("PROFILE").IsNullOrEmptyOrFullSpace() ? string.Empty : reader.GetString("PROFILE"),
IsPersonnel = reader.GetString("PROFILE") == "XX" ? true : false,
IsPrivateBn = reader.GetString("IsOB").IsNullOrEmptyOrFullSpace() ? false : reader.GetBool("IsOB"),
VIP = reader.GetInt32("VIP_FLAG"),
Gender = reader.GetString("GENDER").IsNullOrEmptyOrFullSpace() ? string.Empty : reader.GetString("GENDER"),
BusinessLine = reader.GetString("BUSINESSLINE").IsNullOrEmptyOrFullSpace() ? string.Empty : reader.GetString("BUSINESSLINE"),
WorkPhone = reader.GetString("WORK_PHONE").IsNullOrEmptyOrFullSpace() ? string.Empty : reader.GetString("WORK_PHONE"),
HomePhone = reader.GetString("HOME_PHONE").IsNullOrEmptyOrFullSpace() ? string.Empty : reader.GetString("HOME_PHONE"),
CompanyName = reader.GetString("COMPANY_NAME").IsNullOrEmptyOrFullSpace() ? string.Empty : reader.GetString("COMPANY_NAME"),
BranchName = reader.GetString("BRANCH_NAME").IsNullOrEmptyOrFullSpace() ? string.Empty : reader.GetString("BRANCH_NAME"),
PfNxxx = reader.GetString("PFNXXX").IsNullOrEmptyOrFullSpace() ? string.Empty : reader.GetString("PFNXXX"),
Rgxxx = reader.GetString("RGXXX").IsNullOrEmptyOrFullSpace() ? string.Empty : reader.GetString("RGXXX"),
PCBN = reader.GetString("PCBN").IsNullOrEmptyOrFullSpace() ? string.Empty : reader.GetString("PCBN"),
BPH = reader.GetString("BPH").IsNullOrEmptyOrFullSpace() ? string.Empty : reader.GetString("BPH"),
TranValue = reader.GetString("TRAN_VALUE"),
TranReferenceId = reader.GetString("TRAN_REFERENCE_ID"),
TranReferenceDate = reader.GetDateTime("TRAN_REFERENCE_DATE"),
Amount = reader.GetDecimal("AMOUNT"),
...
DynamicFields = new DynamicFields {
PropCxxx = reader.GetInt64("CXXX"),
FIELD1 = reader.GetString("DYNAMIC_FIELD1"),
FIELD2 = reader.GetString("DYNAMIC_FIELD2"),
FIELD3 = reader.GetString("DYNAMIC_FIELD3"),
FIELD4 = reader.GetString("DYNAMIC_FIELD4"),
FIELD5 = reader.GetString("DYNAMIC_FIELD5"),
FIELD6 = reader.GetString("DYNAMIC_FIELD6"),
FIELD7 = reader.GetString("DYNAMIC_FIELD7"),
FIELD8 = reader.GetString("DYNAMIC_FIELD8"),
FIELD9 = reader.GetString("DYNAMIC_FIELD9"),
FIELD10 = reader.GetString("DYNAMIC_FIELD10"),
FIELD11 = reader.GetString("DYNAMIC_FIELD11"),
FIELD12 = reader.GetString("DYNAMIC_FIELD12"),
FIELD13 = reader.GetString("DYNAMIC_FIELD13"),
FIELD14 = reader.GetString("DYNAMIC_FIELD14"),
FIELD15 = reader.GetString("DYNAMIC_FIELD15")
},
CampaignCodeOrLink = reader.GetString("CAMPAIGN_CODE").IsNullOrEmptyOrFullSpace() ? string.Empty : reader.GetString("CAMPAIGN_CODE"),
ListId = reader.GetInt64("LIST_ID")
};
x.ChannelType = isFlag1 ? Enums.Channel.C1 : isFlag2 ? Enums.Channel.C2 : Enums.Channel.C3;
if (x.ChannelType == Enums.Channel.C1) {
S1 s1 = CommonUtils.AutoMap <S1> (x);
s1.S1Prop = reader.GetString("S1Prop");
xList.Add(s1);
}
else if (x.ChannelType == Enums.Channel.C2) {
S1 s2 = CommonUtils.AutoMap <S2> (x);
s2.S2Prop = reader.GetString("S2Prop");
xList.Add(s2);
} else {
S3 s3 = CommonUtils.AutoMap <S3> (x);
s3.S3Prop = reader.GetString("S3Prop");
xList.Add(s3);
}
}
}
Second Edition:
I just changed object initialization from X x = new X(){...} to
X x;
if(isFlag1)
{
x=new S1();
}
and so on. After that, 80K rows took approximately 10s. It's amazing. In conclusion, when i used CommonUtils.AutoMap method process took ~60m also when i used the second method it decreased to ~10s. This surprised me a lot.
I just changed object initialization method, so i removed CommonUtils.AutoMap that map objects use reflection. After all, 80K rows processed in ~10s instead of ~60m. Here is final code.
using(SmartSqlReader reader = db.ExecuteReader(sp)) {
while (reader.Read()) {
bool isFlag1 = reader.GetBool("XX_TO_SEND");
bool isFlag2 = reader.GetBool("YY_TO_SEND");
bool isFlag3 = reader.GetBool("ZZ_TO_SEND");
if (!isFlag1 && !isFlag2 && !isFlag3) {
continue;
}
X x;
if (isFlag1) {
var s = new S1();
s.S1Prop = reader.GetString("S1Prop");
x = s;
} else if (isFlag2) {
var s = new S2();
s.S2Prop = reader.GetString("S2Prop");
x = s;
} else {
var s = new S3();
s.S3Prop = reader.GetString("S3Prop");
x = s;
}
x.RecordId = reader.GetInt64("RECORD_ID"),
x.PropCxxx = reader.GetInt64("CXXX"),
x.PropCxxt = reader.GetInt32("CXXT"),
...
x.DynamicFields = new DynamicFields {
FIELD1 = reader.GetString("DYNAMIC_FIELD1"),
FIELD2 = reader.GetString("DYNAMIC_FIELD2"),
FIELD3 = reader.GetString("DYNAMIC_FIELD3"),
FIELD4 = reader.GetString("DYNAMIC_FIELD4"),
FIELD5 = reader.GetString("DYNAMIC_FIELD5"),
FIELD6 = reader.GetString("DYNAMIC_FIELD6"),
FIELD7 = reader.GetString("DYNAMIC_FIELD7"),
FIELD8 = reader.GetString("DYNAMIC_FIELD8"),
FIELD9 = reader.GetString("DYNAMIC_FIELD9"),
FIELD10 = reader.GetString("DYNAMIC_FIELD10"),
FIELD11 = reader.GetString("DYNAMIC_FIELD11"),
FIELD12 = reader.GetString("DYNAMIC_FIELD12"),
FIELD13 = reader.GetString("DYNAMIC_FIELD13"),
FIELD14 = reader.GetString("DYNAMIC_FIELD14"),
FIELD15 = reader.GetString("DYNAMIC_FIELD15")
},
};
xList.Add(x);
}
}

How can I fix this Error: not all code paths return a value

My project has 2 part ClientSide and Server side. In Server side I have Controller that it needs query and command. I put both of them and my command has a handler but after I'd done my handler it throws a error that say: not all code paths return a value.
this is my handler:
public Task<ReturnCreateDataQuery> Handle(CreateCompletedActCommand request, CancellationToken cancellationToken)
{
var party = _dbContext.Parties.SingleOrDefault(t => t.PartyCode == request.PartyCode);
if (party == null) throw new Exception("");
if ((bool)request.ResonableType)
{
var departmentText = request.DepartmentIds.Any() ? string.Join(",", request.DepartmentIds.Distinct().OrderBy(t => t)) : string.Empty;
var cartableActs = new List<CartableActModel>();
var cartable = new CartableStateModel()
{
ClaimId = request.ClaimId,
CreationDate = DateTime.Now,
StatusCode = (int)Enumeration.StateType.Compeleted,
PreviouseCartableStateId = request.CartableStateId
};
var cartableAct = new CartableActCompleteModel()
{
ActCode = (int)Enumeration.ActType.CompleteCustomerData,
ActorId = party.PartyId,
CartableStateId = cartable.CartableStateId,
ChangeDate = DateTime.Now,
ClaimSubjectId = request.ClaimSubjectId,
ClaimType = request.ClaimType,
Departments = departmentText,
ExpertPartyId = request.ExpertPartyId,
ResonableType = request.ResonableType,
SubClaimSubjectId = request.SubClaimSubjectId,
CompletedDescription = request.CompletedDescription,
};
var attachments = request.Attachments.Select(t => new ActAttachmentModel
{
AttachmentContent = t.AttachmentContent,
ActAttachmentId = cartableAct.CartableActId,
ActId = cartableAct.CartableActId,
CreationDate = DateTime.Now,
Creator = party.PartyId,
FileExtension = t.FileExtension,
Title = t.Title,
MimeType = t.MimeType
}).ToList();
cartableAct.ActAttachments = attachments;
cartableActs.Add(cartableAct);
cartable.CartableActs = cartableActs;
_dbContext.Cartables.Add(cartable);
_dbContext.SaveChangesAsync(cancellationToken);
}
else
{
var cartableActs = new List<CartableActModel>();
var cartable = new CartableStateModel()
{
ClaimId = request.ClaimId,
CreationDate = DateTime.Now,
StatusCode = (int)Enumeration.StateType.Finished,
};
var cartableAct = new CartableActSatisficationModel()
{
ActCode = (int)Enumeration.ActType.SatisficationCustomer,
ActorId = party.PartyId,
CartableStateId = cartable.CartableStateId,
ChangeDate = DateTime.Now,
IsSatisfy = false,
SatisfyLevel = "1",
};
var attachments = request.Attachments.Select(t => new ActAttachmentModel
{
AttachmentContent = t.AttachmentContent,
ActAttachmentId = cartableAct.CartableActId,
ActId = cartableAct.CartableActId,
CreationDate = DateTime.Now,
Creator = party.PartyId,
FileExtension = t.FileExtension,
Title = t.Title,
MimeType = t.MimeType
}).ToList();
var outBox = new OutBoxModel
{
SentType = "SMS",
ClaimId = request.ClaimId,
IsSent = false,
PartyCode = request.PartyCode,
IsCustomer = true
};
cartableAct.ActAttachments = attachments;
cartableActs.Add(cartableAct);
cartable.CartableActs = cartableActs;
_dbContext.Cartables.Add(cartable);
_dbContext.OutBoxes.Add(outBox);
_dbContext.SaveChangesAsync(cancellationToken);
}
}
I don't know how can I fix this error I search a lot of source but I can't understand which value should return if you know this I would thank you.
Change your metod header
public async Task Handle(CreateCompletedActCommand request, CancellationToken cancellationToken)
{
....your code
}

Task.WhenAll gives an error

public async virtual Task<ActionResult> Store(int? id, int? mainRoadID, int? segmentID, int? cityid, string serverMessage = "")
{
UserTrafficReport_Create model = await Task.WhenAll(GetNewModel, InitialCameras, GetMonitoredWaysListAndPushViewData(mainRoadID, segmentID, cityid));
return View(model);
}
The previous function has an error line ... I can't find the exact error
Error 1358 The best overloaded method match for 'System.Threading.Tasks.Task.WhenAll(params System.Threading.Tasks.Task[])' has some invalid arguments
And those are the three functions used in When All
public async virtual Task<UserTrafficReport_Create> GetNewModel(int? id, int? mainRoadID, int? segmentID, int? cityid)
{
var model = new UserTrafficReport_Create();
var serializer = new JavaScriptSerializer();
if (id != null && id > 0)
{
var report = _repository.FindOne<UserTrafficReport>((int)id);
model.InjectFrom(report);
model.Comments = report.Comments;
if (report.PictureSize.HasValue && report.PictureSize > 0)
model.photo_name = report.ID.ToString(CultureInfo.InvariantCulture);
if (report.RoadID != null)
{
model.RoadID = (int)report.RoadID;
_repository.FindOne<MonitoredWay>((int)report.RoadID);
}
FakeUsers(report.UserID);
model.RoadStatus = report.RoadStatus ?? 99;
if (report.traffic_rating >= 0)
model.traffic_rating = report.traffic_rating;
else
model.traffic_rating = null;
}
else
{
var fakeGroup = _repository.First<UserGroup>(g => g.Name.Contains("Fake"));
var fakeGroupId = 3;
if (fakeGroup != null)
fakeGroupId = fakeGroup.ID;
var dbNamesList = (from userAD in _context.UserAdditionalDatas
join groups in _context.UserMultiGroups on userAD.ID equals groups.UserDataId
join aspUser in _context.AspnetUsers on userAD.ID equals aspUser.ID
where (groups.UserGroupId == fakeGroupId)
select new
{
name = userAD.FirstName,
UserName = aspUser.Username,
userId = aspUser.ID
}).Distinct().ToList();
if (dbNamesList.Any())
{
var randomedList = dbNamesList.Randomize();
var fakeUser = randomedList.FirstOrDefault();
if (fakeUser != null)
{
model.GuestName = fakeUser.name;
model.UserID = fakeUser.userId;
}
}
model.RoadID = segmentID.GetValueOrDefault(-1);
model.traffic_rating = -1;
if (cityid != null)
model.CityId = (int)cityid;
}
return model;
}
.
public async virtual Task InitialCameras(int? cityid,string serverMessage = "")
{
var serializer = new JavaScriptSerializer();
var conditionslist = CreateListFromSingle(
new
{
value = "99",
text = "Not Specified"
}
);
conditionslist.Add(new { value = "4", text = "Accident" });
conditionslist.Add(new { value = "2", text = "Danger" });
conditionslist.Add(new { value = "3", text = "Road Work" });
string outputOfConditions = serializer.Serialize(conditionslist);
ViewData["ConditionsListSerialized"] = outputOfConditions;
var conditionslistitems =
(from condition in conditionslist
select new SelectListItem
{
Value = condition.value,
Text = condition.text
}).ToList();
ViewBag.ConditionsList = conditionslistitems;
ViewData["serverMsg"] = serverMessage;
if (cityid == null || cityid == -1)
{
var cameras = _context.Cameras.Select(c => new
{
value = c.Id,
text = c.Name
}).ToList();
cameras.Insert(0, new { value = (long)0, text = "--Select a Camera --" });
ViewData["Cameras"] = serializer.Serialize(cameras);
}
else
ViewData["Cameras"] = GetCityCameras((int)cityid);
}
..
private async Task GetMonitoredWaysListAndPushViewData(int? roadID = null, int? segmentID = null, int? cityID = null, Guid? reporterId = null)
{
int? id = cityID;
var dbWaysList =
_context.MonitoredWays.Where(
m =>
!m.IsTest &&
(m.RoadID != null && m.Road.AppOrder >= 0 && (id <= 0 || id == null)
? m.Road.AreaID > 0
: m.Road.AreaID == id));
var xWayseSelectList = (from s in dbWaysList
select new
{
OppId = s.OppositeSegment ?? 0,
Value = s.ID,
Title = s.EnglishName,
RoadTitle = s.Road.EnglishName
}).ToList().Distinct();
var repsList = (from s in xWayseSelectList//context.MonitoredWays
select new SelectListItem
{
Value = s.Value.ToString(CultureInfo.InvariantCulture),
Text = string.IsNullOrEmpty(s.RoadTitle) ? s.Title : s.RoadTitle + " (" + s.Title + ")",
Selected = segmentID != null && (segmentID.Value == s.Value)
}).Distinct().ToList();
var serializer = new JavaScriptSerializer();
string wayseSelectListOppId = serializer.Serialize(xWayseSelectList);
string outputOfAreas = serializer.Serialize(repsList);
ViewData["MonitoredWaysListSerialized"] = outputOfAreas;
ViewData["OppositeMonitoredWays"] = wayseSelectListOppId;
ViewBag.MonitoredWaysList = repsList;
var conditionslist = CreateListFromSingle(
new
{
value = "99",
text = "Not Specified"
}
);
conditionslist.Add(new { value = "4", text = "Accident" });
conditionslist.Add(new { value = "2", text = "Danger" });
conditionslist.Add(new { value = "3", text = "Road Work" });
string outputOfConditions = serializer.Serialize(conditionslist);
ViewData["ConditionsListSerialized"] = outputOfConditions;
var conditionslistitems =
(from condition in conditionslist
select new SelectListItem
{
Value = condition.value,
Text = condition.text
}).ToList();
ViewBag.ConditionsList = conditionslistitems;
var ratingslist = CreateListFromSingle(
new
{
value = "0",
text = "V. Bad"
}
);
ratingslist.Add(new { value = "1", text = "Bad" });
ratingslist.Add(new { value = "2", text = "Average" });
ratingslist.Add(new { value = "3", text = "Good" });
ratingslist.Add(new { value = "3", text = "V. Good" });
ViewBag.Ratingslist = ratingslist;
string outputOfRatings = serializer.Serialize(ratingslist);
ViewData["RatingsListSerialized"] = outputOfRatings;
if (roadID != null)
{
var rod = _context.Roads.FirstOrDefault(r => r.ID == roadID);
if (rod != null)
{
cityID = rod.AreaID;
}
}
var dbAreassList = _context.Cities.ToList();
var areas =
(from area in dbAreassList
select new SelectListItem
{
Value = area.ID.ToString(CultureInfo.InvariantCulture),
Text = area.EnglishName,
Selected = cityID != null && (cityID.Value == area.ID)
}).ToList();
ViewBag.AreasList = areas;
var areasList = (from s in _context.Cities
select
new
{
id = s.ID,
text = s.EnglishName
}).ToList();
serializer = new JavaScriptSerializer();
string outputOfAreas1 = serializer.Serialize(areasList);
ViewData["AreasListSerialized"] = outputOfAreas1;
var fakeGroup = _repository.First<UserGroup>(g => g.Name.Contains("Fake"));
var fakeGroupId = 3;
if (fakeGroup != null)
fakeGroupId = fakeGroup.ID;
var dbNamesList = (from userAD in _context.UserAdditionalDatas
join groups in _context.UserMultiGroups on userAD.ID equals groups.UserDataId
join aspUser in _context.AspnetUsers on userAD.ID equals aspUser.ID
where (groups.UserGroupId == fakeGroupId)
select new
{
Text = userAD.FirstName,
Value = userAD.ID,
Selected = false
//Email = aspUser.Username
}).Distinct().ToList();
var namess = dbNamesList.Select(s => new SelectListItem
{
Text = s.Text,
Value = s.Value.ToString(),
Selected = s.Selected
}).ToList();
if (reporterId != null)
{
var member = _repository.FindOne<UserAdditionalData>((Guid)reporterId);
if (member != null)
{
namess.Add(new SelectListItem
{
Text = member.FirstName,
Value = member.ID.ToString(),
Selected = true
});
}
}
var random = new Random();
if (!namess.Any(n => n.Selected))
{
int rand = random.Next(0, namess.Count - 1);
namess[rand].Selected = true;
}
ViewBag.FakeUsersList = namess;
}
A few things wrong with this line:
UserTrafficReport_Create model =
await Task.WhenAll(
GetNewModel,
InitialCameras,
GetMonitoredWaysListAndPushViewData(mainRoadID, segmentID, cityid));
Task.WhenAll takes a collection of Task instances as an argument.
You're passing 2 delegates and a task. You probably meant to actually call the first two methods, so that they'll return a task?
Task.WhenAll returns a Task. Awaiting that task won't return anything, so you won't be able to assign anything to model.
Task<UserTrafficReport_Create> modelFactoryTask = GetNewModel(...);
await Task.WhenAll(
modelFactoryTask ,
InitialCameras(...),
GetMonitoredWaysListAndPushViewData(mainRoadID, segmentID, cityid));
UserTrafficReport_Create model = modelFactoryTask.Result;

LINQ2SQL: Using the parent ID in a child object twice - parent ID equals zero

I've got the following code and I wish to set the AssignmentID and the ToDoAssignmentID to the same value. Setting AssignmentID to workOrder.AssignmentID works just fine, but setting ToDoAssignmentID to workOrder.AssignmentID results in ToDoAssignmentID being set to 0. Why is that?
workOrder.ClientID = this.Client.ClientID;
workOrder.AssignmentID = this.WorkOrderID;
workOrder.AssignmentNumber = this.GetNextWorkOrderNumber(this.Client);
workOrder.CustomerID = this._CustomerID;
workOrder.DateCreated = this.Created;
workOrder.DatoAvtaltStart = this.AgreedStart == DateTime.MinValue ? new DateTime().MinSDTValue() : this.AgreedStart;
workOrder.DatoAvtaltSlutt = this.AgreedEnd == DateTime.MinValue ? new DateTime().MinSDTValue() : this.AgreedEnd;
workOrder.DateStopped = this.Ended == DateTime.MinValue ? new DateTime().MinSDTValue() : this.Ended;
workOrder.CreatedByEmployeeID = this._CreatedByEmployeeID;
workOrder.ResponsibleEmployeeID = this._ResponsibleEmployeeID;
workOrder.KoordinatorAnsattId = this._CoordinatorEmployeeID;
workOrder.Description = this.Description;
workOrder.Notes = this.Notes;
workOrder.EstimertTimerFra = this.EstimatedHoursFrom;
workOrder.EstimertTimerTil = this.EstimatedHoursTo;
workOrder.EstimatedBillingDate = this.EstimatedBillingDate;
workOrder.Priority = (byte)this.Priority;
workOrder.OBS = this.OBS;
workOrder.CustomerReference = this.CustomersReference;
workOrder.InterntOrdrenr = this.InternalOrderNumber;
workOrder.EksterntOrdrenr = this.ExternalOrderNumber;
workOrder.AssignmentStatusID = this.WorkOrderStatusID;
foreach (var activity in this.Activities)
{
var ProductID = 0;
try
{
ProductID = activity.Product.ProductID;
}
catch (Exception ex)
{
}
workOrder.Activities.Add(new Activity()
{
ActivityID = activity.ActivityID,
ClientID = activity.Client.ClientID,
AssignmentID = workOrder.AssignmentID,
Description = activity.Description,
Notes = activity.Notes,
IsBillable = activity.Billable,
Priority = (byte)activity.Priority,
ActivityTypeID = activity.ActivityType.TypeID,
PerformedByEmployeeID = activity.PerformedByEmployee.EmployeeID,
ProductID = ProductID,
ToDo = activity.IsPlanned,
ToDoAssignmentID = workOrder.AssignmentID,
ToDoCustomerID = workOrder.CustomerID
});
}
workOrderContext.SubmitChanges();
The key is not to think database style, but ORM style.
So instead of setting keys, you assign entities.
so change
ToDoAssignmentID = workOrder.AssignmentID
to (most probable guess of tablenames, check the definition of your entity) the following assignment of entities
ToDoAssignment = workOrder
This will be handled during SubmitChanges as well.

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