Change Devexpress export row value - c#

My Controller:
public ActionResult ExportTo(ExportFormat exportFormat = ExportFormat.Xlsx)
{
ExportType exportType = GridViewHelper.ExportTypes.SingleOrDefault(x => x.Format == exportFormat);
if (exportType != null)
{
var modelList= modelRepository.GetAll();
var gridviewSettings = CreateExportGridViewSettings();
if(gridviewSettings != null)
return exportType.Method(gridviewSettings, modelList);
}
return RedirectToAction("Index");
}
...
private GridViewSettings CreateExportGridViewSettings()
{
var settings = new GridViewSettings
{
Name = "Export",
CallbackRouteValues = new {Controller = "MyController", Action = "List"},
Width = Unit.Percentage(100)
};
settings.Columns.Add("Id", Resources.Id);
!!! ---- !!!
...
}
!!! ---- !!! <- Here I want to add column. the row output in this column must be YES if value is True and NO if value is False

settings.Columns.Add(set =>
{
set.FieldName = "IsSomething";
set.Caption = "Is Something";
set.UnboundType = DevExpress.Data.UnboundColumnType.String;
set.UnboundExpression = "Iif([IsSomething]==True, 'Yes', 'No')";
});

Related

Passing List of Data to Other Controller

So I have action Method in my controller which get data from the CSV file which I uploaded through web
I want to pass that data to Insert controller so data from the CSV will automatically inserted to tables in my DB and pass it to view
I'm using CSV HELPER, MVC
public ActionResult ImportCSV(HttpPostedFileBase file, int compID)
{
var compName = db.CourierCompanies.Find(compID);
string path = null;
List<MyViewModel> csvD = new List<MyViewModel>();
try
{
if(file.ContentLength > 0)
{
var fileName = Path.GetFileName(file.FileName);
path = AppDomain.CurrentDomain.BaseDirectory + "upload\\" + fileName;
file.SaveAs(path);
var csv = new CsvReader(new StreamReader(path));
var invoCSV = csv.GetRecords<ImportCsV>();
foreach(var i in invoCSV)
{
MyViewModel iCSV = new MyViewModel();
iCSV.CustID = i.cust_id;
iCSV.Fullname = i.fullname;
iCSV.CustComp = i.company;
iCSV.InvoiceNo = i.rec_no;
iCSV.InsertDate = DateTime.Parse(i.doc_dt);
iCSV.Road = i.w_addr1;
iCSV.City = i.w_city;
iCSV.Zip = i.w_zip;
iCSV.Phone = i.w_phone;
iCSV.Status = "BelumTerkirim";
iCSV.compID = compID;
iCSV.CompName = compName.CompName;
iCSV.StatDate = DateTime.Now;
csvD.Add(iCSV);
}
}
}
catch
{
ViewData["Error"] = "Upload Failed";
}
return View();
}
Insert Controller
public ActionResult Create( MyViewModel model, int compID, HttpPostedFileBase file)
{
if (file != null)
{
using (MemoryStream ms = new MemoryStream())
{
file.InputStream.CopyTo(ms);
model.Image = ms.GetBuffer();
}
}
var cust = new Customer()
{
CustID = model.CustID,
Phone = model.Phone,
CustComp = model.CustComp,
Fullname = model.Fullname
};
var addrDet = new AddrDetail()
{
Road = model.Road,
City = model.City,
Zipcode = model.Zip
};
var invoice = new Invoice()
{
InvoiceNo = model.InvoiceNo
};
var stat = new Status()
{
Status1 = model.Status,
StatDate = model.StatDate,
Ket = model.Ket
};
var image = new Models.Image()
{
Image1 = model.Image
};
var detail = new DetailPengiriman()
{
NamaPenerima = model.NamaPenerima,
StatusPenerima = model.StatusPenerima,
TrDate = model.TrDate,
InsertDate = model.InsertDate
};
if (ModelState.IsValid )
{
//customer
db.Customers.Add(cust);
detail.CustID = cust.CustID;
invoice.CustID = cust.CustID;
//addrDet
db.AddrDetails.Add(addrDet);
cust.AddrDetID = addrDet.AddrDetID;
//invoice
db.Invoices.Add(invoice);
stat.InvoiceNo = invoice.InvoiceNo;
image.InvoiceNo = invoice.InvoiceNo;
detail.InvoiceNo = invoice.InvoiceNo;
//status
db.Status.Add(stat);
detail.StatusID = stat.StatusID;
////image
db.Images.Add(image);
detail.ImageID = image.ImageID;
//detail
detail.CompID = compID;
db.DetailPengirimen.Add(detail);
db.SaveChanges();
return RedirectToAction("Index", new { compID = detail.CompID});
}
return View();
}
You can abstract that business logic in another class and instantiate it inside your CSV action.
This way your can call your methods for inserting customers from both actions!

Setting RouteValueDictionary html attributes differently on first object in a foreach loop

I have a fairly large method which is returning Radio buttons based fundamentally on an enum.
foreach (var name in names)
{
//other stuff
var id = string.Format(
"{0}_{1}_{2}",
htmlHelper.ViewData.TemplateInfo.HtmlFieldPrefix,
metaData.PropertyName,
name
);
var attribs = new RouteValueDictionary(htmlAttributes) { { "id", id }, { "checked", true } }; //<- I want this to be true on first, false on everything after
var radio = htmlHelper.RadioButtonFor(expression, name, attribs).ToHtmlString();
var field = fields.Single(f => f.Name == name);
//more stuff
}
I am arranging my array names in a certain order before I drop into the loop, the order stipulates that the first radio button should be checked when finally rendered to my page, and this is what I'm struggling with as, it is checking each and every item in the for each, resulting in the last item to go through being the one left checked.
I have tried adding something like:
bool firstRadioButton = true;
...outside the loop however I am loosing the reference to attribs etc. when I start placing them inside if statements and I cant seem to declare them without their required parameters outside the if statements.
Can anyone suggest a way that I can only set checked to true for attribs on the first pass of the foreach?
It's not clear what you were doing with firstRadioButton, but something like this should work:
bool firstRadioButton = true;
foreach (var name in names)
{
// ....
RouteValueDictionary attribs = null;
if (firstRadioButton)
{
attribs = new RouteValueDictionary(htmlAttributes) { { "id", id }, { "checked", true } }; //<- I want this to be true on first, false on everything after
firstRadioButton = false;
}
else
{
attribs = new RouteValueDictionary(htmlAttributes) { { "id", id }};
}
// ...
}
Use instead foreach loop for.
for (int i = 0; i < names.length; i++)
{
var name = names[i];
var id = string.Format(
"{0}_{1}_{2}",
htmlHelper.ViewData.TemplateInfo.HtmlFieldPrefix,
metaData.PropertyName,
name
);
var attribs = new RouteValueDictionary(htmlAttributes) { { "id", id }, { "checked", i == 0 ? true : false} };
var radio = htmlHelper.RadioButtonFor(expression, name, attribs).ToHtmlString();
var field = fields.Single(f => f.Name == name);
}
Or in foreach you can do
bool isFirst = true;
foreach (var name in names)
{
var id = string.Format(
"{0}_{1}_{2}",
htmlHelper.ViewData.TemplateInfo.HtmlFieldPrefix,
metaData.PropertyName,
name
);
var attribs = new RouteValueDictionary(htmlAttributes) { { "id", id }, { "checked", isFirst} };
var radio = htmlHelper.RadioButtonFor(expression, name, attribs).ToHtmlString();
var field = fields.Single(f => f.Name == name);
if(isFirst)
{
isFirst = false;
}
}

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;

ASP devexpress How to filter gridview by combobox selected item

I have problem with interaction from combobox to gridview. My use case is: User select from combox value and gridview will update its content by value from combobox. I'm using devexpress controls in aps webapplication.
Model:
public class MyModel
{
public IEnumerable<Person> Persones()
{
return DataProvider.GetPersons();
}
public IEnumerable<Role> Roles()
{
return DataProvider.GetRoles();
}
public int SelectedRoleId { get; set; }
}
Index view:
#model DXWebApplication1.Models.MyModel
#Html.DevExpress().Splitter(settings => {
settings.Name = "InnerContentSplitter";
settings.AllowResize = true;
settings.Orientation = System.Web.UI.WebControls.Orientation.Vertical;
settings.FullscreenMode = false;
settings.SeparatorVisible = true;
settings.Styles.Pane.Border.BorderWidth = System.Web.UI.WebControls.Unit.Pixel(0);
settings.Styles.Pane.Paddings.Padding = System.Web.UI.WebControls.Unit.Pixel(0);
settings.Panes.Add(pane => {
pane.Name = "InnerContentHeader";
pane.PaneStyle.BorderBottom.BorderWidth = System.Web.UI.WebControls.Unit.Pixel(1);
pane.PaneStyle.CssClass = "headerPane";
pane.SetContent("<h2>Header of View</h2>");
});
settings.Panes.Add(pane =>
{
pane.Name = "InnerContent01";
pane.PaneStyle.CssClass = "mainContentPane01";
pane.PaneStyle.BackColor = System.Drawing.Color.White;
pane.Size = System.Web.UI.WebControls.Unit.Pixel(150);
pane.SetContent(() =>
{
Html.DevExpress().Splitter(splitSettings =>
{
splitSettings.Name = "Splitter001";
splitSettings.AllowResize = false;
splitSettings.Orientation = System.Web.UI.WebControls.Orientation.Horizontal;
splitSettings.FullscreenMode = false;
splitSettings.SeparatorVisible = false;
splitSettings.Styles.Pane.Border.BorderWidth = System.Web.UI.WebControls.Unit.Pixel(0);
splitSettings.Styles.Pane.Paddings.Padding = System.Web.UI.WebControls.Unit.Pixel(0);
splitSettings.Panes.Add(innerpane =>
{
innerpane.AutoWidth = true;
innerpane.Name = "Content001";
innerpane.PaneStyle.BackColor = System.Drawing.Color.White;
innerpane.PaneStyle.Paddings.Padding = System.Web.UI.WebControls.Unit.Pixel(10);
innerpane.PaneStyle.Paddings.PaddingTop = System.Web.UI.WebControls.Unit.Pixel(20);
innerpane.SetContent(() => Html.RenderPartial("ComboBoxPartialView", Model));
});
splitSettings.Panes.Add(innerpane =>
{
innerpane.Name = "Content002";
innerpane.PaneStyle.BackColor = System.Drawing.Color.White;
innerpane.SetContent(() => Html.RenderPartial("GridViewPartialView", Model));
});
}).Render();
});
});
}).GetHtml()
Grid partial view:
#Html.DevExpress().GridView(
settings =>
{
settings.Name = "GridView";
settings.CallbackRouteValues = new { Controller = "Home", Action = "GridViewPartialView" };
settings.Width = System.Web.UI.WebControls.Unit.Percentage(100);
settings.SettingsPager.Visible = false;
settings.SettingsPager.PageSize = 20;
settings.Settings.VerticalScrollBarMode = ScrollBarMode.Visible;
settings.Settings.VerticalScrollableHeight = 350;
settings.Settings.VerticalScrollBarStyle = GridViewVerticalScrollBarStyle.Virtual;
settings.ControlStyle.Paddings.Padding = System.Web.UI.WebControls.Unit.Pixel(0);
settings.ControlStyle.Border.BorderWidth = System.Web.UI.WebControls.Unit.Pixel(0);
settings.ControlStyle.BorderBottom.BorderWidth = System.Web.UI.WebControls.Unit.Pixel(1);
// DXCOMMENT: Configure grid's columns in accordance with data model fields
settings.Columns.Add("Id");
settings.Columns.Add("Name");
settings.Columns.Add("RoleId");
}).Bind(Model.Persones()).GetHtml()
Combobox partial view
#Html.DevExpress().ComboBox(cmbSettings =>
{
cmbSettings.Name = "RoleId";
cmbSettings.Width = System.Web.UI.WebControls.Unit.Pixel(200);
cmbSettings.Properties.ValueField = "Id";
cmbSettings.Properties.TextField = "RoleName";
cmbSettings.Properties.ValueType = typeof(int);
cmbSettings.SelectedIndex = 0;
cmbSettings.Properties.IncrementalFilteringMode = IncrementalFilteringMode.Contains;
cmbSettings.Properties.ClientSideEvents.SelectedIndexChanged =
"function(s, e) {GridView.PerformCallback();}";
}).BindList(Model.Roles()).Bind(Model.SelectedRoleId).GetHtml()
Controler:
public class HomeController : Controller
{
public ActionResult Index([ModelBinder(typeof(DevExpressEditorsBinder))]MyModel mo)
{
return View(mo);
}
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult GridViewPartialView([ModelBinder(typeof(DevExpressEditorsBinder))]MyModel mo)
{
return PartialView("GridViewPartialView", mo);
}
}
So I'm expecting in my controler updated model, but everitime I get model with not actual data. What I missed in my model usage? What's the best way to implement my use case?
I discuss this issue with peoples from DevExpress and they helped me to solve this.
Solution is here

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