Accessing data with DAL2: Value cannot be null.Parameter name: con - sql

I'm trying to access data with DAL2 in DotNetNuke. When I use the repository.Get() to get all fields of a certain table I sometimes get this error:
'Value cannot be null. Parameter name: con'
public IEnumerable<SitesProvince> GetAll()
{
using (var ctx = DataContextContent.Instance())
{
var rep = ctx.GetRepository<SitesProvince>();
return rep.Get();
}
}
Model:
[TableName("Sites_Province")]
[PrimaryKey("Sites_Province_No")]
[Cacheable("Sites_Province", CacheItemPriority.Default, 20)]
[Scope("Sites_Province_No")]
public class SitesProvince
{
public int Sites_Province_No { get; set; }
public string BU { get; set; }
public string Province { get; set; }
}
What could be the problem? In some queries it works and some don't and I don't see any difference between the methods.
I found this but I have no contracts:
http://clraddins.codeplex.com/discussions/24568

I solved this problem by adding an empty constructor to my model. Now everything works fine.

Related

How to bind custom model class in mvc

I am new in MVC. I am working on a project where i have created a model class and also context class which is working good if i view the record in normal view.
but if i try to get the data in group by "Series_Name" and bind it into same model class it gives error. here is my code
Here is Model class and DBContextClass
[Table("tblvideo")]
public class TVSerial
{
[Key]
public Int64 Video_ID { get; set; }
public string Series_Name { get; set; }
public string Season_No { get; set; }
public string Episode_No { get; set; }
public string Episode_Name { get; set; }
public string Time_Duration { get; set; }
public string File_Url_480p { get; set; }
public string File_Url_720p { get; set; }
public string Description { get; set; }
public bool Is_Active { get; set; }
public string Image_Url_Small { get; set; }
public string Image_Url_Big { get; set; }
}
public class TvSerialContext : DbContext
{
public DbSet<TVSerial> TvSerials { get; set; }
}
Here is controller class:
public class TvSerialController : Controller
{
public ActionResult ListAllTvSerial()
{
try
{
TvSerialContext tvContext = new TvSerialContext();
List<TVSerial> tv = tvContext.TvSerials.ToList();
return View(tv);
}
catch (Exception ex)
{
return Content(ex.Message);
}
}
}
Above code works as expected, but if i am doing this :
public ActionResult ListAllSeason(string serial)
{
try
{
TvSerialContext tvContext = new TvSerialContext();
List<TVSerial> tv = tvContext.TvSerials.Where(tvs => tvs.Series_Name == serial).Distinct().ToList();
return View(tv);
}
catch (Exception ex)
{
return Content(ex.Message);
}
}
it return all rows , i just want single row from every series_name and custom field "Series_Name,Season_No,Image_Url_Big"
i don't know how to achieve this.
getting result :
Expected result:-
You could do this by creating a view model and using a .GroupBy() clause
public class TVSerialVM
{
public string SeriesName { get; set; }
public string SeasonNo { get; set; }
public string ImageUrl { get; set; }
}
and the query to project into your view model
List<TVSerialVM> model = tvContext.TvSerials.Where(t => t.Series_Name == serial)
.GroupBy(t => new { t.Series_Name, t.Season_No, t.Image_Url_Big })
.Select(t => new TVSerialVM
{
SeriesName = t.Key.Series_Name,
SeasonNo = t.Key.Season_No,
ImageUrl = t.Key.Image_Url_Big
}).ToList();
Side note: Your duplicating data in the database (the season number and the image url). You should consider moving the image urls to another table with a relationship to the season number.
The reason you are getting multiple values even though you are using distinct is the Distinct method does not know what "equal" is for TVSerial.
You can use Distinct with IEqualityComparer.
https://msdn.microsoft.com/en-us/library/vstudio/bb338049(v=vs.100).aspx
Distinct is not guaranteed to on custom objects it doesn't know what to compare. I have used this SO in the past to make my custom object work with Distinct.
Creating a distinct list of custom type in C#

Using ReadAsAsync<T>() to deserialize complex Json object

I want to use ReadAsAsync() in my mvc project with .net 4.0. The result comes as null.
If I enter the uri to address bar, the result in chrome as(tag names are changed):
<ns2:MyListResponse xmlns:ns2="blablabla">
<customerSessionId>xxcustomerSessionIdxx</customerSessionId>
<numberOfRecordsRequested>0</numberOfRecordsRequested>
<moreResultsAvailable>false</moreResultsAvailable>
<MyList size="1" activePropertyCount="1">
<MySummary order="0">
<id>1234</id>
<name>...</name>
.
.
</MySummary>
</MyList>
</ns2:MyListResponse>
If I use the statement in code :
using (var client = new HttpClient())
{
var response = client.GetAsync(apiUri).Result;
var message = response.Content.ReadAsStringAsync().Result;
var result1 = JsonConvert.DeserializeObject<MyListResponse>(message);
var result2 = response.Content.ReadAsAsync<MyListResponse>().Result;
}
the message comes in string format as "{\"MyListResponse\":{\"customerSessionId\"...}" which corresponds to a json object as:
{"MyListResponse":
{"customerSessionId":"xxcustomerSessionIdxx",
"numberOfRecordsRequested":0,
"moreResultsAvailable":false,
"MyList":
{"#size":"1",
"#activePropertyCount":"1",
"MySummary":
{"#order":"0",
"id":1234,
"name":"...",
.
.
}
}
}
}
and the properties of result1 and result2 came as null or default values. Class definitions are below. I want to read the content as an object but I couldn't. What do you advice to solve this? What am I doing wrong? Thanks in advance.
public class MySummary
{
public int #Order { get; set; }
public string Id { get; set; }
public string Name { get; set; }
.
.
}
public class MyList
{
public int #Size { get; set; }
public int #ActivePropertyCount { get; set; }
public MySummary MySummary{ get; set; }
}
public class MyListResponse
{
public string CustomerSessionId { get; set; }
public int NumberOfRecordsRequested { get; set; }
public bool MoreResultsAvailable { get; set; }
public MyList MyList { get; set; }
}
I defined a new class as:
public class ResponseWrapper
{
public MyListResponse MyListResponse { get; set; }
}
then I used this wrapper with,
var result1 = JsonConvert.DeserializeObject<ResponseWrapper>(message);
var result2 = response.Content.ReadAsAsync<ResponseWrapper>().Result;
then it worked. I need only MySummary object but I should write more classes to make it work.
After reading your solution I came up with one that doesn't need an extra class:
private static async Task<U> Execute<U>(HttpClient client, string path)
{
U output = default(U);
HttpResponseMessage response = await client.GetAsync(path);
if (response.IsSuccessStatusCode)
{
var jsonAsString = await response.Content.ReadAsStringAsync();
output = JsonConvert.DeserializeObject<U>(jsonAsString);
}
else
{
throw new ApplicationException(string.Format("Response message is not OK. Issues in action: {0}", path));
}
return output;
}
For the sake of future readers, I think the correct approach is using ReadAsAsync overload that takes IEnumerable<MediaTypeFormatter> and provide a formatter with the same settings used on the server for serialization. That should fix it.
It is possible to use at client ReadAsAsync with MyListResponse directly (in consequence without ResponseWrapper). To do this, you can define "BodyStyle = WebMessageBodyStyle.Bare" in the operation contract of "apiuri" in stead of "BodyStyle = WebMessageBodyStyle.Wrapped" (server side, i.e. service contract).

RavenDb Select() downcasts instead of selecting the neccessary fields

public class PersonBrief
{
public int Id { get; set; }
public string Picture { get; set; }
public PersonBrief(Person person)
{
Id = person.Id;
Picture = person.Picture;
}
}
public class Person : PersonBrief
{
public string FullName { get; set; }
}
var results = session.Query<Person>()
.Select(x => new PersonBrief(x))
.ToList();
Assert.IsNull(results[0] as Person); // Fails
Is this a bug? If not, what would be the correct way to select only the fields i'm interested in?
It would work if you move the .ToList before the .Select, but that would be doing the work on the client.
If you want to do it on the server, you need to use As in your query, and you need a static index that does a TransformResults. See these docs.

Nested json deserialized incompletely

I mentioned in title that the json is deserialized incompletely because some of the objects have the right value in the controller (I send the json to an asp.net mvc 4 controller), but the problem occurs with properties of objects stored in arrays (to be exact, the problem appears with Data)
I have the following classes:
public class Node
{
[JsonProperty("id")]
public int? Id { get; set; }
[JsonProperty("name")]
public string Name { get; set; }
[JsonProperty("type")]
public string Type { get; set; }
private Data _data = new Data();
[JsonProperty("data")]
public Data Data { get; set; }
private List<Adjacency> _adjacencies = new List<Adjacency>();
[JsonProperty("adjacencies")]
public List<Adjacency> Adjacencies
{
get { return _adjacencies; }
set { _adjacencies = value; }
}
private List<Instance> _dependendStates = new List<Instance>();
public List<Instance> DependentStates
{
get { return _dependendStates; }
set { _dependendStates = value; }
}
}
public class Data
{
[JsonProperty("$posX")]
public decimal PosX { get; set; }
[JsonProperty("$posY")]
public decimal PosY { get; set; }
}
public class Adjacency
{
[JsonProperty(PropertyName = "nodeTo")]
public string NodeTo { get; set; }
[JsonProperty(PropertyName = "data")]
public AdjData Data { get; set; }
//doesn't contain definition for automated transitions
}
public class AdjData
{
[JsonProperty(PropertyName = "$labelid")]
public string LabelId { get; set; }
[JsonProperty(PropertyName = "$labeltext")]
public string Label { get; set; }
[JsonProperty(PropertyName = "$type")]
public string Type { get; set; }
}
I've highlighted fields that don't have the right value.
The null problem http://img19.imageshack.us/img19/530/36976913.png
The json looks like this:
{
"result":[
{
"id":"100",
"name":"Start",
"data":{
"$posX":-100,
"$posY":-100,
"$deployed":true,
"$color":"#000000",
"$selected":"true"
},
"adjacencies":[
{
"nodeTo":"188",
"data":{
"$type":"labeled_arrow",
"$labelid":"Label Name",
"$labeltext":"Label Name"
}
}
]
},
{
"id":"188",
"name":"Second ",
"data":{
"$dim":20,
"$color":"#000000",
"$selected":"true"
},
"adjacencies":[
]
}
],
"smName":"gftrds"
}
I'm having a problem sorting this out as I do not understand or see where the problem is.
Disclaimer: I wasn't able to reproduce this exactly, as in my case Label and LabelId deserialized fine, though Type did not, so my anwser may not address the problem you are having.
In my case, I was only able to deserialize the "$type":"labeled_arrow" property if it was not the first one - if it appeared after "$labelid":"Label Name" or "$labeltext":"Label Name" it worked fine.
Strangely, if the $type property was called type in the Json and referred to as [JsonProperty(PropertyName = "type")] in the C#, it would deserialize fine, regardless of the order.
In your case you can't deserialize Label or LabelId either, so it could be that your problem is caused by something else. To rule out what I have suggested, it might pay to try modifying some of the property names (possibly just take off the $) to see if they are causing the properties to be deserialized incorrectly.
I experienced the same issue, however in my case this was related to how the data was being transmitted from client side. Make sure the AJAX request is using the proper headers and formatting. For example:
dataType: 'json',
contentType: 'application/json; charset=UTF-8',
data: JSON.stringify({
MemberId : '123',
UserName: '456',
Parameters: [
{ Value : 'testing' },
{ Value : 'test2' }
]
}),

NHibernate - IUserType For Changing Type?

My application has the following classes:
public class Widget {
public virtual int Id { get; set; }
public virtual WidgetType Type { get; set; }
public virtual string Parameters { get; set; }
}
public class WidgetType {
public virtual int Id { get; set; }
public virtual string Name { get; set; }
public virtual string ParametersAssembly { get; set; }
public virtual string ParametersClass { get; set; }
}
Now if i'd like to update the Parameters for a particular widget i would say something like:
// Get the widget
var widget = GetWidget(1);
// Create an instance of the type parameters class
var parameters = Activator.CreateInstance(Assembly.LoadFrom(Server.MapPath("~/bin/"
+ widget.Type.ParametersAssembly + ".dll")).GetType(widget.Type.ParametersClass));
... Code here to update the parameters
widget.Parameters = new XmlSerializer(parameters.GetType()).Serialize(parameters);
I have to do the reverse when i wish to get the parameters. You can imagine this becomes quite tedious. I was wondering if it was possibly to automatically do this?
I've been looking at the IUserType interface. I found an article which is kind of similar. However my problem is a little more complicated as my type changes based on the type of the widget.
I'd appreciate it if someone could let me know if this is possible and possibly how it could be achieved. Thanks
an easy way
public class Widget
{
public virtual int Id { get; set; }
public virtual WidgetType Type { get; set; }
private string _serializedParameters;
private virtual string SerializedParameters {
get
{
return new XmlSerializer(Parameters.GetType()).Serialize(Parameters);
}
set
{
_serializedParameters = value;
// code to deserialize the Parameters and set to Parameters
var ptype = Assembly.LoadFrom(Server.MapPath("~/bin/" + widget.Type.ParametersAssembly + ".dll")).GetType(widget.Type.ParametersClass);
Parameters = Activator.CreateInstance(ptype);
}
}
private object _parameters;
public virtual object Parameters
{
get
{
if (_parameters == null)
_parameters = Activator.CreateInstance(Assembly.LoadFrom(Server.MapPath("~/bin/" + widget.Type.ParametersAssembly + ".dll")).GetType(widget.Type.ParametersClass));
return _parameters;
}
set { _parameters = value; }
}
}
it can't be in the Parameters property because then you have to get -> alter -> set instead of get -> alter. But you are right that building the parameters object should go in the getter of Parameters because only there we can be sure to have the WidgetType loaded
it is essentially the same as a UserType except that we know that WidgetType is there