January 18, 2012

Querying XML in Javascript

The most important aspects of using XML is its usability, readability and the ability to search for information contained in the document. There are various ways to implement the searching/querying the XML document depending on the type of language you would use.

The most widely used method for querying an XML document is XPATH. XPath is a well defined query language especially defined for XML documents. All languages support the XPath syntax in one format or the other, and it also has a very well defined implementation in JavaScript as well.

One of the best resources i found over the net is the following one : Choose between XPath and jQuery with an XPath-jQuery phrase book. It describes 2 different methodologies, one is using XPath and the other is using jQuery. Definitely a must read and able guide to your arsenal.

January 9, 2012

IE and XMLHTTPRequest overrideMimeType dilemma

“Bummer! and IE does it again!!!” I thought, actually that was the first thought that came to my mind and boy was i right about it. I should have been accustomed to all this intricacies and little nuggets here and there, which IE tends to reveal once more often than not.

I will tell you what hit me this time, its the ubiquitous XMLHTTPRequest, that small piece of function which is the forerunner of all things magic about AJAX in HTML5. I tell you, its a very simple problem, now i have a servlet which spits out some response for all the world to consume. When I say “I have” it is not “I Have”, it is like “I have access to”, because I cannot change the output, OK?, right!.

But now i am able to connect and receive the response, we are very fine till here, no problems (I can see it in fiddler, so i am not lying about that). But the problem is I am not able to access the information in javascript, the data is truncated. Why? i tell you why, because the response is a delimited string, delimited using null terminator (that’s how it is :( ).

Rummaging through the web i found that there are problems with AJAX when the response contains a null terminator, but which can be overcome by overriding the mime type for the AJAX response, using “xmlHttpReq.overrideMimeType” function, but guess what the IE doesnt support the function. I ask you why? why wouldnt IE support it? Its more than I can fathom, but such are the strange ways of IE and they want me to patch the servlet to send appropriate mime-type.

Now, I am left with patching the servlet (which is outside the scope) and moreover i dont have access to. Bummer, grumble grumble grumble!!!!

October 18, 2011

Developer resource – Cheat Codes

More often than not as we go through our daily chore of coding, we usually get stuck at some trivial scenario, where we get lost as to what is the next logical statement to be written. Or you may get totally lost as to what needs to be done and how to go about achieving the results for the given problem. Sounds familiar? Happens often to me, that’s why when i stumbled upon this site, it was answer to my prayers.

For all the lost souls, this is the first place of knocking http://devcheatsheet.com/. It has a host of Cheat codes ranging over a wide programming section. Go check it out.

Happy coding

December 25, 2010

Accessing Session from Javascript using JQuery, AJAX in ASP.Net

Well, well well, this is one of those problems which crops out many a time while developing web application “How do i access session variables in my Javascript?” Usually the answer is you cannot, simply because sessions are stored on the server and your application is running on some remote client. Theoretically that is truth, but not the whole truth. Let us dispel the misconception.

 

Accessing session variables in ASP.Net

Well as we said before, it is not completely true when someone tells you, that session values cannot be used in JavaScript. It can be done, but with limitations. You can only have read-only access :)

This is how we do it

//Consider you have set the following session variable in code-behind
//Session[“UserName”] = “kalpesh”
function PrintUserName()
{
var sv = '<%= Session["UserName"] %>'
} 
 
//When you execute the aspx page; the value should be replaced by the session value
//e.g. var sv = ‘kalpesh’

 

Pretty simple isnt it? For most purposes this will do just fine. Where the value is largely static i.e. it doesn’t change much often we can just get by with no issues. What do you do for values which are constantly modified and need to be displayed to the user, without forcing the user to refresh the page?

 

Accessing session variables using AJAX

As the question states, we are in a soup when we need to display constantly modifying values. If we have to force the user to modify, you can very well guess what can happen? :)

Despite the popular belief it is quite easy to access session values using AJAX, if you know where to look :D (I have been hunting for it for quite a while, before having a deja vu :) )

All we need to do is create an asmx Web Service which exposes the desired method as shown below

//The important part is “EnableSession = true
[WebMethod(EnableSession = true)]
public string GetSessionValue(String Name)
{
    string sessionVal = String.Empty;
    if (Session != null && Session[Name] != null)
    {
        sessionVal = Session[Name].ToString();
    }
    return sessionVal;
}
 

Invoking web service methods using JQuery

Calling our web method from javascript is very easy. There are a whole lot of tutorials around so i wont get into details.

I have can implemented a generic method to due the AJAX calls offloading for me

 
var webMethod_result;
function WebMethod_OnError(result, response)
{
    //debugger
    //Dummy function for page method ajax call
}
function WebMethod_OnSuccess(result, response)
{
    //Dummy function for page method ajax call
    webMethod_result = result.d;
}

function CallWebMethod(MethodName, ObjParams, isAsync, OnSuccessHandler, OnErrorHandler)
{
    try
    {
    //Set the callback methods for success and error
    if (OnSuccessHandler == undefined || typeof (OnSuccessHandler) == "undefined")
    {
        OnSuccessHandler = WebMethod_OnSuccess
    }

    if (OnErrorHandler == undefined || typeof (OnErrorHandler) == "undefined")
    {
        OnErrorHandler = WebMethod_OnError
    }

    //Serialize the webmethod function parameters
    var serializedParams = "";
//using Json2.js; 
//you can download the file from the location mentioned in the references
   serializedParams = JSON.stringify(ObjParams); 
    //Make the ajax calls
    return $.ajax(
        {
        type: "POST",
        async: isAsync,
        url: "TestJQueryWebservice.asmx/" + MethodName,
        data: serializedParams,
        dataType: "json",
        contentType: "application/json; charset=utf-8",
        success: OnSuccessHandler,
        error: OnErrorHandler
        });
    }
    catch (e)
    {
    //suppress error
    }

    return;
}

 

The next stop is to define proxy methods which can be called from our javascript function

//Proxy method for getting the Session value for a given name 

function GetSessionValue(SessionName, OnSuccessHandler, OnErrorHandler)
        {
            //set web method parameters; should be same as parameter name else the web 
            //method wont be called 
            var methodParams = new Object();
            methodParams.Name = SessionName; 

            CallWebMethod("GetSessionValue", methodParams, false, OnSuccessHandler, OnErrorHandler); 

            //get the response 
            return webMethod_result;
        }
 

 

And calling the method from javascript? Easy :)

var sessionVal; 

sessionVal = GetSessionValue("TestJQuery");

 

Nice :)  

Modifying session variables

Its pretty simple to add a method to modify the session variables. Well this is how you do it.

The web method

[WebMethod(EnableSession = true)]
        public void SetSessionValue(String Name, String Value)
        {
            string sessionVal = String.Empty;

            if (Session != null)
            {
                Session[Name] = Value;
            }
        }

 

The proxy method

function SetSessionValue(SessionName, SessionValue, OnSuccessHandler, OnErrorHandler)
        {
            //set web method parameters; should be same as parameter name else the web method wont be called
            var methodParams = new Object();

            methodParams.Name = SessionName;
            methodParams.Value = SessionValue;

            CallWebMethod("SetSessionValue", methodParams, false, OnSuccessHandler, OnErrorHandler);
        }

 

And the call from javascript

//update session value
SetSessionValue("TestJQuery", "UpdatedValue");

 

Sweet. It can’t get better than this.

Until then, Happy coding :)

 

Refrences

jQuery.ajax()

json2.js : JSON library by Douglas Crockford

JSON Home

December 21, 2010

Displaying formatted text in a Label

Recently while working on some project of mine, i came across an interesting problem (not that it was problem actually, just may be a dilemma), so it got me thinking. The problem was to display formatted text in a label, as you must have already guessed by reading the title.

The solution for it is very simple, if you ask me and the solution is very much acceptable :) , then you may ask why are we bothered about the problem at all? for one I was feeling bored and wanted to do something interesting :D and two, this clears a lot of clutter from the application :)

The Simple Solution

lblText.Text = String.Format("Age is : {0}", "78"); //this is a hypothetical example

In most cases this will be very acceptable, but some more of those String.Format functions and your code starts to clutter up. Moreover, this will permanently change the text property of the label, so you wont be able to retrieve the original value “78”, if you wanted to :(

The Elegant Solution

Create a user control which inherits from Label Control, exposing additional property

 

public virtual String FormatString
       {
           get
           {

//get the value stored in the viewstate; Default Empty string

//Need to check the viewstate for nulls 
               return ViewState.GetValue("FormatString",String.Empty);
           }
           set
           {

//save the value to viewstate
               ViewState.SetValue("FormatString", value);
           }
       }

Which can then be used as follows.

lblText.FormatString = "Age is : {0}";
lblText.Text = “78”; //this is a hypothetical example

How about that? A little better, but we can do better, we can set the format string in the aspx/ascx and set the text property in the code behind.

<cc1:FormatedLabel runat="server" ID="lblFormatString" Text="89" FormatString="Age is : {0}"></cc1:FormatedLabel>

//Code behind
lblFormatString.Text = “78”;

 

Formatting Numeric types

Things started to get little exciting when we try to format numeric data i.e. int, floats etc. What would you do to display numeric data in exponential format e.g.”1.052033e+003” for a given text “1052.0329112756”. Hmmmmm.

The String.Format function formats the string based on a given format string provided, the object on which the formatting is to be performed supports it. Pretty heavy stuff, huh. In simple words it means format string “{0:e}” for instance, is only applicable when you are using a numeric datatype. See below

String frmtString = “{0:e}”;
String formattedString = String.Empty;

String sVal =”78”;

formattedString  = String.Format(frmtString ,sVal ); //will not format as expected; output will be “78”

int iVal = “89”;
formattedString  = String.Format(frmtString ,iVal ); //format as expected; output will be “8.900000e+001”

So if we try to do the following, it wont work

<cc1:FormatedLabel runat="server" ID="lblFormatString" Text="1052.0329112756" FormatString="{0:e}"></cc1:FormatedLabel>

//output
1052.0329112756

This wont work because the text property contains string data type and string data type does not support “e” format, that format is specific to numeric data type. So how do we get around this problem? One solution which immediately came to my mind is specify the Data Type for formatting

public enum DataType
{
    String,
    Numeric,
    DateTime,
    Boolean
}

public DataType DataType
       {
           get
           {
               return ViewState.GetValue("DataType", DataType.String);
           }
           set
           {
               ViewState.SetValue("DataType", value);
           }
       }

I have added support/made provisions for other datatypes as well :) You can add more if you want to.

Cool, now we are getting somewhere. Now you can do the following and you should get see the expected result :)

<cc1:FormatedLabel runat="server" ID="lblFormatString" Text="1052.0329112756" FormatString="{0:e}" DataType="Numeric"></cc1:FormatedLabel>

//Output
1.052033e+003

 

Voila, this is neat.

 

String to DataType Conversion

Its a little bit tricky when you have to convert the data from string to actual data type, for this small control it is not an issue. The way i got about it is by using TypeDescriptor and TypeConverters classes :)

Its a simple control, but may be very useful. Happy coding :)

Source Code

If you are interested, you can get the source code from the link provided.

NOTE :- Please note that the source code is in a zip file. Due to some restriction by WordPress.com, i have renamed the file as “FormattedLabel.zip.pdf”.

Download Source

 

References

MSDN : TypeDescriptor Class

MSDN : TypeConverter Class

October 23, 2010

How To [SQL] : Convert Binary String to Integer value

Recently i came across a very trivial but an interesting problem. The problem was how to convert a string representing a binary value to its corresponding integer value in SQL. I searched high and dry on the net, but was faced with no luck of finding an inbuilt method to accomplish the task.

So reluctantly i set out of doing it my own way. After a couple of false starts i came up with this solution. Pretty simple and elegant, more importantly effective.


/****** Object:  UserDefinedFunction [dbo].[UDF_BinarytoInt]    Script Date: 10/04/2010 20:47:36 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[UDF_BinarytoInt]') AND TYPE in (N'FN', N'IF', N'TF', N'FS', N'FT'))
DROP FUNCTION [dbo].[UDF_BinarytoInt]
GO

/*
Converts a given binary string to a INTeger value
e.g. 11 => 3

SELECT  [dbo].[udf_binarytoINT]('1011011011110') -- 5854
SELECT [dbo].[udf_binarytoINT]('1111100111101111111') --511871

*/
CREATE FUNCTION  [dbo].[UDF_BinarytoInt](@binarystring NVARCHAR(100))
RETURNS INT
AS
BEGIN

DECLARE @position INT, @rev NVARCHAR(100), @intvalue INT
-- Initialize the variables.
SET @position = 1
SET @rev = REVERSE(@binarystring)

DECLARE  @tbl table (powerv INT, bitvalue NVARCHAR(1))

--Split the individual bits (0/1) into seperate rows 
WHILE @position <= len(@rev)
   BEGIN
		INSERT INTO @tbl(powerv, bitvalue)
		SELECT @position -1, SUBSTRING(@rev, @position, 1)
	    SET @position = @position + 1
   END

SELECT @intvalue = sum(power(2, powerv) * bitvalue)
FROM @tbl
WHERE bitvalue > 0

RETURN @intvalue
END
GO

Until then, happy coding :)

October 13, 2010

Attributes, Properties and ViewState

Recently i was thinking on a rather a small but a niggling problem, as part of web control development, we save the information we need to be persisted in viewstate(this is rather obvious to state). The way i do it is as follows

   1:  public string ViewStatePropertyName
   2:          {
   3:              get
   4:              {
   5:                  //this is rather simplified version; we need to check null objects as well
   6:                  return (string)ViewState["ViewStatePropertyName"];
   7:              }
   8:              set
   9:              {
  10:                  ViewState["ViewStatePropertyName"] = value;
  11:              }
  12:          }

This works fine, but takes up a lot of space. So i was thinking on the lines of using the power of Attributes (MSDN : Attributes Tutorial). As i was wandering around i stumbled upon this article, which does pretty much the same thing what i wanted. Here is the link : Saving server control properties to ViewState with custom attributes.

 

I havent tried the example, will take a look once i have some little free space on my hand. Until then Happy Coding.

March 19, 2010

Convert String Value to Valid DataType using Type Converters

While working on one of my projects which entitled creation of user control in ASP.Net, i was flummoxed with a very interesting problem. The problem was very simple and no doubt there was a straight forward answer to it, but i was not satisfied. The problem is for initializing properties for control dynamically.

The user control is generic, but there is a fixed set of properties which are requierd for a certain behaviour. Values for each property for a given behaviour is stored in an XML config file. The user control will have a unique identifier which will point to the correct configuration.

Lets dive into the problem space.

Say there is a user control which has different types of properties exposed. The properties themselves are of different data types (for e.g. int, boolean, string, string array, enums. Pretty complex control, I know :) , but this is a grind you need to go make things generic). For illustration let us assume a realistic scenario, where this kind of complex situation may arise (there are very few of them though :) )

For illustration we shall assume a very simple scenario. We shall develop a user control for drawing a shape (2-Dimensional)

The shape control will have the following properties

  • Type
    • Enum type
    • Type of shape (Circle, rectangle, polygon etc)
  • No of Sides
    • Integer
    • in case of polygon type
  • Length of each side
    • Array of strings (comma seperated string values)
    • in case of polygon type
  • Scale
    • Enum type
    • The type of mathematical scale to use for lengths(Centimeter, Millimeter, Inches, meters)
  • some more properties

To initialize the properties of this control in the consuming aspx/ascx we would usually do something as suggested below

<Aryan:Shape runat="server" Type="Polygon" Sides="5" Length="20,45,45,60,50" Scale="Centimeter"></Aryan:Shape>

We wont go into details of how the properties are implemented, for our little pertains to initializing the properties dynamically.

The XML configuration snippet looks like below (for instance Shape type – Square)

So now if we wanted to refer to the configuration file to read th

<Shapes>
  <Shape ID="Square">
    <Property Name="Type" Value="Polygon"></Property>
    <Property Name="Sides" Value="4"></Property>
    <Property Name="Length" Value="20,20,20,20"></Property>
    <Property Name="Scale" Value="Inches"></Property>
  </Shape>
</Shapes>

e property values, we would do something like this

<Aryan:Shape runat="server" ShapeConfigID="Square"></Aryan:Shape>

Makes my consuming page less cluttered and i can reuse my configuration across multiple pages, effectively allowing to centralize my changes. sweet :)

How the values are initialized is what we are concerned and the crux of the post.

For initializing the values we need to do the following

  • Read xml
  • Read property value
  • Assuming property value exists cast the property value to appropriate datatype and assign the value.
/// <summary>
/// Reads the configuration information for the given shape and returns the value
/// for the property provided by PropertyName
/// </summary>
/// <param name="PropertyName">Name of the property whose value need to be read</param>
/// <returns></returns>
private String GetPropertyValue(String PropertyName)
{
    //read the xml file or the xml segment
    //assuming we have the proper xml segment
    //get to the property node suggested by property name
    //XPath = "//Shape/Propert[@Name='<PropertyName>']"
    //read the node and return value
}

The function is pretty simple and i wont go into details of the implementation :)

string sides = GetPropertyValue("Sides");
int intsides = -1;

Int32.TryParse(sides, out intsides);
//set the property 
shp.sides = intsides;

The steps repeats for the other properties, based on the datatype the code changes. If the number of properties increase you can imagine the horror of the situation.

This type of code gives me the chills in any case, something needs to be done. I wanted something elegant.

This is how i did it, may be it is not the most fullproof, but it works and it reduces the lines of code i would otherwise have to write. I stumbled upon the solution during one of my rendezvous on the net. The solution uses Generics and another concept TypeConverters.

There are whole lot of type converters defined which reads a string value and tries to convert the value to the appropriate datatype. There are whole lot of methods provided in the typeconverter class, which can be used, the one which i use is ConvertFromInvariantString method, which takes string as an argument and tries to convert it into the appropriate datatype. Here is the method

/// <summary>
/// Convert the string value to the appropriate datatype suggested by T
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="dataValueString"></param>
/// <returns></returns>
public T GetDatafromString<T>(string dataValueString)
{
    //Initialize the value to return a default value
    T returnValue = default(T);

    //Get the Type for the return datatype; the Type will be used to get the appropriate converter
    Type valueType = typeof(T);

    //Get the converter for the given datatype
    TypeConverter converter = TypeDescriptor.GetConverter(valueType);

    //Convert the string to the appropriate data type value;
    //the value returned will be a an object which needs to be cast to the required datatype
    returnValue = (T)converter.ConvertFromInvariantString(dataValueString);

    return returnValue;
}

Inorder to return the appropriate value for a given datatype with the value returned from XML file, the method below will do the bulk of the work


private T GetPropertyValue<T>(String PropertyName)
{
    //read the xml file or the xml segment
    //assuming we have the proper xml segment
    //get to the property node suggested by property name
    //XPath = "//Shape/Propert[@Name='<PropertyName>']"
    //read the node

 //if the node contains value get the value
    return GetDatafromString<T>(dataValueString);
}

Now inorder to initialize the properties of the control, all we need to do is this

...
shp.sides = GetDataFromString<int>("Sides");
...

It even works for enum types, so i no longer need to cast the enum to the appropriate enumtype, so this code will also work as a charm.

shp.Type = GetPropertyValue<Shape>("Shape");

Sweet i say, very sweet.

With little ingenuity you can make it work for string array as well, we shall keep this as an exercise for you guys ;)

 

Refrences

MSDN : TypeConverter Class

MSDN : An introduction to Generics

October 5, 2009

Getting the absolute path in ASP.NET which is application independent

There comes a time when you need to get the absolute path to reference a file or some resource existing at some relative path of the website or web application. As things turned i was in need some of the similar functionality. The first thing that came to my mind was doing something similar :

 

//get the absolute path for the following relative path
String relPath = @"~/ImageResource/ImageName.jpg";
Control cntrl = new Control();
String absPath = cntrl.ResolveClientUrl(relPath);

As it is this works great, but i wanted something more elegant, which doesnt involve the creation of the Control object. So i searched for sometime and stumbled upon an unknown utility function available, right over in .NET framework. Interesting to know that there so many useful functionality in-built in .NET framework which rarely are seen in practice.

Ok then about this utility API is called VirtualPathUtility and it is contained in the System.Web namespace. So using the VirtualUtilityPath you can rewrite the above piece of code as follows

 //get the absolute path for the following relative path
String relPath = @"~/ImageResource/ImageName.jpg";
String absPath =VirtualPathUtility.ToAbsolute(relPath);

Nice little function. But beware there are some pitfalls you need to avoid. This function is not one size fits all solution. You need to be aware of some of shortfalls described in some of the posts below. But for simple use, this works great.

 

Related Posts
MSDN: VirtualPathUtility Class
Weblogs.asp.net: VirtualPathUtility Class
How VirtualPathUtility combines paths in .Net 2.0 – level 100
September 25, 2009

How-To : Splitting delimited strings using XQuery in SQL

Well, this was just kind of an experiment of sorts of using XQuery. The idea just occured some time back when i was trying some other similar experiment.

Now as you all know there is no in-built function for Split in SQL. So lots of people have come out with different solution. This solution is just another solution to the old problem of splitting delimited strings.

The solutions i found mostly revolved around string manipulation, and i have been using the same before my chance encounter with XML support in SQL. The solution i came out with was using XQuery support in SQL Server and it works pretty well too. My thoughts are, it might be just a little wee faster than the other implementation (no numbers from me on that front :) )

Implementation

DECLARE @DelimitedString NVARCHAR(500)
DECLARE @Delimiter NVARCHAR(10)
DECLARE @DelimitedStringXML XML

SET @DelimitedString = 'Apples,Bananas,Mangoes,Peaches,Watermelons'

SET @Delimiter = ','

--Create a document fragment for the delimited string
SET @DelimitedString = REPLACE('<s>' + @DelimitedString + '</s>',@Delimiter, '</s><s>' )
PRINT @DelimitedString --PRINTS <s>Apples</s><s>Bananas</s><s>Mangoes</s><s>Peaches</s><s>Watermelons</s>

--Cast the string to xml format, for use in the xquery
SET @DelimitedStringXML = CAST(@DelimitedString AS XML)

SELECT t.r.query('./text()')
FROM @DelimitedStringXML.nodes('/s') t(r)

For people who are unfamiliar with Xquery can check out the reference section.

Have fun and happy coding

Reference

MSDN :: Introduction to XQuery in SQL Server 2005

MSDN Blogs :: XQuery Inside SQL Server 2005

Follow

Get every new post delivered to your Inbox.