Array in view mvc - asp.net-mvc

I have an array of bytes in my model
public byte[] created_dt { get; set; }
It represents a timestamp value in the database.
In my view , I am referring it as #model.created_dt
but it is coming as system.byte[]
How to resolve this?

Try as this is just an example to achieve the functionality
#foreach(var a in model.created_dt){
<label>#a</label>
}

Judging by the behavior, this looks like ASP.NET and you are simply seeing the output of an implicit call to ToString() on the array (the default way of displaying anything that does not have a template defined). You will have to do something with the raw byte data and present it to the user.
Since you refer to "timestamp" and the property name might suggest a record creation time, you may want to write a helper method to translate this raw data to a DateTime which you could then format accordingly.
However, one of the following is most likely true:
It strikes me as odd that you are using raw binary to store what should otherwise be a datetime2 column. (Or it is a datetime in your database but you're doing something unorthodox to retrieve the value.)
Your property/column name of "created_dt" is a misnomer and it is really a timestamp (i.e. rowversion) column. In which case I don't think this is something a user would know what to do with, and it probably doesn't belong on the UI.

Related

Telerik Kendo Chart : How to bind the chart to a string type

I've been stuggling for a moment and I'm unable to find anything related to that. I'm a total newbie with Kendo, and sadly I was not able to find anything that could help my question, documentation, forums and all of that : they haven't helped at all.
Situation :
I have a viewmodel in my ASP .NET app. I'm trying to make a chart out of one of the proripeties called "Type". This propriety represent a type of data - let's say fruits, like "Banana", "Apple" etc.
This type contains only and only one type at the time. It cannot contain something like "Apple and bananas". It's always a string, too.
This proriety is part of a larger model. But I'm only interested in this one.
Now, what I like to do :
I'd like to make a chart, using Kendo, from that propriety.
That means, I have to bind my chart to my model, and then, it will be able to know how many time some of those Types were used.
Like, example, If I have three objects :
Name : "Mjuzl"
Type : "Potato"
Name : "Uijqf"
Type : "Apple"
Name : "Zjli"
Type : Potato"
I'd like my char to count that my model used the type Potato twice, and the type Apple once.
I know how to get my datasource that contain all of the objects that use my model. (I have already used Kendo Grid just before but it's so simplier tbh) My issue right now, is that I have no idea - and I wasnt' able to find any - how to actually display what I want in my chart. I say it again, they are strings. I know how to get my datasource. I don't know how to actually show what I want to show. (Should I use columns ? sections ? I don't know)
Do I need to build a JSON from my controller that will ask the database to count ? Does Kendo is able to do it by it's own ? I'm so lost, I have no idea what Kendo is actually waiting for to make my chart working. The documentation isn't helping at all. I've been researching for a while, I haven't found anything that describes the exact same problem. And I've been searching for days.
Very badly drawn image I've done to put a picture on my problem :
I don't ask to do it for me, I ask for a path. A way to do it.
Thanks.
One way would be to create a view model specifically for your chart, and you can populate that view model based on your data.
Roughly (untested code - just to give you an idea), something like this:
public class MyChartViewModel
{
public int TypeCount { get; set; }
public string TypeName { get; set; }
}
and then in your read method for the chart where you are populating MyChartViewModel:
var myExistingDataModel = howeverYouGetYourDataHere;
var model = new MyChartViewModel();
var distinctTypes = myExistingDataModel.Select(x => x.Type).Distinct().ToList();
foreach (var distinctType in distinctTypes)
{
model.TypeCount = myExistingDataModel.Count(x => x.Type == distinctType);
model.TypeName = distinctType;
}
Finally ! I managed to do it !
For any future reference :
Based on G_P's answer, I used a LINQ request to count all of my types : Linq distinct - Count (don't forget to remove the .District() otherwise I won't work !)
Then, I did some debuging to see if I actually return my data, because nothing was showing in the chart. It did return my data and the right number.
The issue for this case was, I use
return Json(types.ToDataSourceResult(request, ModelState));
To return my data to my chart. But ! there is a little thing to know about Chart, they don't work like grids. You have to use a specific setup for showing your data if you use ToDataSourceResult : https://docs.telerik.com/aspnet-mvc/html-helpers/charts/data-binding (See "3) (Optional) Configure a Custom DataSource."), just change the call to your controller, and voilĂ  ! It worked !

Save multiple selected dropdown values into a single column in Grails

How to save multiple selected dropdown values into a single column in Grails?
Input will look like
<g:select name="item1Price" from="${1..10}"/>
<g:select name="item2Price" from="${1..10}"/>
<g:select name="item3Price" from="${1..10}"/>
And Output Should be stored in one field
ItemPrice: 2,8,6
Your question is a bit vague, so hopefully a somewhat vague answer will be helpful too!
If you have a domain object Foo:
class Foo {
String itemPrice
}
Then in your controller action, you can just do something like:
def save() {
Foo f = new Foo()
f.itemPrice = [params.item1Price, params.item2Price, params.item3Price].join(",")
f.save()
}
Really all you're trying to do is join your parameters from your page into one string, right?
Now this actually seems like bad design to me. What happens if the order changes, or if nothing is selected for item 2? Or what happens if somebody wants to edit your object and you need to parse the values back out? Obviously you could split on commas...until one of the values contains a comma!
You're better off storing one value for each field that means something different, or storing a single field as a structured value. You might want to look at encoding a Map into JSON and storing that, for example, if you really just want to have one field in your domain object.

MVC EF String Length / Data Type for Signature Image

I'm using a javascript plugin called jSignature to give my MVC4 application delivery signature capture functionality. jSignature outputs the signature info in a data:image/png;base64,iVBORw0KG... string format that looks to be around 32,000 characters long. I created a property in my model called DeliverySignature as a string and am able to save and retrieve the signature data but when I pull it back in from the database it's only about 5,000 characters long. What data type do I need to be using in my model's definition and in the action method (it's being passed in to a controller to save to the db) so that it preservers the complete string length? Thank you.
I would store it in varchar(max) column.
You can keep model property type of string as strings do not have a limited length.

RavenDB ID for child documents

I like how cleanly an object is stored in ravenDB, but have a practical question for which I'm not sure of the best answer.
Lets say i have a quote request:
QuoteRequest.cs
int Id;
dateTime DateCreated;
List<Quotes> Quotes;
Quote.cs
int ProviderId;
int Price;
int ServiceDays;
int ServiceTypeId;
when someone hits a page, i spit out a list of quotes from which they can choose. These quotes are only related to an instance of the quote request.
My question is, since a child object, such as a quote in the list, doesnt have an Id generated by the database, how do I generate a querystring to let the next page know which quote the user wants to buy?
There could be multiple quotes by one providerId.
My thoughts were either add a QuoteId and increment it based on this.Quotes.Count, but that seems a little hacky, or generate a random number, also a little hacky.
How do people generally handle something like this?
Do you really need to associate the purchase (what the user chose to buy) with the original quote? I'm guessing that you take the quote and then convert it to a purchase.
If that is so, then don't worry about an id at all. Just pass along the constituent values to the next step. In other words, treat quote like a Value in the DDD sense.
However, if you do need to store an association to the purchase... well, then it depends on what you really need to track. For example, you could just update the QuoteRequest, marking the selected quote. (Add an IsSelected or something similar to the quote class Quote.) Then the purchase could be linked back to the quote request, and you could identify the quote by way of the flags.
Again, all this depends on the context (and I'm just making guesses about that).
Since no one has answered this yet I'll just say how I would do it;
Why add a Id at all? just use the index of the List? It the request is "?quote=0" they get the quote at position 0?
Not really sure If I'm not getting something here though...
One option is to have the parent object store the last used id. When adding a new child object you increment the id-counter and add that to the child. When the object is saved the id-counter is automatically incremented.
Lets say you have blog post with comments:
public class Post
{
public int NextCommentId;
public List<Comment> Comments;
...
}
...
var comment = new Comment { Id = post.NextCommentId++ };
post.Comments.Add(comment);
session.SaveChanges();
The code above might not be 100% correct, but should give you an idea of how to do it at least!

Code re-use with Linq-to-Sql - Creating 'generic' look-up tables

I'm working on an application at the moment in ASP.NET MVC which has a number of look-up tables, all of the form
LookUp {
Id
Text
}
As you can see, this just maps the Id to a textual value. These are used for things such as Colours. I now have a number of these, currently 6 and probably soon to be more.
I'm trying to put together an API that can be used via AJAX to allow the user to add/list/remove values from these lookup tables, so for example I could have something like:
http://example.com/Attributes/Colours/[List/Add/Delete]
My current problem is that clearly, regardless of which lookup table I'm using, everything else happens exactly the same. So really there should be no repetition of code whatsoever.
I currently have a custom route which points to an 'AttributeController', which figures out the attribute/look-up table in question based upon the URL (ie http://example.com/Attributes/Colours/List would want the 'Colours' table). I pass the attribute (Colours - a string) and the operation (List/Add/Delete), as well as any other parameters required (say "Red" if I want to add red to the list) back to my repository where the actual work is performed.
Things start getting messy here, as at the moment I've resorted to doing a switch/case on the attribute string, which can then grab the Linq-to-Sql entity corresponding to the particular lookup table. I find this pretty dirty though as I find myself having to write the same operations on each of the look-up entities, ugh!
What I'd really like to do is have some sort of mapping, which I could simply pass in the attribute name and get out some form of generic lookup object, which I could perform the desired operations on without having to care about type.
Is there some way to do this to my Linq-To-Sql entities? I've tried making them implement a basic interface (IAttribute), which simply specifies the Id/Text properties, however doing things like this fails:
System.Data.Linq.Table<IAttribute> table = GetAttribute("Colours");
As I cannot convert System.Data.Linq.Table<Colour> to System.Data.Linq.Table<IAttribute>.
Is there a way to make these look-up tables 'generic'?
Apologies that this is a bit of a brain-dump. There's surely imformation missing here, so just let me know if you'd like any further details. Cheers!
You have 2 options.
Use Expression Trees to dynamically create your lambda expression
Use Dynamic LINQ as detailed on Scott Gu's blog
I've looked at both options and have successfully implemented Expression Trees as my preferred approach.
Here's an example function that i created: (NOT TESTED)
private static bool ValueExists<T>(String Value) where T : class
{
ParameterExpression pe = Expression.Parameter(typeof(T), "p");
Expression value = Expression.Equal(Expression.Property(pe, "ColumnName"), Expression.Constant(Value));
Expression<Func<T, bool>> predicate = Expression.Lambda<Func<T, bool>>(value, pe);
return MyDataContext.GetTable<T>().Where(predicate).Count() > 0;
}
Instead of using a switch statement, you can use a lookup dictionary. This is psuedocode-ish, but this is one way to get your table in question. You'll have to manually maintain the dictionary, but it should be much easier than a switch.
It looks like the DataContext.GetTable() method could be the answer to your problem. You can get a table if you know the type of the linq entity that you want to operate upon.
Dictionary<string, Type> lookupDict = new Dictionary<string, Type>
{
"Colour", typeof(MatchingLinqEntity)
...
}
Type entityType = lookupDict[AttributeFromRouteValue];
YourDataContext db = new YourDataContext();
var entityTable = db.GetTable(entityType);
var entity = entityTable.Single(x => x.Id == IdFromRouteValue);
// or whatever operations you need
db.SubmitChanges()
The Suteki Shop project has some very slick work in it. You could look into their implementation of IRepository<T> and IRepositoryResolver for a generic repository pattern. This really works well with an IoC container, but you could create them manually with reflection if the performance is acceptable. I'd use this route if you have or can add an IoC container to the project. You need to make sure your IoC container supports open generics if you go this route, but I'm pretty sure all the major players do.

Resources