In my web application I include all of my JavaScripts as js files that are embedded resources in the assembly, and add them to the page using ClientScriptManager.GetWebResourceUrl(). However, in some of my js files, I have references to other static assets like image urls. I would like to make those assembly resources as well. Is there a way to tokenize the reference to the resource? e.g.
this.drophint = document.createElement('img');
this.drophint.src = '/_layouts/images/dragdrophint.gif';
Could become something like:
this.drophint = document.createElement('img');
this.drophint.src = '{resource:assembly.location.dragdrophint.gif}';
I'd suggest that you emit the web resources as a dynamic javascript associative array.
Server side code:
StringBuilder script = new StringBuilder();
script.Append("var imgResources = {};");
script.AppendFormat("imgResources['{0}'] = '{1}';",
"drophint",
Page.ClientScript.GetWebResourceUrl(Page.GetType(), "assembly.location.dragdrophint.gif"));
script.AppendFormat("imgResources['{0}'] = '{1}';",
"anotherimg",
Page.ClientScript.GetWebResourceUrl(Page.GetType(), "assembly.location.anotherimg.gif"));
Page.ClientScript.RegisterClientScriptBlock(
Page.GetType(),
"imgResources",
script.ToString(),
true);
Then your client side code looks like this:
this.drophint = document.createElement('img');
this.drophint.src = imgResources['drophint'];
this.anotherimg = document.createElement('img');
this.anotherimg.src = imgResources['anotherimg'];
Hope this helps.
I don't particularly care for the exact implementation #Jon suggests, but the idea behind it is sound and I would concur that emitting these would be a good thing to do.
A slightly better implementation, though this is all subjective to some degree, would be to create a server-side model (read: C# class(es)) that represents this dictionary (or simply use an instance of Dictionary<string, string>) and serialize that to JavaScript literal object notation. That way you are not dealing with the string hacking you see in Jon's example (if that bothers you).
I concur with Jason's assessment of the initial solution I proposed, it can definitely be improved. My solution represents an older school javascript mentality (read, pre the emergence of ajax and JSON). There are always better ways to solve a problem, which one of the reasons why StackOverflow is so cool. Collectively we are better at the craft of programming than anyone of us on our own.
Based on Jason's ideas I'd revise my initial code, and revise some of what Jason suggested. Implement a C# class with two properties, the img resource id and a property that contains the WebResourceUrl. Then, where I differ some from Jason is that rather than using a Dictionary<string, string> I'd propose using a List<MyImageResourceClass>, which you can then in turn serialize to JSON (using DataContractJsonSerializer), and emit the JSON as the dynamic script, rather than manually generating the javascript using a string builder.
Why a List? I think you may find that dictionaries when serialized to JSON, at least using the DataContractJsonSerializer (fyi available with the 3.5 framework only, with the 2.0 or 3.0 framework you'd need to bolt on aspnet ajax and use is JSON serializer), are a little more cumbersome to work with than how a list would serialize. Although that is subjective.
There are implications too with your client side code. Now on the client side you'll have an array of the JSON serialized MyImageResourceClass instances. You'd need to iterate through this array creating your img tags as you go.
Hopefully, these ideas and suggestions can help get you going! And no doubt there are other solutions. I'm interested to see what comes of this.
Related
I am using JSON.Net to deserialize a JSON string to object. My JSON string consists of huge data which can be loaded onto an array or dataset. Could someone please let me know which of the below appraoch is more efficient for the same.
var CSharpClassObject = JsonConvert.DeserializeObject<CSharpClass[]>(jsonString);
and
var dataSetObject = JsonConvert.DeserializeObject<DataSet>(jsonString);
Datasets are generally inefficient due to the memory they require, as well as events, etc. They are really suited to RAD (Rapid Application Development) and not too much else. For your purposes (and probably most others) I would certainly suggest using a custom type.
This might seem dirty but it's for documentation purposes I swear!
I am accessing my services using GETs in my documentation so people can try things out without needing to get too complicated.
Appending x-http-method-override=POST to the URL forces the server to take a GET as a POST
This is all good except when I need to POST an array of objects. This would be simple in a standard POST but today I have a new bread of nightmare.
The expected POST looks like:
{"name":"String","slug":"String","start":"String","end":"String","id":"String","artists":[{"id":"String","name":"String","slug":"String"}],"locationId":"String"}
As you can see there is an array of artists up in here.
I have tried to do the following:
model/listing?start=10:10&end=12:30&artists[0].name=wayne&artists[0].id=artists-289&locationid=locations-641&x-http-method-override=POST
But to no avail.
How can I get an array of objects into a URL so that service stack will be happy with it?!
I appreciate this is not the done thing but it's making explaining my end points infinitely easier with clickable example URLs
You can use JSV to encode complex objects in the URL. This should work for your DTO:
model/listing?name=wayne&artists=[{id:artists-289,name:sample1},{id:artists-290,name:sample2}]&locationId=locations-641
You can programmatically create JSV from an arbitrary object using the ToJsv extension method in ServiceStack.Text.
There are some posts on this, but not an answer to this specific question.
The server is returning this: "/Date(1304146800000)/"
I would like to not change the server-side code at all and instead parse the date that is included in the .Net generated JSON object. This doesn't seem that hard because it looks like it is almost there. Yet there doesn't seem to be a quick fix, at least in these forums.
From previous posts it sounds like this can be done using REGEX but REGEX and I are old enemies that coldly stare at each other across the bar.
Is this the only way? If so, can someone point me to a REGEX reference that is appropriate to this task?
Regards,
Guido
The link from Robert is good, but we should strive to answer the question here, not to just post links.
Here's a quick function that does what you need. http://jsfiddle.net/Aaa6r/
function deserializeDotNetDate(dateStr) {
var matches = /\/Date\((\d*)\)\//.exec(dateStr);
if(!matches) {
return null;
}
return new Date( parseInt( matches[1] ) );
}
deserializeDotNetDate("/Date(1304146800000)/");
Since you're using jQuery I've extended its $.parseJSON() functionality so it's able to do this conversion for you automatically and transparently.
It doesn't convert only .net dates but ISO dates as well. ISO dates are supported by native JSON converters in all major browsers but they work only one way because JSON spec doesn't support date data type.
Read all the details (don't want to copy blog post content here because it would be too much) in my blog post and get the code as well. The idea is still the same: change jQuery's default $.parseJSON() behaviour so it can detect .Net and ISO dates and converts them automatically when parsing JSON data. This way you don't have to traverse your parsed objects and convert dates manually.
How it's used?
$.parseJSON(yourJSONstring, true);
See the additional variable? This makes sure that all your existing code works as expected without any change. But if you do provide the additional parameter and set it to true it will detect dates and convert them accordingly.
Why is this solution better than manual conversion? (suggested by Juan)
Because you lower the risk of human factor of forgetting to convert some variable in your object tree (objects can be deep and wide)
Because your code is in development and if you change some server-side part that returns JSON to the client (rename variables, add new ones, remove existing etc.), you have to think of these manual conversions on the client side as well. If you do it automatically you don't have to think (or do anything) about it.
Two top reasons from the top of my head.
When overriding jQuery functionality feels wrong
When you don't want to actually override existing $.parseJSON() functionality you can minimally change the code and rename the extension to $.parseJSONwithdates() and then always use your own function when parsing JSON. But you may have a problem when you set your Ajax calls to dataType: "json" which automatically calls the original parser. If you use this setting you will have to override jQuery's existing functionality.
The good thing is also that you don't change the original jQuery library code file. You put this extension in a separate file and use it at your own will. Some pages may use it, others may not. But it's wise to use it everywhere otherwise you have the same problem of human factor with forgetting to include the extension. Just include your extension in some global Javascript file (or master page/template) you may be using.
I wonder if there is any .net library to create "dummy" instances of an object. In my particular scenario im dealing with classes with lots of fields, so manual creation is not practical.
It would not be that hard to code this. But maybe there is something out there.
Thanks
There is. Check out NBuilder.
var products = Builder<Product>.CreateListOfSize(100)
.WhereTheFirst(10)
.Have(x => x.QuantityInStock = Generate.RandomInt(1, 2000))
.List;
And it goes from there. Pretty cool stuff.
What is the best way to store instances of a class to file/database?
We have a base class called Command and loads of derived classes.
Users create instances of these classes by adding commands to a graphical designer
where they can configure them. (Set the properties).
We then need a way to store these "commands" to a file without losing
any information.
One idea was to use db4o, but the GPL license is not acceptable for this project.
Any suggestions or code samples?
Update:
(In order to "de-blurryfie" my question :p)
The generated code might look something like:
command[i++] = new DelayInSecondsCommand(2);
command[i++] = new DaliRequestCommand(1, false, 254);
command[i++] = new DaliRequestCommand(2, false, 254);
command[i++] = new DaliRequestCommand(3, false, 254);
command[i++] = new WaitInSecondsCommand(2);
command[i++] = new DaliRequestCommand(1, false, 0);
command[i++] = new DaliRequestCommand(2, false, 0);
command[i++] = new DaliRequestCommand(3, false, 0);
command[i++] = new JumpCommand(0);
But then with loads of different commands.
I know it's possible with .NET serialization, altough I've never used it before,
but I was wondering if there are better alternatives, like I said db4o seems nice but the license doesn't fit the project.
Update 2:
Thank you for the replies. I'll probably go with the serialization solution now,
but I'll look into the other options as well. F.Y.I. data is stored in a SQL Compact database.
Are you trying to save the data in tables? or as blob/clob data? Since you mention files, I assume the latter: any of the standard .NET serializers should be fine - they all support inheritance etc. I'd consider for DataContractSerializer, as this combines the field-level support (like BinaryFormatter), and the assembly-independence of XmlSerializer.
You could also consider more esoteric things like protobuf-net.
So: what is it you need to do that won't work under the standard serializers?
serialization does the trick! Serialization is nothing more than converting an object or a connected graph of objects into a stream of bytes (in order to persist the current state of the object). This can be a binary stream, XML or whatever. You don't have to do this conversion by your own since .Net has great support for serialization. Once you serialized an object, you are free to store this data to a file or database. Likewise, a stream of bytes representing a serialized object can be deserialized into an object which will have the same state as the original one.
Btw: Once you have a serialized stream of bytes, you can apply some more functions on it, e.g. compression or encryption.
Pretty blurry question, why don't you just use .NET's built-in serialization possibilities (e.g. XmlSerializer).
db40 also provides a commerical license but it has been recently bought by versant so maybe you may want to look at that. This sort of database is known as object orientated database and is a way of creating persistant instances of classes which is very different to relational databases that work using tables.
This (wikpedia.org) is a good read on object orienated databases and this (also wikipedia) is a list of some of the available options.
In my opinion object databases are much better & more powerfull than relational and I will only use relational databases like mysql if I really have to (not very often).
I would recommomend you watch these videos and download the trial.
Serialization is a great way to store this type of data. See http://blog.paranoidferret.com/index.php/2008/06/20/csharp-tutorial-xml-serialization/
There is http://www.neodatis.org. Its LGPL, but the time I used there was only a implementation for Java. Now, there's a "beta" release for C#, but I didn't tested.