*.dannyg

Serializing .NET Resources (.resx) as JSON

Jun
08

This is actually quite a useful solution.  The goal here is to use the same resource file for client and server side coding, while also utilizing the “Culture” awareness of .NET that might be built into your application.

Be sure to create your Resources as a separate satellite assembly.

We are going to create an HttpHandler.  Basically create a class and implement the IHttpHandler interface.

Look at the sample code below.

    public class ResourceJS : IHttpHandler
    {
        public bool IsReusable
        {
            get { return true; }
        }
        public void ProcessRequest(HttpContext context)
        {
            ResourceManager rm = new ResourceManager(ConfigurationManager.AppSettings["JSResourcesAssemblyType"].ToString(),
                Assembly.LoadFile(ConfigurationManager.AppSettings["JSResourcesAssemblyPath"].ToString()));
            rm.GetString("");
            ResourceSet rs = rm.GetResourceSet(Thread.CurrentThread.CurrentCulture, false, false);
            var sbInitial = "var rm = {";
            var sb = new StringBuilder(sbInitial);
            var resEnum = rs.GetEnumerator();
            while (resEnum.MoveNext())
            {
                if (sb.ToString() != sbInitial) sb.Append(",");
                sb.Append(""" + resEnum.Key + "":"" +
                    resEnum.Value.ToString().Replace("rn", "").Replace(""", "\"") + """);
            }

            sb.Append("}");
            sb.ToString();

            context.Response.ContentType = "text/javascript";
            context.Response.Write(sb.ToString());
        }
    }

You can see here that there are two Web.config values that have specified here.  JSResourcesAssemblyType is the full Namespace and root class name of the Resource files.  JSResourcesAssemblyPath is the location of satellite assembly.  This uses reflection to load up the metadata of the assembly.

Once this compiled, you need to add this to the web.config.  Here is a sample for IIS7.

 

<handlers>
            <remove name="WebServiceHandlerFactory-Integrated" />
            <remove name="ScriptHandlerFactory" />
            <remove name="ScriptHandlerFactoryAppServices" />
            <remove name="ScriptResource" />
            <add name="ScriptHandlerFactory" verb="*" path="*.asmx" preCondition="integratedMode" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
            <add name="ScriptHandlerFactoryAppServices" verb="*" path="*_AppService.axd" preCondition="integratedMode" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
            <add name="ScriptResource" preCondition="integratedMode" verb="GET,HEAD" path="ScriptResource.axd" type="System.Web.Handlers.ScriptResourceHandler, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
      <add name="ResourceJS" path="ResourceJS.axd" verb="GET" type="ResourceJS" resourceType="Unspecified" requireAccess="Script" preCondition="integratedMode" />
      <add name="UrlRoutingHandler" preCondition="integratedMode" verb="*" path="UrlRouting.axd" type="System.Web.HttpForbiddenHandler, System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
    </handlers>

You can see the ResourceJS is being extended to the url ResourceJS.axd.  Below is my sample page.

 

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="ResourceJSTest.aspx.cs" Inherits="ResourceJSTest" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script type="text/javascript" src="js/2.1.0.0-debug/jquery-1.4.4.min.js"></script>
    <script type="text/javascript" src="/ResourceJS.axd"></script>
    <script type="text/javascript">
        $(function () {
            $("#target").html(rm.FAQ_Q8_TEXT);
        });
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div id="target"></div>
    </form>
</body>
</html>

The rm object in javascript has all the “keys” that were defined in the original RESX file for that culture.  You can call any of these as a property of rm.   Very re-usable.

Reinstalling WCF on Windows

Mar
24

PartialView: Why?

Mar
22

There are several cases where you would want to break down your view into several small components. One use case that I am working with right now, is I have a multi-lingual site that I would like to reload content using AJAX principles.

Normally what I would do in the case of a non-multi lingual site is to create another ActionResult to return the ViewModel that is changing with the new parameters. I like to use a custom ActionResult that I have called JsonpResult. The problem resides in the fact that I have labels not in my database but in Resource files. So what I would need to do is to somehow hydrate my Resource file data into the ViewModel.

Once the data comes down the pipe, my AJAX callback handles the wiring up of the ViewModel response back to the HTML page using Javascript (I use jQuery).

This definitely works, however it becomes a question of maintainability. I now need to not only maintain my original ASP.NET view, but I also need to maintain a set of scripts that handle AJAXian behavior. If you need to have your site SEO, then you really need to make sure that both the Server Side and Client Side behavior are both working the same.

This is where Partial Views come into play for me. What I do is "pull out" the logical data sections where the bulk of the reload occurs. The nice thing about PartialView is that you can pass your ViewData and Model along to the PartialView. If your PartialView is strongly typed against your ViewModel you can get Intellisense to help with the wiring of the PartialView.

Now all I need to do with my AJAX call is to write the response back to a single DIV rather than handling data points individually. What it does mean is that there would be more content coming down the pipe. However, the trade off is easier to read and maintain code.

Technorati Tags: ,,,

Reverse Proxying With IIS7

Mar
09

There are some really nice modules to add on to IIS7.  One of the them URL Rewrite.  You can also set up a Reverse Proxying rule.  This basically allows you to re-route any traffic that might be specified in DNS to a different server.  In this particular scenario, the DNS rules couldn’t be changed because they weren’t owned.  However, because there is control over the destination server, I can re-route incoming traffic to a different server.

image

Double-click on URL Rewrite on the website that is accepting the incoming traffic.  Then “Add Rule”.  Select “Reverse Proxy” rule.

image

Now you can specify the new destination for all request.  You can be a little more specific about links with regular expressions if necessary.

image

Now you can test your theory by opening your web browser and pointing to the original domain name.  You can even rewrite links in the response.

Technorati Tags: ,,

Curvycorners.js with jQuery

Feb
26

Curvycorners.js is a great library that can add curvycorners to DOM elements.  A lot of older browsers don’t support the CSS3 property to add “radius” to make them rounded (amongst other properties).

I thought it might useful to be able to use curvycorners with jQuery.  Here is a very simple example of this.  Enjoy!

 

$(function () {
    var settings = {
        tl: { radius: 10 },
        tr: { radius: 10 },
        antiAlias: true
    }
 
    var divObj = $(".main");
    for (var i = 0; i < divObj.length; i++) {
        curvyCorners(settings, divObj[i]);
    }
});

jQuery is bundled w/VS2010

Feb
03

Both webforms and MVC have jquery 1.4.1 in the Scripts folder by default.

image

Technorati Tags: ,,

Flex Help

Jan
25

So I have officially delved into the world of Flash development recently.  It took some time to configure Eclipse to work properly, but I got the Gannymede version from eclipse.org site to work just fine. 

Here are some helpful links I ran across.

Flashvars

http://help.adobe.com/en_US/flex/using/WS2db454920e96a9e51e63e3d11c0bf626ae-7feb.html

JSON decoding /as3corelib

http://www.codingforums.com/showthread.php?t=147845

Casting

http://www.darronschall.com/weblog/2006/02/actionscript-3-casting.cfm

AS Codebehind in Flex

http://livedocs.adobe.com/flex/3/html/help.html?content=usingas_6.html

Image as a button

http://soenkerohde.com/2008/05/flex-image-control-as-button/

Technorati Tags: ,,

Decoupling CSS Files (Skinning)

Dec
14

It can be very useful to decouple CSS files from each other without reusing classes.  In some cases you might want a designer to focus on handling the coloring items and not have control over positioning.  This can be very painful especially if most of your CSS classes have already been defined.

This methodology allows you to dynamically create some “Skin” classes based off predefined ones.  I have created two simple helper functions.  This tutorial requires that you use jQuery.

function applySkin() {
    _skinObjs($("body"));    
    _skinObjs($("div"));
    _skinObjs($("span"));    
    _skinObjs($("a"));
}
 
function _skinObjs(objs) {
    for (var i = 0; i < objs.length; i++) $(objs[i]).addClass($(objs[i]).attr("class") + "-Skin");    
}

This will essentially, add a “–Skin” class to every body, div, span, and anchor tag on your page (feel free to add additional tags as necessary). 

Now you can remove what information you want repeated.  So let’s say that you have a Site.css stylesheet and you want to remove some stylistic definitions to a separate file (coloring for example).  To continue on that example, take this sample html code.

<html>
<head>
<title>Sample Page</title>
<link href="Site.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
</head>
<body>
<div class="MainTitle">Hello World!</div>
</body>
</html>

 

Take a look at the Site.css, notice how the color information is in the same file.

.MainTitle 
{
    font-size: 32pt;
    position: absolute;
    top: 100px;
    left: 100px;
    background-color: #fea130;
}

So what I need to do now is to create a separate file.  Let’s call it Site-Skin.css.  I will append to my class “-Skin” as seen earlier.  I also need to remove it from my Site.css file.

Updated Site.css

.MainTitle
{
    font-size: 32pt;
    position: absolute;
    top: 100px;
    left: 100px;
}

 

Site-Skin.css

.MainTitle-Skin
{
    background-color: #fea130;
}

Now I need to specify in my HTML code the link to the particular “-Skin” I want to use.  Let’s say that I’m using a scripting language like ASP.NET, I could put the skins in different folders and dynamically change the decoupled CSS file.

<%@ Page Language="C#" %>
<html>
<head>
<title>Sample Page</title>
<link href="Site.css" rel="stylesheet" type="text/css" />
<link href="<%=Skin_Folder%>/Site-Skin.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
</head>
<body>
<div class="MainTitle">Hello World!</div>
</body>
</html>

 

Now if you look below you can see my folder structure has multiple Site-Skin.css files.

image

This is very powerful as your designer can very easily work on the Skin while you work / or someone else works on positioning and other features of the styling process.

Technorati Tags: ,,,

Cool Stuff Vol 2.

Nov
30

· Jquerypad attached (running against jquery 1.4.4, but you can modify the jquery.js that is being used)

· Stylizer http://www.skybound.ca/

· Blue Beanie Day 2010 http://www.zeldman.com/2010/11/28/dont-forget-blue-beanie-day/ | check out my twitter profile http://twitter.com/#!/dannygnj | http://twitter.com/#!/search/%23bbd4

· HTML5 Gang Sign http://html5homi.es/

· JQuery Splash Screen http://tutorialzine.com/2010/11/apple-style-splash-screen-jquery/

· Visual Studio 2010: JScript Editor Extensions http://visualstudiogallery.msdn.microsoft.com/en-us/872d27ee-38c7-4a97-98dc-0d8a431cc2ed

· Sessionless Controllers in MVC 3 http://www.dotnetcurry.com/ShowArticle.aspx?ID=609&AspxAutoDetectCookieSupport=1

Troubles installing Windows Live Essentials 2011

Nov
21

I faced some tough issues trying to install Windows Live Essentials.  Even more so it feels good to blog as I haven’t written an entry in over a month.  I have a lot of good stuff coming in the next few days.  I got an error when executing the wlsetup-web.exe available from the live.com site.  You can also use the offline installer which is available here.

So the error I was getting said Bad Image, something along the lines that c:windowssystem32wer.dll (Windows Error Reporting), had some kind of issue.  This is related to a corrupt DLL. 

I needed to ensure that the “Windows Modules Installer” service was started.  Then I opened up a command prompt as administrator and ran the following cmd.

sfc /scannow

This took a few minutes to run.  Then I was able to launch the installer.  However the installer informed me that I had to uninstaller Windows Live Mesh Beta (2009).  This was rather difficult.  I ran the uninstall several times, but the Live Essentials installer was still complaining that it was installed.  I wound up searching through the entire registry for any key called “Live Mesh” and deleted them.

After this, I was able to successfully install.  A quick reboot and here I am writing this blog entry in Windows Live Writer 2011.

Technorati Tags: ,,