Archive for Web

Easily Move Objects From .NET to Javascript

Jun 22

For those of you who are (un)fortunate enough to do web development you will probably run into the issue of wanting to move a .NET DTO and be able to access it in JavaScript. The simple way to do this is to use JSON (I know this is nothing new but a lot of people have not heard of this technology). JSON stands for the JavaScript Object Notation and is a simple string representation of an object that can be parsed using the JavaScript eval() method.

Simply the way this works is that a .NET library (I am using the free newtonsoft library in my project) takes an object and serializes it to a string. We then call var object = eval(serializedString) and then we can access all the properties off the object (and it seriously is that simple).

.NET Code:

public interface IResource
{
      IList<IResource> Resources { get; set; }
      string Name { get; }
      bool IsOnline { get; }
      void Check();
}

public string GetServers()
{
      return Newtonsoft.Json.JavaScriptConvert.SerializeObject(resource);
}

JavaScript Code:

function ShowObject(input)
{
      var resource = eval("(" + input + ")");
      document.getElementById("txtName").value = resource.Name;
      document.getElementById("chkIsOnline").checked = resource.IsOnline;
      //we could actually walk resource.Resources in a recursive fashion here as even the 
      //child collections get serialized and sent across the wire.
}

And it is just that easy. You can also modify the object in JavaScript and return it to .NET and call JavaScriptConvert.DeserializeObject() and have the object back in the .NET form and process it. The possibilities for this are quite powerful.

I would watch for security issues with this though as calling eval on a string with JavaScript can be quite dangerous if the input is not validated properly! This is because the eval() function evaluates a string and executes it as if it was JavaScript so the injection of dangerous code is a very simple possibility.

Filed Under: Web

Debugging Javascript

Aug 10

One thing I have noticed is that there are numerous ways to debug javascript with visual studio. I thought I would share some of them that I have found over the years.

  1. In internet explorer you can go to view->script debugger->Break
    at next statement. This will cause the debugger to run when the next
    javascript statement runs in the browser. This is not a feature that is
    enabled by default. To enable it you will need to go to the advanced
    tab in internet options and uncheck the “Disable Script Debugging”
    option and restart IE. This is the method I use most often.
  2. Force javascript to call the debugger. You can do this like so in your javascript:
        function DoTask()
        {
           debugger;
           return 3+7;
        }
    when the browser encounters the debugger statement it will lanch vs and you can step through your code.
  3. In visual stuido attach the debugger to the Internet Explorer property
    and select script as what you want to debug. On the right hand side
    where solution explorer is you should see a tab called running
    documents. Select the document to debug and set any breakpoints you
    wish to step through.
  4. Use Firefoxes javascript console to spot errors. It is the icon in the top right hand corner and will show a list of javascript errors on the page which is quite handy at a glance.
  5. If you are a firefox user you can also call Ghost Busters. By that I mean install the Venkman Javascript debugger for firefox that allows you to debug firefox (get it here: http://www.mozilla.org/projects/venkman/). I have only used it once and perfered using the IE methods myself. But if you don’t have a script debugger installed on your machine this is a good solution.

Filed Under: Web

~= friend

May 17

One of those nice little things not many people know about is the use
of a ~ character in relative URLS. The ~ allows you to access the
document root.

i.e. <a href=”~/showlog.aspx”>Show the log</a>

If this was in a virtual directory called sampleapp the url would render to be

http://localhost/sampleapp/showlog.aspx

but when deployed to a production and not in a sample app it would be
http://www.sampleapp.com/showlog.aspx

if we just had a link without the tilde like this:
i.e. <a href=”/showlog.aspx”>Show the log</a>

then it would work in production but in development it would render to the root of the server
i.e. http://localhost/showlog.aspx
instead of the vdir like we want :)

Just
a little trick. I am not sure if this works on apache or not or if IIS
is finding those ~’s and replacing them for the user.

Filed Under: Web

Sending a file to the client

May 17
Sometimes you need to send a file to the client by them clicking a
link. If it is stored on your hard drive (appologies for the bad
formatting. busy day today):

private sub SendFile(fileName as string)
dim filepath as string = Server.MapPath(“files”) & fileName

filepath = Server.UrlPathEncode(filepath) ‘encoded to remove special characters i.e. spaces

response.clear() ‘clear the output buffer

Response.ContentType = “application/binary”
‘binaries are almost always downloaded. If it was set to excel for an
excel file the browser might try to open it in the browser window

Response.AddHeader(“Content-Disposition”, “attachment;filename=” + fileName) ‘This is what tells the browser the filename to prompt the user with when they save it

Response.TransmitFile(filePath) ‘transmit the file (internally reads and sends the file to the client

Response.Flush() ‘write everything in the buffer to the client

Response.End() ‘end the response so nothing else gets sent to the browser

end sub

Often you have these files in an area outside of the web root or in a database. If you have this scenario you can use a

Response.BinaryWrite(bytearray)

to
send a bytearray to the client. You can easily get a byte array by
reading a file with a filestream and then copying that to a byte array.
Wish I had time to post on that today but sadly I do not.

Filed Under: Web

Determining if a session has expired

May 16

The first thing to discuss is Session.IsNewSession() this returns true if a session was just created on this request.

On the first request to a page this will return true.
durring the session it will return false
after a timeout error occurs this will also return true (the session no longer exists so it gets recreated).

So we know that if IsNewSession() returns true that either this is a new request or the session has timed out.

Now
the way that sessions work is the server sends the browser a cookie
with the session ID. On every request the client sends this cookie and
the server loads your session.

On the first request to a page the browser will not send a cookie
durring the session it will send the cookie
after a timout occurs it will still send the cookie

So now we can determine if we have a timeout by using this code:

If Session.IsNewSession Then
Dim strCookieHeader As String = Request.Headers(“Cookie”)
If strCookieHeader.Length > 0 AndAlso strCookieHeader.IndexOf(“ASP.NET_SessionId”) > 0 Then
‘redirect to timeout page here
end if

I put this code into a basepage that all of my pages that use session data inherit from.

Filed Under: Web

Why not to depend on client side validation

May 16

A great example on why not to depend on client side validation only:
http://thedailywtf.com/forums/65974/ShowPost.aspx

Filed Under: Web

Javascript rounding errors

May 16

I have this in code:

var total = parseFloat(txtGLItemAmount1.value) + parseFloat(txtGLItemAmount2.value)

when I insert 110.16 and 7.74 I should get 117.90 but instead get 117.8999999999

Pretty
freakin weird! I assume this has something to do with floating point
math and all its weirdness. The fix I found for this was this line:

total = total.toFixed(2);

This yeilds the correct value. I bet that I could do this as well to get it correct:

var total = txtGLItemAmount1.value.toFixed(2) + txtGLItemAmount2.value.toFixed(2);

Filed Under: Web

Cool web tool

May 11

It has been a long time since I saw a peice of software (Especially a
plugin) that makes me go “Wow how did I ever live without this / why
didn’t I think of that?”. I have only played with the IE Dev toolbar
for 5 mins now and I had to write about it.

1. Allows you to hightlight all tables or table cells or divs on a page
2. Show the DOM of a page in a handy little treeview
3. Easily disable Cache, Images, Cookies, script, or the popup blocker
4. Validate a pages HTML, CSS, XHTML, Feed, links, and some other stuff I don’t know about
5. Show image dimensions, filesizes, alt tags, and paths
6. Resize the browser window to any size you want (great for testing a site that needs to be 800×600 compatible)
7. Shortcuts to clear cookies, cache, and possibly session (i.e. server side cookies)
8. A ruler that you can draw on a page and get the pixel measurements of items on the page

thats what I have discovered in ten minutes.

The IE download is here:
http://www.microsoft.com/downloads/details.aspx?FamilyID=e59c3964-672d-4511-bb3e-2d5e1db91038&displaylang=en

Also for the Mozilla/Firefox people out there there is apparently a tool like it that can be found here:
http://chrispederick.com/work/webdeveloper/

Filed Under: Web

I finally caved to AJAX

May 11

I had played a little with AJAX (Async Java and XML) but I finally
caved and started to use it in an app. I must say that it is pretty
freakin sweet but I am still concerned (as always with javascript) how
it will behave in different browsers and operating sysystems.

<script>;
function CreateRequestObject()

{
if (navigator.appName == “Microsoft Internet Explorer”)
return new ActiveXObject(“Microsoft.XMLHTTP”)
else
return new XMLHttpRequest();
}

var http = CreateRequestObject();

function getData()
{
http.open(‘get’, ‘info.ext’)
http.onreadystatechange = handleResponse
http.send(null);
}

function handleResponse()
{
if (http.readyState == 4)
{
var data = http.responseText;
var arr = data.split(“”);
alert(arr[0]);
}
}

</script>
<a onclick=”getData()” href=”#”>get stuff</a>

Now
this is a basic example but one thing that I have done that most other
samples have done is not use xml at all in this (my info.ext file
contains only this: “testtest2″). I have no real need to use xml. xml
would take more bandwidth, more complex code, and a dependancy on the
microsoft XML parser activeXobject. Simple text parsing will do fine
for me :)

If your info.ext file is a dynamic page (i.e. asp, php, jsp, etc.) and you want to pass parameters to it do this:

function getData(params)
{
http.open(‘get’, ‘info.ext’ + params)
http.onreadystatechange = handleResponse
http.send(null);
}

and then in the html:

<a onclick=”getData(‘?action=getdata&id=37)” href=”#”>get stuff</a>;

I
assume that you can send post data by changing the method to post in
the http.open line and then replace the null in http.send() with the
post data you want to send. I have not tried this as it is a bit more
than I need.

I hope that gets you started. It really is quite easy even though js is a pain and makes me a little twitchier!

Filed Under: Web

Validator Controls and IE

May 4

I developed a little app last night that used the builtin ASP.NET
validators. Now that I am running firefox as my default browser I have
discovered that the validators client script does not work in anything
other than IE. The reason for this is that the BaseValidator class (all
validation controls derive from this class) have methods the emit
javascript to do the validation. This script also contains an array of
validator controls and summaries that looks like this:

var Page_ValidationSummaries = new Array(document.all["ValidationSummary1"]);
var
Page_Validators = new Array(document.all["RequiredFieldValidator1"],
document.all["RequiredFieldValidator2"],
document.all["RequiredFieldValidator3"],
document.all["RequiredFieldValidator4"],
document.all["RegularExpressionValidator1"],
document.all["RequiredFieldValidator5"]);

And therin lies the
problem. Only IE uses document.all every other browser I know off does
not recognize document.all. Instead what should have been used is
document.getElementById to get the controls.

There are two ways I see to fix this. The first is to just download a replacement validator suite like this free one.
I have not tried it (so I appreciate some feedback if you do). Instead
I am going to do things the hard way and fix the javascript issues by
creating a class that emits compatable javascript for all browsers. I
do it the hard way so that I can better understand what is going on
internally and seems to help me build better solutions.

Update.
It is now 9pm and I am frustrated. I have made a ton of progress
towards this goal but am having issues with the runtime not wanting to
run my override (I assume this is because it thinks firefox can only do
html 3.2 not 4.0 like the all mighty IE). I am going to leave this for
a while and get some beer therapy and maybe try more tommorow. I will
post the code once I get a solution figured out.

Filed Under: Web