Archive

Posts Tagged ‘Javascript’

Pass your own arguments to the ClientValidationFunction in a CustomValidator

May 30th, 2010 Anuraj P No comments

Last few days I am working on an ASP.Net, where I can create Grids, Dropdown lists with Post back :) , and the best part is browser compatibility, client only requires compatible with IE. Yes it was a refresher course for me, I revisited GridView templates, Page.IsPostback checking etc. Today I got a requirement like I need to validate few radio buttons. I searched for an implementation, I found we can use required field validator for RadioButtonList, but in my case it was Radio buttons (Initially it was RadioButtonList, but due to some customization issues, I changed it to Radio Buttons). Then I implemented a custom validator, and in the client validation function I hardcoded the Radio Button ids, because for the client validation function we can’t pass the parameters to the function. Same problem again I faced in a GridView, where the problem I found was I won’t get the client id of the radio button in the Item template. :( After doing some research I found we can extend the custom validator control using Validation Framework. And here is the implementation. Using this we can add properties to the source / sender parameter in the client side validation function.

function ValidateRadioButtons(source, arguments) {
    var radio1 = document.getElementById(source.Radio1);
    var radio2 = document.getElementById(source.Radio2);
    var radio4 = document.getElementById(source.Radio4);
    var radio3 = document.getElementById(source.Radio3);
    var result = radio1.checked || radio2.checked || radio3.checked || radio4.checked;
    arguments.IsValid = result;
}

This is the JavaScript function which implements the validation logic. You can get the controls as part of the Source object. To get the Source.Radio1, you need to register the Radio1 as ClientValidator attribute. You can do some C# code like this.

protected void Page_Load(object sender, EventArgs e)
{
    this.Page.ClientScript.RegisterExpandoAttribute(customCheck.ClientID, "Radio1", this.radio1.ClientID, false);
    this.Page.ClientScript.RegisterExpandoAttribute(customCheck.ClientID, "Radio2", this.radio2.ClientID, false);
    this.Page.ClientScript.RegisterExpandoAttribute(customCheck.ClientID, "Radio3", this.radio3.ClientID, false);
    this.Page.ClientScript.RegisterExpandoAttribute(customCheck.ClientID, "Radio4", this.radio4.ClientID, false);
}

And the ASPX Code is like this

<asp:CustomValidator runat="server" ID="customCheck" ClientValidationFunction="ValidateRadioButtons"
        ErrorMessage="Choose any option" />

And here is the Output code generated for the custom validator.

Custom validator output rendering

Custom validator output rendering

Happy Coding.

System.InvalidOperationException – The length of the string exceeds the value set on the maxJsonLength property.

April 16th, 2010 Anuraj P No comments

Yesterday I got a problem from one of my friend; he is getting a Javascript exception from some Ajax Page methods. The exception occurred when he tried to return a very long string from web method. The exception was like this.

Error: Sys.Net.WebServiceFailedException: The server method ‘WebServiceMethod’ failed with the following error: System.InvalidOperationException– Error during serialization or deserialization using the JSON JavaScriptSerializer. The length of the string exceeds the value set on the maxJsonLength property.

After doing some searching we resolved it. You can resolve this error by modifying the web.config file, and add / modify the Configuring JSON Serialization.

<configuration>
  <system.web.extensions>
    <scripting>
      <webServices>
        <jsonSerialization maxJsonLength="5000"/>
      </webServices>
    </scripting>
  </system.web.extensions>
</configuration>

The default length is 102400.
You can get more information about this from MSDN : http://msdn.microsoft.com/en-us/library/bb763183.aspx

Developing simple Windows 7 Gadget – Part 3

March 9th, 2010 Anuraj P No comments

In this I am exploring another two features of Gadget API, one is Docking and other is Flyout. The Docking feature is helpful in Windows Vista, because the gadget lives only in Vista Sidebar, but in Windows 7 it can be anywhere in the desktop. The Docking feature helps to change the size of Gadget, in Windows Vista, the docking / un-docking events will automatically fired, when we drag the gadget out of the sidebar, but in Windows 7 another button will displayed in the Gadget toolbox. You can query the current state of a gadget with System.Gadget.docked. It returns true if docked, false if undocked.

Docking / UnDocking button in Sidebar

Docking / UnDocking button in Sidebar

There are also two events that you can monitor, System.Gadget.onDock and System.Gadget.onUndock, to determine when the docking state changes.

You can change the Width of the gadget by calling document.body.style.width = “130px”;. And the Docking and Undocking events should be attached on the Page_load.

System.Gadget.onDock = dockStateChanged;
System.Gadget.onUndock = dockStateChanged;

And the dockStateChanged function is

function dockStateChanged() {
//Checks the current state of the Gadget, if Docked state, setting the width to 130px;
//Otherwise changing to 330px;
	if (System.Gadget.docked) {
		document.body.style.width = "130px";
document.getElementById("RSSOutput").style.width = "125px";
	} else {
		document.body.style.width = "330px";
document.getElementById("RSSOutput").style.width = "325px";
	}
}

Another feature is Flyout. Flyouts used to extend the Gadget UI. The flyouts are system modal—only one can be displayed at a time. And when a gadget loses focus, its flyout will close. API for Flyouts available under System.Gadget.Flyout. As the flyouts is completely a separate window, with its own DOM, helps to add / create controls dynamically in it. Also you need to specify the flyout file, like Settings file.

The System.Gadget.Flyout.document returns the Document object of the flyout window. To display a flyout you need to set Flyout.show to True and to hide, set it to false. This property also returns the current state of flyout. But we cannot control the location of side bar, it is managed by Sidebar or OS.

System.Gadget.Flyout.file = "flyout.html";

There are certain events also available for Flyouts

System.Gadget.Flyout.onShow = function()
{
//Do something, when flyout is opening, may be a dynamic control creation
}
System.Gadget.Flyout.onHide = function()
{
//Do some code.
}

Developing simple Windows 7 Gadget – Part 2

February 24th, 2010 Anuraj P No comments

In my last post I have created a simple Windows 7 Gadget for testing Regular expressions. In this post we look into the Gadget Options dialog and Gadget API, which helps to display the options dialog and save the preferences from the User. The options dialog is a nice feature used in Gadgets to manage the user preferences. It is also an HTML file. Unlike the main Gadget HTML file, which is specified in the XML Definition file, the Options HTML File is specified in the main gadget file or in the main Javascript file, generally in the gadget initialization area of your script. In the RegEx Tester example, I am using the RegEx function flags as customization options.

RegEx Tester Settings

RegEx Tester Settings

So I have created an HTML File with 3 checkboxes and wrote a javascript function to get the user selected options, create the flags variable, and when closing the Options dialog, save the user preferences. To create the settings or options dialog, set the SettingsUI property.

System.Gadget.settingsUI = "settings.html";

After setting the SettingsUI property, the Gadget will display a Options button in the Gadget handle.

Settings Button

Settings Button

The Gadget API also supports various events / callback functions for the Options dialog, like SettingsClosing, SettingsClosed etc, which helps to save the Preferences and Read the preferences in the Gadget.

System.Gadget.onSettingsClosed = settingsClosed;
function settingsClosed(event) {
	//OK Button clicked.
if (event.closeAction == event.Action.commit) {
	//Load settings here.
}
}

Gadget API supports various methods to read and write settings. For writing setting we can use System.Gadget.Settings.write or System.Gadget.Settings.writeString. Both the functions will expects a key/value pair. And for reading can use System.Gadget.Settings.read or System.Gadget.Settings.readString, both of these functions take a key and return a value. If the key does not exist (for instance if it has never been written) both will return a value of undefined. Use System.Gadget.Settings.xxxxString method, if you are working with string values. All the settings are stored in Settings.ini file. And it is available in the “C:\Users\\AppData\Local\Microsoft\Windows Sidebar” location.
Saving the preferences

System.Gadget.Settings.write("RegExOptionsSaved", "true");
System.Gadget.Settings.write("RegExOption", escape(result));

And reading the Preferences 

if (System.Gadget.Settings.read("RegExOptionsSaved")) {
regExOptions = unescape(System.Gadget.Settings.read("RegExOption"));
}

RegEx Object constructor 

var re = new RegEx("Pattern","Flags");

And the Flags are

  1. Global Search – g – The global search flag makes the RegExp search for a pattern throughout the string, creating an array of all occurrences it can find matching the given pattern.
  2. Ignore Case – i – The ignore case flag makes a regular expression case insensitive. For international coders, note that this might not work on extended characters such as å, ü, ñ, æ.
  3. Multiline Input – m – This flag makes the beginning of input (^) and end of input ($) codes also catch beginning and end of line respectively.

Image cropping in ASP.Net with JQuery

December 7th, 2009 Anuraj P No comments

Yesterday I got a chance to explore Jcrop – the jQuery Image Cropping Plugin. You can get more details about JCrop from here. It is nice JQuery plugin to Crop photos. Here is a simple implementation of JCrop with ASP.Net and C#, which will upload a File to webserver, allows the user to crop and save it back to the server. This is POC code. Make sure you validate all the inputs from end users.

Implementation

For the implementation first download the JQuery plugin from the deepliquid download page. Extact it. Open the JS folder, and add reference of the scripts (jquery.Jcrop.min.js and jquery.min.js) files to the web application. Also Open the CSS folder and link the style sheet (jquery.Jcrop.css) to the ASPX Page. I am using Hidden fields to get the width, height, X, and Y values from the JCrop.

function crop() {
    jQuery(function() {
        jQuery('#<%= PicCropImage.ClientID %>').Jcrop({
            onSelect: updateValues, //this function will be invoked when the user completes his selection
            aspectRatio: 1  //Setting aspectRatio: 1 will allow user to draw rectangle with aspectratio.
        });
    });
    //Updating the values of the Hidden fields from the output of crop.
    function updateValues(img) {
        document.getElementById('<%= positionx.ClientID %>').value = img.x;
        document.getElementById('<%= positiony.ClientID %>').value = img.y;
        document.getElementById('<%= positionx1.ClientID %>').value = img.x2;
        document.getElementById('<%= positiony1.ClientID %>').value = img.y2;
        document.getElementById('<%= sizew.ClientID %>').value = img.w;
        document.getElementById('<%= sizeh.ClientID %>').value = img.h;
    }
}

And in the server side I am taking the values from the Hidden fields and drawing a new image using the values and saving it in the File System.


//Getting the Filename of the Image displayed.
string fileName = Server.MapPath(this.PicCropImage.ImageUrl);
using (Bitmap sourceImage = new Bitmap(fileName, true))
{
    Rectangle destinationArea = new Rectangle(0, 0,
        int.Parse(this.sizew.Value), int.Parse(this.sizeh.Value));
    Rectangle sourceArea =
        new Rectangle(int.Parse(this.positionx.Value), int.Parse(this.positiony.Value),
        int.Parse(this.sizew.Value), int.Parse(this.sizeh.Value));
    using (Bitmap newBitmapImage = new Bitmap(destinationArea.Right, destinationArea.Bottom))
    {
        using (Graphics graphicsImage = Graphics.FromImage(newBitmapImage))
        {
            //Setting the Graphics properties
            graphicsImage.InterpolationMode = InterpolationMode.HighQualityBicubic;
            graphicsImage.CompositingQuality = CompositingQuality.HighQuality;
            graphicsImage.SmoothingMode = SmoothingMode.HighQuality;
            graphicsImage.DrawImage(sourceImage, destinationArea, sourceArea, GraphicsUnit.Pixel);
            IntPtr hbitMap = newBitmapImage.GetHbitmap();
            using (Image image = Image.FromHbitmap(hbitMap))
            {
                //Saving the Image to file system.
                image.Save(Path.Combine(Path.GetDirectoryName(fileName),
                    string.Concat("Cropped_", Path.GetFileName(fileName))), ImageFormat.Jpeg);
            }
        }
    }
}

Thats it. You are ready for cropping with JCrop and ASP.Net.
Happy Cropping :)

A Simple Chat script using ASP.Net C#

September 11th, 2009 Anuraj P 2 comments

Few days back one of my colleague was looking for a simple chat script in ASP.Net, but he can’t found one. Almost all of the chat scripts were in ASP and he want to do it for an internal site. So I thought about implementing one. And here is the simple script using ASP.Net’s Page method feature. For this I am using Windows Authentication, because it is for a intranet site, where users will be coming from one domain only.

Code behind – Global.asax

private List<string> onlineUsers;
void Session_Start(object sender, EventArgs e)
{
	if (this.onlineUsers == null)
	{
            this.onlineUsers = new List</string><string>();
        }

        if (!this.onlineUsers.Contains(HttpContext.Current.User.Identity.Name))
        {
            this.onlineUsers.Add(HttpContext.Current.User.Identity.Name);
        }
        HttpContext.Current.Session["Users"] = this.onlineUsers;
}

void Session_End(object sender, EventArgs e)
{
        if (this.onlineUsers != null)
        {
            this.onlineUsers.Remove(HttpContext.Current.User.Identity.Name);
        }
	HttpContext.Current.Session["Users"] = this.onlineUsers;
}

Web.Config

<authentication mode="Windows"/>
<authorization>
	<deny users="?"/>
</authorization>

Default.aspx.cs

private static List</string><string> chatCollection;

[WebMethod(true)]
public static List</string><string> Add(string comment)
{
	string user = HttpContext.Current.User.Identity.Name;
        if (chatCollection == null)
        {
		chatCollection = new List</string><string>();
        }
        comment = comment.Replace("< ", "[").Replace(">", "]");
        comment = GetSmileys(comment);
        chatCollection.Add(string.Format("<tr><td>{0} :<font color=\"blue\">{1}</font></td></tr>", user, comment));
        return chatCollection;
}

private static string GetSmileys(string comment)
{
        if (comment.Contains("[:-)]"))
        {
        	comment = comment.Replace("[:-)]", "<img src=\"icons\\smile.gif\"/>");
        }
        else if (comment.Contains("[;-)]"))
        {
        	comment = comment.Replace("[;-)]", "<img src=\"icons\\wink.gif\"/>");
        }
        else if (comment.Contains("[:-(]"))
        {
        	comment = comment.Replace("[:-(]", "<img src=\"icons\\frown.gif\"/>");
        }
        else if (comment.Contains("[:-D]"))
        {
        	comment = comment.Replace("[:-D]", "<img src=\"icons\\biggrin.gif\"/>");
        }
        else if (comment.Contains("[:-|]"))
        {
        	comment = comment.Replace("[:-|]", "<img src=\"icons\\blankstare.gif\"/>");
        }
        else if (comment.Contains("[B-)]"))
        {
        	comment = comment.Replace("[B-)]", "<img src=\"icons\\cool.gif\"/>");
        }
        else if (comment.Contains("[}-)]"))
        {
        	comment = comment.Replace("[}-)]", "<img src=\"icons\\devilish.gif\"/>");
        }
        else if (comment.Contains("[:-P]"))
        {
        	comment = comment.Replace("[:-P]", "<img src=\"icons\\p.gif\"/>");
        }
	return comment;
}

[WebMethod(true)]
public static List</string><string> GetChat()
{
	if (chatCollection == null)
        {
        	chatCollection = new List</string><string>();
        }
        return chatCollection;
}

[WebMethod(true)]
public static List</string><string> GetUsers()
{
	if (HttpContext.Current.Session["Users"] == null)
        {
        	HttpContext.Current.Session["Users"] = new List</string><string>();
        }
        return HttpContext.Current.Session["Users"] as List</string><string>;
}

And finally the HTML

Default.aspx


< !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>:: TEAM CHAT ::</title>

    <script type="text/javascript">
        function sendChat() {
            var chatText = $get("txtChatInput").value;
            if (chatText != "") {
                PageMethods.Add(chatText, sendChat_Callback);
            }
            else {
                $get("txtChatInput").focus();
            }
            return false;
        }
        function sendChat_Callback(response) {
            displayChatText(response);
            $get("txtChatInput").value = "";
            $get("txtChatInput").focus();
        }
        function GetChat() {
            PageMethods.GetChat(GetChat_Callback);
        }
        function GetChat_Callback(response) {
            displayChatText(response);
        }
        function displayChatText(response) {
            var result;
            result = "<table>";
            for (var i = response.length - 1; i >= 0; i--) {
                result = result + response[i];
            }
            result = result + "</table>";
            $get("chatOutputDiv").innerHTML = result;
        }
        function getUsers() {
            PageMethods.GetUsers(GetUsers_Callback);
        }
        function GetUsers_Callback(response) {
            $get("lstUsers").options.length = 0;
            for (var i = response.length - 1; i >= 0; i--) {
                addUsers(response[i]);
            }
        }
        function addUsers(text) {
            var optn = document.createElement("OPTION");
            optn.text = text;
            optn.value = text;
            $get("lstUsers").options.add(optn);
        }
        function LoadUI() {
            getUsers();
            GetChat();
            $get("txtChatInput").focus();
        }
        function showAbout() {
            var msg = "Copyright (c) 2009 Anuraj. All rights reserved.\nLicenced under GNU GPL v2.";
            msg += "\n\nVersion 0.2 : Supports Smileys\n";
            msg += "Smileys should be in square brackets, like below,\ncase-sensitive(Sorry I will fix it later)\n";
            msg += "Supported :- [:-)], [;-)], [:-(], [:-D], [:-|], [B-)], [}-)],[:-P]\n";
            msg += "\n\nHappy Chatting [:)]\n";
            alert(msg);
        }
        setInterval("LoadUI();", 5000);
    </script>

    <style type="text/css">
        body
        {
            font-family: Calibri;
            font-size: 11pt;
        }
        input
        {
            font-family: Calibri;
            font-size: 11pt;
            color: Blue;
        }
        .txt
        {
            border: solid 1px #000;
            font-family: Calibri;
            font-size: 11pt;
            color: Black;
        }
        option
        {
            font-family: Calibri;
            font-size: 11pt;
            color: Blue;
        }
        h1
        {
            color: Blue;
            font-size: xx-large;
            text-decoration: underline;
            text-align: center;
        }
    </style>
</head>
<body onload="javascript:LoadUI();">
    <form id="form1" runat="server" onsubmit="javascript:return sendChat();">
    <div>
        <asp :ScriptManager runat="server" ID="scriptMgr" EnablePageMethods="true" ScriptMode="Release"
            EnableViewState="false" />
        <table cellpadding="0" cellspacing="0" border="0">
            <tr>
                <td colspan="2" style="text-align: center">
                    <h1>
                        :: TEAM CHAT ::
                    </h1>
                    <span>A simple chat script using ASP.Net and C#</span>
                    &nbsp;<a href="javascript:void('About');" title="About TeamChat" onclick="javascript:return showAbout

();">?</a>&nbsp;
                </td>
            </tr>
            <tr>
                <td>

                    <input class="txt" type="text" maxlength="1500" style="width: 340px;" id="txtChatInput" />
                </td>
                <td valign="middle">
                    &nbsp;<input type="button" id="cmdSubmit" value="Send" onclick="javascript:return sendChat();" />
                </td>
            </tr>
            <tr>
                <td colspan="2">
                    &nbsp;
                </td>
            </tr>
            <tr>
                <td colspan="2" valign="top">
                    <div id="chatOutput" style="height: 300px; width: 400px; border: solid 1px #000;
                        overflow: scroll;">
                        <div id="chatOutputDiv" style="height: 280px; width: 380px;">
                        </div>
                    </div>
                </td>
            </tr>
            <tr>
                <td colspan="2">
                    &nbsp;
                </td>
            </tr>
            <tr>
                <td colspan="2" valign="top">
                    <label>
                        Online Users</label><br />
                    <select class="txt" size="4" id="lstUsers" style="width: 400px; border: thin solid #000000;
                        font-family: Calibri; font-size: 11pt; color: #FFFFFF;">
                        <option>No users available </option>
                    </select>
                </td>
            </tr>
            <tr>
                <td colspan="2" style="text-align: center; font-size: 11px;">
                    Copyright &copy; 2009 <a href="mailto:anuraj.p@mymailserver.com">Anuraj</a>. All rights
                    reserved.<br />
                    Licenced under GNU GPL v2.
                </td>
            </tr>
        </table>
    </div>
    </form>
</body>
</html>

Here is the Image “Team Chat” running on my machine

Team chat - asp.net script screenshot

Team chat - asp.net script screenshot

Code seems like pretty self explantory. As wordpress don’t support zip attachments, I will upload, and give the source later.

Happy Chating ;)

I took the Emoticons from deviantart.com