How to get language native name (endonym) from country code in C#? - c#

Can I get the language name from country code? I have create a program to let user select localization for currency display purposes. This is the program that do the configuration.
CultureInfo[] cinfo = CultureInfo.GetCultures(CultureTypes.AllCultures & ~CultureTypes.NeutralCultures);
Dictionary<string, string> Misc_dictLocalization = new Dictionary<string, string>();
var sortList = cinfo.OrderBy(p => p.EnglishName).ToList();
foreach (CultureInfo cul in sortList)
{
//Add country name and bind with country code
Misc_dictLocalization.Add(cul.Name, cul.EnglishName);
}
Misc_LocalizationCombobox.DataSource = new BindingSource(Misc_dictLocalization, null);
Misc_LocalizationCombobox.DisplayMember = "Value";
Misc_LocalizationCombobox.ValueMember = "Key";
On Combobox selection,
string key = ((KeyValuePair<string, string>)Misc_LocalizationCombobox.SelectedItem).Key;
string value = ((KeyValuePair<string, string>)Misc_LocalizationCombobox.SelectedItem).Value;
Misc_CountryCode.Text = key;
decimal dec = Convert.ToDecimal(Misc_DecimalNumber.Text);
Misc_CurrencyFormat.Text = dec.ToString("C", new CultureInfo(Misc_CountryCode.Text));
I'm currently using
var allCultures = System.Globalization.CultureInfo.GetCultures(System.Globalization.CultureTypes.AllCultures);
string countrycode = "ar-SA";
string langname = allCultures.FirstOrDefault(c => c.Name == countrycode).DisplayName;
//langname will have "Arabic"
How to get native name (endonym) from country code?
Based from the Wikipedia List of ISO 639-1 codes,
I need to get;
1) Philippines(fil-PH) => Tagalog
2) Vietnam(vi-VN) => Tiếng Việt
3) United States(en-US) => English
4) Arabic(ar-SA) => العربية
SOLUTION SOLVED (credit Nhan Phan)
..Exactly like how I would want
DirectoryInfo di = new DirectoryInfo(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, #"Language"));
FileInfo[] Files = di.GetFiles("*.xaml");
int ID = 1;
var allCultures = System.Globalization.CultureInfo.GetCultures(System.Globalization.CultureTypes.AllCultures);
LocalizationProperty.LangLoc = new List<AppModel.LanguageLocalization>();
foreach (FileInfo file in Files)
{
string countrycode = file.Name.Replace(".xaml", "").Replace("Resources.", "");
int index = countrycode.LastIndexOf("-");
string ISOName = countrycode;
if (index > 0)
ISOName = ISOName.Substring(0, index);
string langname = allCultures.FirstOrDefault(c => c.Name == ISOName).NativeName;
AppModel.LanguageLocalization applang = new AppModel.LanguageLocalization
{
LanguageID = ID,
CountryCode = countrycode,
LanguageName = langname
};
LocalizationProperty.LangLoc.Add(applang);
ID += 1;
}
string langjson = Newtonsoft.Json.JsonConvert.SerializeObject(LocalizationProperty.LangLoc, Formatting.Indented);
LogEvents($"[{PageTitle} Language file retrieved. {langjson}", EventLogEntryType.Information);
Object2JsonString:-
[
{
"LanguageID":1,
"CountryCode":"ar-SA",
"LanguageName":"العربية"
},
{
"LanguageID":2,
"CountryCode":"en-US",
"LanguageName":"English"
},
{
"LanguageID":3,
"CountryCode":"fil-PH",
"LanguageName":"Filipino"
},
{
"LanguageID":4,
"CountryCode":"ms-MY",
"LanguageName":"Melayu"
},
{
"LanguageID":5,
"CountryCode":"syr-SY",
"LanguageName":"ܣܘܪܝܝܐ"
},
{
"LanguageID":6,
"CountryCode":"ta-IN",
"LanguageName":"தமிழ்"
},
{
"LanguageID":7,
"CountryCode":"tt-RU",
"LanguageName":"Татар"
},
{
"LanguageID":8,
"CountryCode":"vi-VN",
"LanguageName":"Tiếng Việt"
},
{
"LanguageID":9,
"CountryCode":"zh-CN",
"LanguageName":"中文"
}
]
The view:-

You can retrieve it via NativeName instead of DisplayName:
var allCultures = System.Globalization.CultureInfo.GetCultures(System.Globalization.CultureTypes.AllCultures);
string countrycode = "ar-SA";
string langname = allCultures.FirstOrDefault(c => c.Name == countrycode).NativeName;

Related

Filtering List Objects Based on Property String

I have a list of FTPFileItems objects that I need to sort and get the latest version based on the Version in the filename.
class FtpFileInfo
{
string FileName;
DateTime FileDate;
long FileSize;
FtpFileType FileType;
}
Example Filename Data in each object
FileName = "XXX_AE_V1_20160812132126.xml"
FileName = "XXX_AE_V2_20160912142126.xml"
FileName = "XXX_AE_V3_20161012152126.xml"
FileName = "XXX_AU_V1_20190213142439.xml"
FileName = "XXX_AU_V2_20190313142439.xml"
FileName = "XXX_AU_V3_20190413142439.xml"
FileName = "XXX_AU_V4_20190513142439.xml"
FileName = "XXX_BR_V1_20170828214049.xml"
FileName = "XXX_BR_V2_20170928214049.xml"
FileName = "XXX_BR_V3_20171028214049.xml"
FileName = "XXX_BR_V4_20171038214049.xml"
FileName = "XXX_BR_V6_20171048214049.xml"
I need to compress the list to the highest file version by country objects. So the list should end up like this but the complete List objects, just showing the filename part:
FileName = "XXX_AE_V3_20161012152126.xml"
FileName = "XXX_AU_V4_20190513142439.xml"
FileName = "XXX_BR_V6_20171048214049.xml"
Here is what I am trying, but I am not getting what I need. I am losing my original object because of the select and not getting highest version number.
var res = xmlFileNames.Select(s => new
{
XXX = s.FileName.Split('_')[0],
Country = s.FileName.Split('_')[1],
Version = s.FileName.Split('_')[2],
FileDate = s.FileName.Split('_')[3]
})
.OrderByDescending(x => x.Version)
.OrderBy(x => x.Country)
;
You are correct that the first select statement is preventing you from maintaining the original object. My suggestion would be to group the collection by the second element (you have called this Country). Then select the one with the highest version as shown below. Finally order by the country.
files.GroupBy(x => x.FileName.Split(new char[] { '_' })[1])
.Select(x => x.OrderByDescending(y => y.FileName.Split(new char[] { '_' })[2]).First())
.OrderBy(x => x.FileName.Split(new char[] { '_' })[1]);
A full solution is shown below with an example collection based on your example.
List<FtpFileInfo> files = new List<FtpFileInfo>() {
new FtpFileInfo { FileName = "XXX_AE_V1_20160812132126.xml" },
new FtpFileInfo { FileName = "XXX_AE_V2_20160912142126.xml" },
new FtpFileInfo { FileName = "XXX_AE_V3_20161012152126.xml" },
new FtpFileInfo { FileName = "XXX_AU_V1_20190213142439.xml" },
new FtpFileInfo { FileName = "XXX_AU_V2_20190313142439.xml" },
new FtpFileInfo { FileName = "XXX_AU_V3_20190413142439.xml" },
new FtpFileInfo { FileName = "XXX_AU_V4_20190513142439.xml" },
new FtpFileInfo { FileName = "XXX_BR_V1_20170828214049.xml" },
new FtpFileInfo { FileName = "XXX_BR_V2_20170928214049.xml" },
new FtpFileInfo { FileName = "XXX_BR_V3_20171028214049.xml" },
new FtpFileInfo { FileName = "XXX_BR_V4_20171038214049.xml" },
new FtpFileInfo { FileName = "XXX_BR_V6_20171048214049.xml" },
};
IOrderedEnumerable<FtpFileInfo> orders = files.GroupBy(x => x.FileName.Split(new char[] { '_' })[1])
.Select(x => x.OrderByDescending(y => y.FileName.Split(new char[] { '_' })[2]).First())
.OrderBy(x => x.FileName.Split(new char[] { '_' })[1]);
foreach (FtpFileInfo order in orders) {
Console.WriteLine(order.FileName);
}
The output I receive is shown below which matches what you mentioned was the desired output.
XXX_AE_V3_20161012152126.xml
XXX_AU_V4_20190513142439.xml
XXX_BR_V6_20171048214049.xml
You could try to use Select scope to define it as a result, but use the scope to avoid calling Slipt for each property (performance). Use OrderBy and ThenBy and you will get ordered as you want. Finally, use ToList method to get it in a better structure (list of anon objects) when a generic one.
var res = xmlFileNames.Select(s =>
{
var a = s.Split('_');
return new
{
XXX = a[0],
Country = a[1],
Version = a[2],
FileDate = a[3]
};
})
.OrderByDescending(x => x.Version)
.ThenBy(x => x.Country)
.ToList();
I left FtpFileType out because I didn't know what a valid value is but this should do it for ya.
c#Fiddle
using System;
using System.Collections.Generic;
using System.Linq;
public class Program
{
public class FtpFileInfo
{
public string FileName;
public DateTime FileDate;
public long FileSize;
public object FileType;
}
public static void Main()
{
var xmlFileNames = fillClasses();
var newXmlFileNames = new List<FtpFileInfo>();
var res = xmlFileNames.Select(s => new
{
Country = s.FileName.Split('_')[1],
Version = s.FileName.Split('_')[2],
ftpFileInfo = s
}).GroupBy(x => x.Country).Select(c=> new {
country = c.Key,
ftpFileInfo = c.OrderByDescending(t=> t.Version).First().ftpFileInfo
}).ToList();
foreach(var item in res.OrderBy(c=> c.country))
{
var ftpFileInfo = new FtpFileInfo();
ftpFileInfo.FileName = item.ftpFileInfo.FileName;
ftpFileInfo.FileDate = item.ftpFileInfo.FileDate;
ftpFileInfo.FileSize = item.ftpFileInfo.FileSize;
ftpFileInfo.FileType = item.ftpFileInfo.FileType;
newXmlFileNames.Add(ftpFileInfo);
}
foreach(var newXmlFileName in newXmlFileNames)
{
Console.WriteLine(string.Format("FileName: {0} FileDate: {1} FileSize: {2}", newXmlFileName.FileName, newXmlFileName.FileDate, newXmlFileName.FileSize));
}
}
public static List<FtpFileInfo> fillClasses()
{
var ftpFileInfoList = new List<FtpFileInfo>();
var fileNames = new List<string>()
{"XXX_AE_V1_20160812132126.xml", "XXX_AE_V2_20160912142126.xml", "XXX_AE_V3_20161012152126.xml", "XXX_AU_V1_20190213142439.xml", "XXX_AU_V2_20190313142439.xml", "XXX_AU_V3_20190413142439.xml", "XXX_AU_V4_20190513142439.xml", "XXX_BR_V1_20170828214049.xml", "XXX_BR_V2_20170928214049.xml", "XXX_BR_V3_20171028214049.xml", "XXX_BR_V4_20171038214049.xml", "XXX_BR_V6_20171048214049.xml"};
foreach (var fileName in fileNames)
{
ftpFileInfoList.Add(new FtpFileInfo()
{FileName = fileName, FileDate = DateTime.Now, FileSize = 11111, FileType = null});
}
return ftpFileInfoList;
}
}

Implementing search in mvc 4

I have a textbox where user types the string he needs to search. If the user enters only a single word string, then I am able to retrieve the correct data from database but if the user enters a multi-word string then my code fails.
I am using EntityFramework to get the data.
Here is my code to get the data using a single word string.
public ActionResult SearchResult(string search)
{
var j = objCon.Mobiles.Where(oh => oh.MobileName.Contains(search) || oh.Description.Contains(search));
List<Mobiles> prod = new List<Mobiles>();
foreach (var p in j)
{
Mobiles Mob = new Mobiles();
Mob.Description = p.Description;
Mob.ImgUrl = p.Url;
Mob.MobileName = p.MobileName;
Mob.Price = Convert.ToString(p.Price);
Mob.SlNo = p.SlNo;
prod.Add(Mob);
}
return View("~/Views/Product/Index.cshtml", prod);
}
I tried breaking the string into single word using split but could not get the correct data.
string str = null;
string[] strArr = null;
int count = 0;
str = //UserInput;
char[] splitchar = { ' ' };
strArr = str.Split(splitchar);
string str = null;
string[] strArr = null;
int count = 0;
str = search;
char[] splitchar = { ' ' };
strArr = str.Split(splitchar);
for (count = 0; count <= strArr.Length - 1; count++)
{
string i = strArr[count];
var j = objCon.Mobiles.Where(oh => oh.MobileName.Contains(i) || oh.Description.Contains(i));
//MessageBox.Show(strArr[count]);
foreach (var p in j)
{
Mobiles Mob = new Mobiles();
Mob.Description = p.Description;
Mob.ImgUrl = p.Url;
Mob.MobileName = p.MobileName;
Mob.Price = Convert.ToString(p.Price);
Mob.SlNo = p.SlNo;
prod.Add(Mob);
}
}
as I help you fix the problem - this is the final code
I Wrote an Example to Solve your Problem. Hope That You will Be Benefited From The Code.
First Create Mobile Class:
public class Mobile
{
public int Id { get; set; }
public string Name { get; set; }
public string Description { get; set; }
}
Next Create Extension method To Check If there is Value:
public static bool ContainsAny(this string haystack, params string[] needles)
{
foreach (var needle in needles)
{
if (haystack.Contains(needle))
return true;
}
return false;
}
Finally Create Main Body Along with Test Data:
using System;
using System.Collections.Generic;
using System.Linq;
namespace StackOverFlow
{
static class Program
{
static void Main()
{
List<Mobile> mobiles = new List<Mobile>
{
new Mobile{Id = 1,Name = "samsung galaxy s3",Description = "model"},
new Mobile{Id = 2,Name = "nokia N67",Description = "nokia n96 time"},
new Mobile{Id = 3,Name = "iphone 5s",Description = "test"},
new Mobile{Id = 4,Name = "samsung galaxy packet",Description = "this time"},
new Mobile{Id = 5,Name = "iphone ipad",Description = "now"},
new Mobile{Id = 6,Name = "glx c5",Description = "time"},
};
string[] search = "galaxy time 5s".Split(' ');
var result = mobiles.Where(c => c.Name.ContainsAny(search) ||
c.Description.ContainsAny(search)).ToList();
foreach (var item in result)
{
Console.WriteLine(item.Id + "-" + item.Name + "-" + item.Description);
}
Console.ReadKey();
}

How do i validate and give list of options after first wrong attempt in FormFlow Bot Framework

I am trying to build a bot using bot framework where i want to take string from user for a department name using FormFlow and if user enters wrong department name, I want to validate and give back a list of choices to choose from
DepartmentName string:
[Prompt("What is your department name? {||}")]
public string DepartmentName { get; set; }
Deaprtment name field is as following:
.Field(nameof(DepartmentName),
validate: async (state, response) =>
{
var value = (string)response;
var result = new ValidateResult() { IsValid = false, Feedback = "Department name is not valid"};
if (Enum.GetNames(typeof(Department)).Any(x => x.ToLower() == value))
{
result.IsValid = true;
result.Feedback = null;
result.Value = value;
}
return result;
})
Department enum is as following:
public enum Department
{
hr = 1,
sales,
marketing,
development,
qm
}
How can i prompt user with list of departments in enum if first attempt goes wrong? Thnaks
1) you can just add the options to the end of the Feedback:
.Field(nameof(DepartmentName),
validate: (state, response) =>
{
var value = (string)response;
string[] departments = Enum.GetNames(typeof(Department)).ToArray();
var feedback = $"Department name is not valid. Options:\n\n {String.Join("\n\n", departments)}";
var result = new ValidateResult() { IsValid = false,
Feedback = feedback };
if (departments.Any(x => x.ToLower() == value))
{
result.IsValid = true;
result.Feedback = null;
result.Value = value;
}
return Task.FromResult<ValidateResult>(result);
});
2) you can use the Choice class (normally for disambiguation):
.Field(nameof(DepartmentName),
validate: (state, response) =>
{
var value = (string)response;
string[] departments = Enum.GetNames(typeof(Department)).ToArray();
IEnumerable<Choice> choices = departments.Select(d => new Choice()
{
Description = new DescribeAttribute(d, null, null, null, null),
Terms = new TermsAttribute() { Alternatives = new[] { d } },
Value = d
}).ToArray();
var result = new ValidateResult()
{
IsValid = false,
Choices = choices,
Feedback = "Department name is not valid."
};
if (departments.Any(x => x.ToLower() == value))
{
result.IsValid = true;
result.Feedback = null;
result.Value = value;
}
return Task.FromResult<ValidateResult>(result);
});

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;

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