Casting and Concatenation in One line - c#

I have seen this done in code once or twice but can't find an example now. Until recently I was working in webforms and have switched to MVC. I have looked around and not found a whole lot on this. The code below is from my controller to pull in the values and display in my view model. I need to take the m.body.MembersId from MSMQ. I know what the problem is I just dont know how to use Linq like this.
The Situation , I need to do all this in one line. Cast the memberIds information that was originally a list named MembersId back to a list to display it but also do a string.join so that the entire list is displayed as one string. While I am aware of how to do both of those by themselves but to do in one line is proving beyond me. I will openly admit I am fairly new to linq and am learning as I go.
This is the class
public class MsgChildClass{
public string SourceSystem { get; set; }
public List<string> MemberIds { get; set; }
public string ParentId { get; set; }
public string Error { get; set; }
}
this is the function
public ActionResult GetAllMessages() {
string queueName = (ViewBag.QueueName != null) ? ViewBag.QueueName : Request.QueryString["queueName"];
Session["CurrentQueueName"] = queueName;
TempData["queueName"] = queueName;
ViewBag.QueueName = queueName;
var queue = _Queues[queueName];
queue.MessageReadPropertyFilter.ArrivedTime = true;
queue.MessageReadPropertyFilter.Body = true;
queue.Formatter = new JsonMessageFormatter();
var messages = queue.GetMessages();
var model = messages.Select(m =>
new ViewModel() {
Id = m.Id,
Date = m.ArrivedTime,
SourceSystem = ((MsgChildClass)m.Body).SourceSystem,
DeletedMemberIds = ((MsgChildClass)m.Body).DeletedMemberIds,//OrderByDescend(x => x); string.Join(",",((MsgChildClass)m.Body).DeletedMemberIds),
ParentMemberId = ((MsgChildClass)m.Body).ParentId,
Error = ((MsgChildClass)m.Body).Error,
QueName = queueName
}).ToList();
return Json(model.ToList(), JsonRequestBehavior.AllowGet);
}
View Model
public class ViewModel
{
[Required]
public string Id { get; set; }
//[Required]
[Display(Name = "Arrival Time")]
public DateTime Date { get; set; }
[Required]
[Display(Name = "Source System")]
public string SourceSystem { get; set; }
[Required]
[Display(Name = "Member Ids")]
public List <string> MemberIds { get; set; }
[Required]
[Display(Name = "Parent Member Id")]
public string ParentMemberId { get; set; }
[Display(Name = "Error")]
public string Error { get; set; }
[Display(Name = "QueName")]
public string QueName { get; set; }
}
This is what I have. All of it works correctly except the memberids. Debugging shows me that the memberids have the value but I am not drilling down far enough. So hopefully some one can help me out quite a bit as been quite few hours at this point. Google is great but he didnt help me out with this one.

It's cleaner and more efficient if you only cast once into a variable. And another advantage is that you can add a break point and look at msgChild.
var model = messages.Select(m =>
{
var msgChild = (MsgChildClass)m.Body;
return new ViewModel
{
Id = m.Id,
Date = m.ArrivedTime,
SourceSystem = msgChild.SourceSystem,
MemberIds = msgChild.MemberIds,
ParentMemberId = msgChild.ParentId,
Error = msgChild.Error,
QueName = queueName
};
}).ToList();

The code was correct which was the maddening part. debugger was telling me the values were there. But the part I didnt look at was how the datatable.js was loading the data for display. After seeing that was done incorrect, I corrected it and now the list is now displayed as string , string, string which is what I was needing so thanks every one

Related

Data from model not passing to view

I have some code that is functioning oddly and was wondering if anyone else hase come across this issue.
I have a view model that collects data from a database via a stored procedure and a vb object (no I do not know vb this is legacy)
When I execute the program the data is collected as expected via the controller. When I debug it I can see all of my parameters populating with information. However when it comes to the view it says that the parameters are null. I have included my code
Models:
public class PersonIncomeViewModel
{
public string IncomeTypeDesc { get; set; }
public string IncomeDesc { get; set; }
public string Income { get; set; }
}
public class PersonIncomeListViewModel
{
public int? PersonId { get; set; }
public List<PersonIncomeListItem> Incomes { get; set; }
public PersonIncomeListViewModel()
{
Incomes = new List<PersonIncomeListItem>();
}
}
public class PersonLookupViewModel : Queue.QueueViewModel
{
public int Action { get; set; }
public bool ShowAdvancedFilters { get; set; }
//Person Search Variables
[Display(Name = #"Search")]
public string SpecialSearch { get; set; }
[Display(Name = #"Person Id")]
public int? PersonId { get; set; }
[Display(Name = #"Full Name")]
public string FullName { get; set; }
[Display(Name = #"SSN")]
public string SSN { get; set; }
public string AddressStatus { get; set; }
public string EmploymentStatus { get; set; }
public PersonIncomeViewModel Income { get; set; }
public List<PersonIncomeListItem> Incomes { get; set; }
public PersonLookupViewModel()
{
Income = new PersonIncomeViewModel();
Incomes = new List<PersonIncomeListItem>();
}
}
Controller:
public ActionResult _Income(int id)
{
var vm = new PersonLookupViewModel();
var personManager = new dtPerson_v10_r1.Manager( ref mobjSecurity);
//var person = personManager.GetPersonObject((int)id, vIncludeIncomes: true);
var person = personManager.GetPersonObject(id, vIncludeIncomes: true);
var look = JsonConvert.SerializeObject(person.Incomes);
foreach (dtPerson_v10_r1.Income income in person.Incomes)
{
if (income.IncomeType_ID == 0)
{
var item = new PersonIncomeListItem
{
IncomeTypeDesc = "Unknown",
IncomeDesc = income.IncomeDesc,
Income = mobjFormat.FormatObjectToCurrencyString(income.Income)
};
vm.Incomes.Add(item);
}
if (income.IncomeType_ID == 1)
{
var item = new PersonIncomeListItem
{
IncomeTypeDesc = "Alimony",
IncomeDesc = income.IncomeDesc,
Income = mobjFormat.FormatObjectToCurrencyString(income.Income)
};
vm.Incomes.Add(item);
}
if (income.IncomeType_ID == 2)
{
var item = new PersonIncomeListItem
{
IncomeTypeDesc = "Child Support",
IncomeDesc = income.IncomeDesc,
Income = mobjFormat.FormatObjectToCurrencyString(income.Income)
};
vm.Incomes.Add(item);
}
}
return PartialView(vm);
}
View:
#using dtDataTools_v10_r1
#using ds_iDMS.Models.Person
#model ds_iDMS.Models.Person.PersonLookupViewModel
#{
var format = new dtDataTools_v10_r1.CustomFormat();
var newInitials = (Model.Income.IncomeTypeDesc.First().ToString() + Model.Income.IncomeDesc.First().ToString() + Model.Income.Income.First().ToString()).ToUpper();
}
using (Html.DSResponsiveRow(numberOfInputs: ExtensionMethods.NumberOfInputs.TwoInputs))
{
using (Html.DSCard(ExtensionMethods.Icon.CustomText, iconInitials: newInitials, color: ExtensionMethods.Colors.PrimaryBlue))
{
<div>#Model.Income.IncomeTypeDesc</div>
<div>#Model.Income.IncomeDesc</div>
<div>#Model.Income.Income</div>
}
}
There are some extensions that we have built but they are irrelevant to the issue
The line that errors out is this one:
var newInitials = (Model.Income.IncomeTypeDesc.First().ToString() + Model.Income.IncomeDesc.First().ToString() + Model.Income.Income.First().ToString()).ToUpper();
Which drives all of the extension methods on the view and as I run the debugger over it all of the parameters read null, however like I said when I run the debugger and check them in the controller they are populated properly.
Sorry about the long post but I wanted to ensure all the detail was there
This is how to pass the Object model to your Partial View
return PartialView("YourViewName", vm);
or using the Views path
return PartialView("~/YourView.cshtml", vm);
EDIT
Try starting your Action Method like this
var vm= new Person();
vm.PersonLookupViewModel = new PersonLookupViewModel();
Problem solved I had issues with some of my vb objects and had the vb person take a look at them and she fixed them.
Thank you for all the help
EDIT
What had to happen is the vb object had to be re-written and my logic was just fine as it was in the beginning. I marked the one response to my question as the answer because had it been in true MVC without vb objects attached to it, that would have worked perfectly

Visual Studio 2015 is truncating long strings on Text Visualizer

UPDATE: After some research, i've found out that that's an issue with Visual Studio 2015 and Text Visualizer, which you can see here.
To reproduce it, Open QuickWatch (Shift+F9) and in the search box, put new string(' ', 32769). After that click at the magnifier glass and you should see a "..." in the middle of the string...
So, changing my question, is there a way to fix this and make it not truncate, so i can copy without workarounds?
I have this piece of code:
JArray bundlesJson = (JArray)JObject.Parse(System.IO.File.ReadAllText(Server.MapPath("~/itens.json")))["bundles"]; // file "itens.json" can be found at http://pastebin.com/7K15yAVd
System.Text.RegularExpressions.Regex rgx = new System.Text.RegularExpressions.Regex(#"(?<sNome>.*?)\/(?<sClasse>.*?)\/(?<sDescricao>.*?)(?:\/(?<sExtras>.*?)\n|\n|$)");
var text = System.IO.File.ReadAllText(Server.MapPath("~/TextFile1.txt")); // TextFile1.txt is too big to put here, so i've uploaded it here: http://pastebin.com/AtxbYPXc
var matches = rgx.Matches(text);
var lstItens = new List<Item>();
var oJson = new JArray();
foreach (System.Text.RegularExpressions.Match match in matches)
{
var item = new Item()
{
sClasse = match.Groups["sClasse"].Value.Trim(),
sDescricao = match.Groups["sDescricao"].Value.Trim(),
sNome = match.Groups["sNome"].Value.Trim(),
sExtras = match.Groups["sExtras"].Value.Trim(),
};
item.PreencherListaBundles(bundlesJson.ToString());
lstItens.Add(item);
}
var result = JsonConvert.SerializeObject(lstItens, Formatting.Indented);
var backResult = JsonConvert.DeserializeObject<List<Item>>(result);
The lstItens list has all items correctly (501 items), but the result string returns only 48 objects when searched for "Nome":, which is a mandatory field. Why is this happening?
To exemplify the error, look for the item lstItens[166], in the result var, if you search for "Nome": "Fiddlehead Fern" you can see that the item doesn't exists...
What is weird is that backResult.Count will show 501 results, and appears to have every item, but a simple search in the json generated at the result var using a mandatory field "Nome" will result in 48 results, as showed in the image :
Item.cs:
public class Item
{
[JsonProperty(PropertyName = "Nome")]
public string sNome { get; set; }
[JsonProperty(PropertyName = "Classe")]
public string sClasse { get; set; }
[JsonProperty(PropertyName = "Descricao")]
public string sDescricao { get; set; }
[JsonProperty(PropertyName = "Extras")]
public string sExtras { get; set; }
[JsonProperty(PropertyName = "Bundles")]
public List<Bundle> lstBundles { get; set; }
public void PreencherListaBundles(string jsonBundles)
{
List<Bundle> lstBundle = JsonConvert.DeserializeObject<List<Bundle>>(jsonBundles.ToString());
this.lstBundles = new List<Bundle>();
lstBundle.ForEach(x =>
{
if (!lstBundles.Select(y => y.sNome).Contains(x.sNome) && x.lstItens.Select(y => y.sNome).Contains(sNome))
{
lstBundles.Add(new Bundle() { sLocal = x.sLocal, sNome = x.sNome, sRecompensa = x.sRecompensa, lstItens = x.lstItens });
}
});
}
}
Bundle.cs
public class Bundle
{
[JsonProperty(PropertyName = "bundle")]
public string sNome { get; set; }
[JsonProperty(PropertyName = "location")]
public string sLocal { get; set; }
[JsonProperty(PropertyName = "reward")]
public string sRecompensa { get; set; }
[JsonProperty(PropertyName = "items")]
public List<BundleItem> lstItens { get; set; }
public class BundleItem
{
[JsonProperty(PropertyName = "name")]
public string sNome { get; set; }
[JsonProperty(PropertyName = "description")]
public string sDescricao { get; set; }
[JsonProperty(PropertyName = "quantity")]
public int nQuantidade { get; set; }
[JsonProperty(PropertyName = "quality")]
public string sQualidade { get; set; }
}
}
EDIT: Looks like that bug is not happening on some machines, like you can see with the Gerard Sexton's answer, but when i run the same code he ran i still get the 48 results. some more details can be found in this discussion: https://chat.stackoverflow.com/rooms/106307/discussion-between-gerard-sexton-and-gabriel-duarte
Try this:
var result = JsonConvert.SerializeObject(lstItens, Formatting.Indented);
//Testing deserialization
var backResult = JsonConvert.DeserializeObject<List<Item>>(result);
The result variable is a string which contains the properly formatted string.
I was not able to reproduce the bug using VS2015, JSON.NET 8.0.3.
I have included my debugger output.
Using your code and files, unchanged, I got 501 results and sJson contains Fiddlehead Fern and the visualizer shows item 166. Deserialization also works correctly.
Please check character encoding and these kind of things. Your system locale might cause something to act differently. Just a thought.

Automapper object to object

UPDATE 2:
It seems to be a problem with the containing value in Format.
The Debugger shows me "{{MinValue: 6, MaxValue:44}}" for property Format.
When I change this to .Format = new MyFormat(6,44) it works fine.. so maybe its a problem with the web api 2 I'm using ... but anyway it should just push the source-object to the destination-object ;)
UPDATE:
I removed the originial post and added some real code here. the other classes were only dummies to explain my problem.
By the way: The Problem only occurrs when I add the "Format" Property of type object to the class. otherwise it works fine...
I tried to create an simple example to keep things easy ;) but here are parts of my real code
private void InitAutoMapper()
{
if (_mappingInitialized) //static init
return;
//will prevent Mapper to try to map constructor-parameters. With Copy-Constructors otherwise this would cause infiniteloops and stackoverflowexceptions.
Mapper.Configuration.DisableConstructorMapping();
//From Client to Server
...
Mapper.CreateMap<SDK.Model.Form.Field, Field>();
//From Server to Client
...
Mapper.CreateMap<Field, SDK.Model.Form.Field>();
...
//checks if the configuration was correct.
Mapper.AssertConfigurationIsValid();
_mappingInitialized = true;
}
and this is the call
public string CreateEntityField(SDK.Model.Form.Field field)
{
var mappedField = Mapper.Map<Field>(field);
...
}
my Field-class looks like this (source and destination classes look exactly the same. they are just separated in two different namespaces to have the possibility to add different properties in the future.
public class Field : IEntityRelatedEntity, IModificationTrackObject
{
public string Id { get; set; }
public string Name { get; set; }
public string DisplayName { get; set; }
public string Description { get; set; }
public DateTime CreatedOn { get; set; }
public DateTime ModifiedOn { get; set; }
public int Status { get; set; }
public int SubStatus { get; set; }
...many more fields
public FieldType Type { get; set; }
public object Format { get; set; }
public FieldRequirement Required { get; set; }
public Field()
{
Name = null;
Description = string.Empty;
DisplayName = null;
Type = FieldType.Text;
Required = FieldRequirement.Optional;
CreatedOn = new DateTime();
ModifiedOn = new DateTime();
}
public Field(Field copy)
{
Id = copy.Id;
Format = copy.Format;
...
}
}
and this is the exception I get (sorry parts of this exception are in german but it means that the source and destination-Type of Format are not the same)
exception =
{
Mapping types:\r\nJObject -> JObject
Newtonsoft.Json.Linq.JObject -> Newtonsoft.Json.Linq.JObject
Destination path:
Field.Format.Format
Source value:
{
"MinValue": "2",
"MaxValue": "100"
}
}
The Mapper should just copy the source to the destination for property "Format" and shouldn't care about whats in there...
one more thing: when i Ignore the Format-Property everything works fine, too.
Mapper.CreateMap<SDK.Model.Form.Field, Field>().ForMember(m => m.Format, opt => opt.Ignore());

ASP.NET Neo4jClient retrieving incorrect number

I have an ASP.NET Web Forms project which is using Readify-Neo4jClient and Neo4J Community 2.0.3, I'm getting a bug where a number stored in the database is changing its value when retrieved. Here is a picture of what’s in the database and what I can see in VS2013:
https://docs.google.com/file/d/0B6b_N7sDgjmvMVF5TFpaZXJmNFk/edit
The code to retrieve the user is as follows:
IEnumerable<SUser> FoundUsers = Neo4jGraphClient.Cypher.Match("(user:User)")
.Where((SUser user) => user.Email == UserName)
.Return(user => user.As<SUser>())
.Results;
Code to write to the database is as follows:
long DateTimeNow = DateTime.Now.Ticks;
SUser ss = new SUser
{
Id = UserCounter.SubmitAndCommitNewUser(),
DateOfBirth = DobDay.Text + "" + DobMonth.Text + "" + DobYear.Text,
Email = UserName.Text,
FirstName = FirstName.Text,
LastName = LastName.Text,
UserCreatedOn = DateTimeNow,
role = UType.ADMIN,
Status = UStatus.NEW
};
Neo4jReq.CreateSUser(ss);
......
public static SUser CrseateSUser(SUser NewUser)
{
//...
Neo4jGraphClient.Cypher
.Create("(user:User {NewUser})")
.WithParam("NewUser", NewUser)
.ExecuteWithoutResults();
existing = NewUser;
}
Class is as follows:
public class SUser
{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string DateOfBirth { get; set; }
public string Email { get; set; }
public UType role { get; set; }
public UStatus Status { get; set; }
public string pass { get; set; }
public string VerificationGUID { get; set; }
public long UserCreatedOn { get; set; }
public string UserNotes { get; set; }
}
Any ideas on whats causing this?
Right - I've got this replicating, this looks like a bug(?) in the way the Neo4j browser shows the data (both the current and older webadmin), so the data stored in Neo4j is correct, but it's getting 'rounded' (in a sense anyway) in the display, if you run the 'Get' query in the browser you get the '00' ending, this also happens in the old web admin:
http://localhost:7474/webadmin/
if you run the query in the 'Data Browser'.
However, if you run the query in the Console (http://localhost:7474/webadmin/#/console/) you'll get the correct results. Neo4jClient is giving you the right results, it's the browser that is wrong in this case.

How - Convert Linq.DataQuery to Generic.List

Would anyone of you could help me solve this? I'm getting this error when casting 'carsList' variable to '_vehicleList'
Unable to cast object of type 'System.Data.Linq.DataQuery to type 'System.Collections.Generic.List`1[VehicleDAOModel]'.
Does the Linq.DataQuery has to match the Properties in VehicleDAOModel?
My code:
public class VehicleDAOModel
{
[Display(Name = "Id")]
public int _Id { get; set; }
[Required]
[Display(Name = "Year")]
public string _year { get; set; }
[Required]
[Display(Name = "Make")]
public string _make { get; set; }
[Required]
[Display(Name = "Model")]
public string _model { get; set; }
[Required]
[Display(Name = "Trim")]
public string _trim { get; set; }
}
// LINQ TO SQL CODE
var dataContext = new VehicleModelL2SQLDataContext();
var carsList = from v in dataContext.Vehicles
select v;
_vehicleList = (List<VehicleDAOModel>)carsList;
public List<VehicleDAOModel> _vehicleList = new List<VehicleDAOModel>();
Tried the following but did NOT work:
carsList.ToList(); (X)
carsList.AsEnumerable().LoList(); (X)
Thank you in advance.
Just do a .ToList()on that carsList.
_vehicleList = carsList.ToList();
That carsList is a query that will be executed, once it's read from. The .ToList() reads the complete query result and returns it as a List<T>.
But that does expect the query to return VehicleDAOModels. If not, then you will need to use .Select() and convert it yourself.
Assuming that your vehicle entity class is not named "VehicleDAOModel" you need to project carsList to a list of VehicleDAOModel objects.
_vehicleList = carsList.Select( c =>
new VehicleDAOModel {
Id = c.Id,
Year = c.Year,
...
});
I would strongly recommend to use Automapper for this:
Mapper.Map<Vehicle, VehicleDAOModel>();
_vehicleList = carsList.Project.To<VehicleDAOModel>();
(Assuming that there is a 1:1 mapping of property names between both classes.)

Categories