Archive

Archive for the ‘Javascript’ Category

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 :)

Creating Captcha HTML Helper

September 15th, 2009 Anuraj P 2 comments

After working with ASP.Net MVC, and my previous posts, in this Post I am trying to implement a Captcha HTML Helper, an HTML Helper is just a method that returns a string. Creating Custom HTML Helpers. It is an extension method, to the existing HTML Helper class.
Here is code.(For more details about the Captcha generation code, check my previous post. : Captcha using ASP.Net and C#);

 public static class CaptchaHelper
    {
        public static string Captcha(this HtmlHelper helper, string text)
        {
            string srcPath = System.Web.VirtualPathUtility.ToAbsolute("~/Handler1.ashx");
            string htmlContent = string.Empty;
            htmlContent += "<script type=\"text/javascript\">function __rc(){document.getElementById(\"" + text +
                           "\").src = \"../Handler1.ashx?query=\" + Math.random();}</script>";
            htmlContent += string.Format("<img id=\"{0}\" src=\"{1}\" alt=\"Captcha Image\"/>", text, srcPath);
            htmlContent += "<a href=\"#\" onclick=\"javascript:__rc();\">Reset</a>";
            return htmlContent;
        }
    }

And in the View you can use like, you may need to import the Namespace of CaptchaHelper class.

 < %= Html.Captcha("Sample") %>

It will render a security image. Happy Programming

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

Simple AutoSuggest Textbox using JQuery

April 20th, 2009 Anuraj P 11 comments

Few months back, one of my colleague from UI team, introduced JQuery to me, our purpose was to show some nice dialog boxes using JQuery. After some time I moved in to some Windows projects. And now I am back in web development, few days back I got a task to implement a Auto suggest textbox for US Cities. Initialy I was planning to implement it via ASP.Net AJAX, then I thought about simple
implementations. After some googling I found one solution, I modified the code slightly, and implemented it in a Custom user control.

Here is the C# custom control (AutoSuggestTextBox) code.


[DefaultProperty("Text")]
[ToolboxData("<{0}:AutoSuggestTextBox runat=server></{0}:AutoSuggestTextBox>")]
public class AutoSuggestTextBox : WebControl
{
protected override void RenderContents(HtmlTextWriter output)
output.WriteLine("<script type=\"text/javascript\">");
output.WriteLine("$().ready(function() {");
output.WriteLine(string.Format("$(\"#{0}TextControl\").autocomplete(\"{0}.ashx\");", this.ID));
output.WriteLine("});</script>");
output.WriteLine(string.Format("<input type=\"text\" id=\"{0}TextControl\" name=\"{0}TextControl\" />", this.ID));
}
}

In the implementation, I need to give the output from the database as string, so I implemented the code in a asp.net handler(ASHX) file. And in the ProcessRequest method, I wrote the following code.

if (!string.IsNullOrEmpty(context.Request.QueryString["q"])) // remember, 'q' is the query the autosuggest will pass
        {
            SqlDataReader reader;
            string query = string.Format("SELECT [CityName] FROM [City] WHERE [CityName] LIKE '%{0}'", context.Request.QueryString["q"].ToString());
            using (SqlConnection connection = new SqlConnection("Server=mydbserver; User Id=sa;Password=mypassword;Database=mylookups;"))
            {
                connection.Open();
                using (SqlCommand command = new SqlCommand(query, connection))
                {
                    reader = command.ExecuteReader(CommandBehavior.CloseConnection);
                    while (reader.Read())
                    {
                        context.Response.Write(reader["CityName"].ToString() + Environment.NewLine);
                    }
                    reader.Close();
                }
                connection.Close();
            }
        }

Note: I am not promising the above code is optimised. [:)]

And the ASPX Page you need to add reference to following JS Files and Style.

    <script type="text/javascript" language="javascript" src="jquery.js"></script>
    <script src="jquery.autocomplete.js" type="text/javascript"></script>
    <style type="text/css">
        .ac_odd {background:#dddddd;}
        .ac_results { padding: 0px; border: 1px solid black; background-color: white; overflow: hidden; z-index: 99999; }
        .ac_results ul { width: 100%; list-style-position: outside; list-style: none; padding: 0; margin: 0; }
        .ac_results li { margin: 0px; padding: 2px 5px; cursor: default; display: block; font: menu; font-size:12px; line-height: 16px; overflow: hidden; }
        .ac_loading { background:url(loading.jpg) right no-repeat; }
        .ac_over { background-color: #0A246A; color: white; }
    </style>

We have completed almost everything, then compile the project, drag the Custom control from toolbox to ASPX page, where you refering the JS Files and CSS. The ASHX File name should be the name of the control. Like if the control’s name is AutoSuggestCity, the ASHX Filename should be AutoSuggestCity.ashx. Please modify the control code if you want to change it.

After running you will get a Textbox, type something there, you will get the suggestions. Here is the one I got.

autosuggest

You can download JQuery from JQuery website. – www.jquery.com. And autosuggest plugin from AutoSuggest plugin page.

Preview of Microsoft Ajax 4.0 available for download

March 31st, 2009 Anuraj P No comments

The Microsoft Ajax team made the fourth preview of the 4.0 version available on CodePlex. The AJAX functionality in ASP.NET 4.0 Preview 4 enables new client data scenarios for page and component developers that allow JSON data from the server to be rendered as HTML in a highly manageable and efficient way.

You can get more information about ASP.Net AJAX 4.0 Preview from codeplex.

Categories: .Net 3.0 / 3.5, ASP.Net, Javascript Tags:

Control focus with Postback

October 8th, 2008 Anuraj P 2 comments

While working with ASP.Net update panel control, the Tab focus will make some problems. Here is a simple solution for that, you can use the Script Manager class to set focus to a specific control.

ScriptManager1.SetFocus(Control);	//You can either use the control or the clientID of the control.

And if you are using Master Pages and placing the script manager in the master page, you can use the following code to get the script manager class.

ScriptManager ScriptManager1 = ScriptManager.GetCurrent(this.Page)	//Getting the script manager class of the current page.
Categories: .Net, .Net 3.0 / 3.5, ASP.Net, Javascript Tags: