Complex input to WebApi2 function - asp.net-mvc

I've got this class in my Model:
public class GetDocParams {
public string LogonTicket { get; set; }
public int CliRid { get; set; }
public string[] ValPairs { get; set; }
public string SortBy { get; set; }
public int StartRec { get; set; }
public int EndRec { get; set; }
}
This is going to be used as input to a WebApi2 function to retrieve query results from Entity Framework.
The function takes the valPairs from input and uses it to build a query that sorts by the passed pairs, i.e.
CLI_RID=111111
DOC_NAME=Letter
would create the SQL:
WHERE CLI_RID = 111111
AND DOC_NAME = 'Letter'
I'm kind of curious, how would I pass the ValPairs, using ajax and/or WebClient?
GET or POST doesn't matter.

You may have to add a new class for ValPair, like the following.
public class GetDocParams {
public string LogonTicket { get; set; }
public int CliRid { get; set; }
public ValPair[] ValPairs { get; set; }
public string SortBy { get; set; }
public int StartRec { get; set; }
public int EndRec { get; set; }
}
public class ValPair {
public int CLI_RID { get; set; }
public string DOC_NAME { get; set; }
}
And you can pass values to the parameters via the following GET API call:
http://www.example.com/api/docs/getDocParams?LogonTicket=111&ValPairs[0][CLI_RID]=111111&ValPairs[0][DOC_NAME]=Letter&ValPairs[1][CLI_RID]=22222&ValPairs[1][DOC_NAME]=document&....
This should work if you know the names of the keys.

Related

Null value assigned when response is written to the Model object

public class BClass
{
public class RClass
{
public string stjCd { get; set; }
public string lgnm { get; set; }
public string stj { get; set; }
public string dty { get; set; }
public List<object> adadr { get; set; }
public string cxdt { get; set; }
public string gstin { get; set; }
public List<string> nba { get; set; }
public string lstupdt { get; set; }
public string rgdt { get; set; }
public string ctb { get; set; }
public Pradr pradr { get; set; }
public string tradeNam { get; set; }
public string sts { get; set; }
public string ctjCd { get; set; }
public string ctj { get; set; }
}
public class AClass
{
public string id { get; set; }
public string consent { get; set; }
public string consent_text { get; set; }
public int env { get; set; }
public string response_code { get; set; }
public string response_msg { get; set; }
public int transaction_status { get; set; }
public string request_timestamp { get; set; }
public string response_timestamp { get; set; }
public RClass result { get; set; }
}
}
//COntroller
BClass.AClass btr = new BClass.AClass();
var lst = JsonConvert.DeserializeObject<BClass.AClass>(strresult);
btr.response_code = lst.response_code;
btr.response_msg = lst.response_msg;
btr.result.lgnm = lst.result.lgnm;
The property btr.result.lgnm = lst.result.lgnm; Gives null value error object reference not set to instance of an object. but the lst variable has a value in the response received.Please provide suggesion
You can solve this by adding one line into your code.
btr.result = new BClass.RClass(); //This one. You need to initialize instance before assigning anything to it.
btr.result.lgnm = lst.result.lgnm;
or else, you can also create default constructor for class A.
public AClass()
{
result = new RClass();
}
I would suggest you to please have a look at below web resources for naming conventions widely used for c# language.
Properties naming conventions: https://learn.microsoft.com/en-us/dotnet/standard/design-guidelines/names-of-type-members
class naming conventions: https://learn.microsoft.com/en-us/dotnet/standard/design-guidelines/names-of-classes-structs-and-interfaces
Assigning this way does not give null reference exception
RClass rclass=new RClass();
rclass.lgnm=lst.result.lgnm

Flatten Domain Class To ViewModel When Source Is Complex

I am using ValueInjecter to map domain classes to my view models. My domain classes are complex. To borrow an example from this question:
public class Person
{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public Address Address { get; set; }
}
public class Address
{
public int Id { get; set; }
public string City { get; set; }
public string State { get; set; }
public string Zip { get; set; }
}
// VIEW MODEL
public class PersonViewModel
{
public string FirstName { get; set; }
public string LastName { get; set; }
public int PersonId { get; set; }
public int AddressId { get; set; }
public string City { get; set; }
public string State { get; set; }
public string Zip { get; set; }
}
I have looked at FlatLoopInjection, but it expects the view model classes to be prefixed with nested domain model type like so:
public class PersonViewModel
{
public string FirstName { get; set; }
public string LastName { get; set; }
public int Id { get; set; }
public int AddressId { get; set; }
public string AddressCity { get; set; }
public string AddressState { get; set; }
public string AddressZip { get; set; }
}
The OP in the linked question altered his view models to match the convention expected by FlatLoopInjection. I don't want to do that.
How can I map my domain model to the original unprefixed view model? I suspect that I need to override FlatLoopInjection to remove the prefix, but I am not sure where to do this. I have looked at the source for FlatLoopInjection but I am unsure if I need to alter the Match method or the SetValue method.
you don't need flattening, add the map first:
Mapper.AddMap<Person, PersonViewModel>(src =>
{
var res = new PersonViewModel();
res.InjectFrom(src); // maps properties with same name and type
res.InjectFrom(src.Address);
return res;
});
and after that you can call:
var vm = Mapper.Map<PersonViewModel>(person);

Automatically add relationships for complex types

I'm looking to do bulk importing of complex models containing objects and collections into Neo4j.
I have the following model:
public class PSNGame
{
public int EarnedPlatinum { get; set; }
public int EarnedGold { get; set; }
public int EarnedSilver { get; set; }
public int EarnedBronze { get; set; }
public int EarnedTotal { get; set; }
public int AvailablePlatinum { get; set; }
public int AvailableGold { get; set; }
public int AvailableSilver { get; set; }
public int AvailableBronze { get; set; }
public int AvailableTotal { get; set; }
public double PercentCompleteBronze { get; set; }
public double PercentCompleteSilver { get; set; }
public double PercentCompleteGold { get; set; }
public double PercentCompletePlatinum { get; set; }
public double PercentCompleteTotal { get; set; }
public DateTimeOffset LastUpdated { get; set; }
public string Platform { get; set; }
public string NPCOMMID { get; set; }
public string TitleName { get; set; }
public string TitleDetail { get; set; }
public string Image { get; set; }
public string LargeImage { get; set; }
// complex model parts
public GameInfo GameInfo { get; set; }
public GameCommon.Rating Rating { get; set; }
public IEnumerable<GameCommon.RatingDescriptor> RatingDescriptors { get; set; }
public IEnumerable<GameCommon.Genre> Genres { get; set; }
public IEnumerable<GameCommon.Publisher> Publishers { get; set; }
public IEnumerable<GameCommon.Developer> Developers { get; set; }
public PSNGame()
{
}
}
I use this code to insert the games to Neo4j, however, it only works without the complex objects/collections:
var client = new GraphClient(new Uri("http://localhost:7474/db/data"));
client.Connect();
client.Cypher
.Match("(p:PSNProfile {PSNId : {profile}.PSNId})")
.ForEach(#"(game in {PSNGames} |
MERGE p-[:PLAYS {LastPlayed : game.LastUpdated}]->(g:PSNGame {NPCOMMID : game.NPCOMMID})-[:LOCALE]->(l:PSNGameLocalized {NPCOMMID : game.NPCOMMID})
SET g = game,
l = { NPCOMMID : game.NPCOMMID,
TitleName : game.TitleName,
TitleDetail : game.TitleDetail,
Locale : {locale}
})")
.WithParams(new
{
PSNGames = games.ToList(),
locale = locale,
profile = profile
})
.ExecuteWithoutResults();
I've tried doing nested FOREACH clauses, but this can get messy very fast. Also, the syntax of MERGE g-[:GAME_RATING]->g.Rating doesn't seem quite right and Neo4j complains that there is an invalid . token. My thought was to loop over the collections and access specific properties with the . accessor, but it doesn't look like Cypher likes the syntax.
For complex types, I would like to automatically create/update relationships/nodes for any child objects/collections contained in the complex type. Is there a way to do this in Neo4jClient?
Is there a way to do this in Neo4jClient?
No. Neo4jClient is a lower level driver, kind of like SqlClient. If you want more ORM-style behaviours on top of it, that would be a higher level library, equivalent to something like Entity Framework. There was a project called Neo4jRepository for a while, which built on top of Neo4jClient, but it has not been updated for the Neo4j 2.0 wave as far as I'm aware.

simple lookups in Data Access Layer, Business Layer or in UI?

ASP .NET MVC4
Class #1:
public class F61BPROD
{
public int WPDOCO { get; set; }
public string WPDCTO { get; set; }
public string WPMCU { get; set; }
public string WPLOCN { get; set; }
public string WPDCT { get; set; }
public int WPTRDJ { get; set; }
public string WPKYPR { get; set; }
public string WPLITM { get; set; }
public decimal WPTRQT { get; set; }
public string WPKYFN { get; set; }
public string WPLOTN { get; set; }
public string WPLRP1 { get; set; }
public string WPLRP2 { get; set; }
public string WPLRP3 { get; set; }
public string WPLRP4 { get; set; }
public string WPLRP5 { get; set; }
public string WPLRP6 { get; set; }
public string WPLRP7 { get; set; }
public string WPLRP8 { get; set; }
public string WPLRP9 { get; set; }
public string WPLRP0 { get; set; }
public string WPFLAG { get; set; }
public string WPLOT1 { get; set; }
public string WPLOT2 { get; set; }
}
For one of the properties of Class #1 i need to fetch one of Class #2:
public class JDEItemBasic
{
public int itm { get; set; }
public string litm { get; set; }
public string dsc { get; set; }
public string dsce { get; set; }
public string ean14 { get; set; }
public string cc { get; set; }
public string uom1 { get; set; }
public string uom2 { get; set; }
public int uom1ea { get; set; }
public int bxuom1 { get; set; }
public int uom1gr { get; set; }
}
There is a DAL that gets the above classes. I need to combine these classes a new class that will have most of the properties of the above classes.
Should i create a third class and do the job in BLL?
or should i do it in UI using LINQ to Entities after i fetch them?
Should i create a third class and do the job in BLL?
or should i do it in UI using LINQ to Entities after i fetch them?
That would depend on where you need this class. If it is for displaying purposes then it should live in the UI. This class even has a name in this case: it's called a view model and is what your controller action could pass to the view after querying your DAL layer and projecting the various results to this view model.

PagedList in MVC3 with IQueryable

I can't understand what i'm doing wrong. Every time I'm getting this error:
The entity or complex type 'BusinessLogic.CompanyWithDivisionCount' cannot be constructed in a LINQ to Entities query.
I need to get info from 'Company' table and divisions count of each company from 'Division' table, and then make PagedList. Here is my 'Company' table:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel.DataAnnotations;
using BusinessLogic.Services;
using BusinessLogic.Models.ValidationAttributes;
namespace BusinessLogic.Models
{
public class Company
{
public Company()
{
Country = "US";
Status = true;
}
public int Id { get; set; }
[Required]
[UniqueCompanyName]
public string Name { get; set; }
public string Street { get; set; }
public string City { get; set; }
public string State { get; set; }
public int Zip { get; set; }
public string Country { get; set; }
public string ContactInfo { get; set; }
[Required]
public DateTime EffectiveDate { get; set; }
public DateTime TerminationDate { get; set; }
public bool Status { get; set; }
[Required]
public string URL { get; set; }
public string EAP { get; set; }
public string EAPCredentials { get; set; }
public string BrandingColors { get; set; }
public string Comments { get; set; }
}
}
Here is my domain model:
public class Company
{
public Company()
{
Country = "US";
Status = true;
}
public int Id { get; set; }
[Required]
[UniqueCompanyName]
public string Name { get; set; }
public string Street { get; set; }
public string City { get; set; }
public string State { get; set; }
public int Zip { get; set; }
public string Country { get; set; }
public string ContactInfo { get; set; }
[Required]
public DateTime EffectiveDate { get; set; }
public DateTime TerminationDate { get; set; }
public bool Status { get; set; }
[Required]
public string URL { get; set; }
public string EAP { get; set; }
public string EAPCredentials { get; set; }
public string BrandingColors { get; set; }
public string Comments { get; set; }
}
public class CompanyWithDivisionCount: Company // I'm using this
{
public int DivisionCount { get; set; }
}
Here is my controller:
public ActionResult CompaniesList(int? page)
{
var pageNumber = page ?? 1;
var companies = companyService.GetCompaniesWithDivisionsCount2();
var model = companies.ToPagedList(pageNumber, PageSize);
return View(model);
}
And here is my service part:
public IQueryable<CompanyWithDivisionCount> GetCompaniesWithDivisionsCount2()
{
return (from c in dataContext.Companies.AsQueryable()
select new CompanyWithDivisionCount
{
Id = c.Id,
Name = c.Name,
Status = c.Status,
EffectiveDate = c.EffectiveDate,
URL = c.URL,
EAP = c.EAP,
EAPCredentials = c.EAPCredentials,
Comments = c.Comments,
DivisionCount = (int)dataContext.Divisions.Where(b => b.CompanyName == c.Name).Count()
});
}
}
Thanks for help!!!
Creator of PagedList here. This has nothing to do with PagedList, but rather is an Entity Framework issue (I'm no expert on Entity Framework, so can't help you there). To confirm that this is true, write a unit test along the following lines:
[Test]
public void ShouldNotThrowAnException()
{
//arrange
var companies = companyService.GetCompaniesWithDivisionsCount2();
//act
var result = companies.ToList();
//assert
//if this line is reached, we win! no exception on call to .ToList()
}
I would consider changing you data model if possible so that instead of relating Companies to Divisions by name strings, instead use a properly maintained foreign key relationship between the two objects (Divisions should contain a CompanyID foreign key). This has a number of benefits (including performance and data integrity) and will almost certainly make your life easier moving forward if you need to make further changes to you app (or if any company ever decides that it may re-brand it's name).
If you create a proper foreign key relationship then your domain model could look like
public class Company
{
...
public virtual ICollection<Division> Divisions{ get; set; }
public int DivisionCount
{
get
{
return this.Divisions.Count()
}
}
...
}

Resources