Showing posts with label JavaScript. Show all posts
Showing posts with label JavaScript. Show all posts
Saturday, May 5, 2018

A minimal web application structure with technologies like node.js, typescript, express

Recently, I have been working the lot with Node.js and TypeScript. And I absolutely love TypeScript due to its features. I was actually looking for a boilerplate code to start which should be very easy to understand. But there was no code there. So I decided to create a minimum web application structure. I have used it in some project and I was quite happy with it.

So I thought why should I make it open source so that people can also get benefited by this. So here I am presenting A minimal Web Application Structure with technologies like Node.js, TypeScript, and Express.

You can find the complete source code on Github at following location - https://github.com/dotnetjalps/minimum-nodejs-typescript-express

How to Run this Project:

To run this project you need to first install all the NPM packages via the following command.
npm install 
Then you can run this project with the following command.
npm start

Directory Structure Of Project:

  • App.ts – Typescript file for creating express application class and where we have initialized the application.
  • routes.ts - Typescript files for creating all the routes under Init() Method.
  • package.json - Contains all the packages and dev dependencies required for this application. You can add more as your requirement.
  • tsconfig.json - Where all the typescript configuration is there and we converting typescript into ES5.
  • Controller Folder - Contains all the classes for the controller of the express application
  • tsconfig.josn  - Contains all the rules for TypeScript linting.
I’m looking for constructive feedback on this and I’m hoping that I will get it.
Share:
Sunday, July 9, 2017

Video: How to debug Node.js Application with Visual Studio Code

Visual Studio code is a Great Editor and I like it very much. It support’s a lot of cool features our of box. Node.js Application debugging is one of them. It provides great debugging with node.js just like Visual Studio. I have created a small video demonstrating the same. Please have a look.


Share:
Saturday, October 3, 2015

Routing with UI-Router and Angular.js

In Today's world, Angular.js is one of best JavaScript framework available to create Single page applications. It's provides some great features and with the help of this features we can built great interactive apps. In any single page application routing is very important as in most of the time single page application will not have full post backs. So routing will be very important to give feel like normal page application and sometimes proper routing will increase search engine ranking also.

So in this blog post we are going to learn how we can create routes in Angular.js application with help of UI-Router.

What is UI-Router:


UI-Router is a routing frame work created Angular.js team and its not a part of Angular.js But it built on top of Angular.js. You can say it's a 3rd-Party module and is very powerful. It support most of things that we can do with ng-route and also do many other stuff that is not possible with ng-route.
You can find more information about UI-Router at following link.

https://github.com/angular-ui/ui-router
http://angular-ui.github.io/ui-router/site/#/api/ui.router

Here are few features that is provided by UI-Router.
  1. UI-Router allows nested views and multiple views
  2. It allows you to strong type linking between state based on state names.
  3. State allows you to map and access different information about different states and you can easily pass information between states via $Stateparams parameter.
  4. With states approach your views are not tied to the URL and it is tied to states. Which can be very useful in large applications as you can change UI part without changing URLs.
  5. You can also change Partial UI of application which is not possible with ng-route.

So what are we waiting for let's create a sample application with UI-Router and Angular.js.

Sample application with UI-Router:


I'm going to use visual studio for creating this sample application. So that we can use IIS local express to host this application. I'm going to create asp.net web application.

angular-Ui-route-demo-project

We are going to use empty asp.net web forms application as we are not going to use asp.net code here it's a simple HTML page application to demonstrate the power of UI-Router.

empty-web-application-angular-ui-route-demo
We are going to create sample application with 3 pages.
  1. Home
  2. About Us
  3. Contact Us

So for that we need three html pages which will acts as partial views just like ASP.NET MVC partial views or user control in ASP.NET Web Forms.
I'm going to create a very basic HTML pages with following code.
home.html page code:
<h1>Home</h1>
About Us HTML page code:
<h1>About us page</h1>
Contact Us HTML page code:
<h1>contact us </h1>
And now we are going create index.html and following is a code for that.
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="utf-8" />
    <title>Angular UI Router Demo</title>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.6/angular.min.js" type="text/javascript"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/angular-ui-router/0.2.15/angular-ui-router.min.js"></script>
    <script src="app.js"></script>
</head>
<body ng-app="routerDemoApp">
    <ul >
        <li><a ui-sref="home">Home</a></li>
        <li><a ui-sref="aboutus">About us</a></li>
        <li><a ui-sref="contactus">Contact us</a></li>
    </ul>
<div>
    Angualr UI Router Demo
</div>
<div>
    <div ui-view></div>
</div>
</body>
</html>
If you see above code you can see I have added angular.js and angular-ui-router-min.js JavaScript files from the cloud flare CDN and then I have created a ng-app "routerDemoApp" with body tag of html page. I have used UL and Li ta and UI-Sref to create link for our routes. Here also notice ui-view tag in one of div where html pages will be rendered in this div.

So now basic infrastructure is ready now its time to create JavaScript code for our application. So lets create app.js file and write code like following.
// JavaScript source code
var routerDemoApp = angular.module('routerDemoApp', ['ui.router']);

routerDemoApp.config(function ($stateProvider, $urlRouterProvider) {

    $urlRouterProvider.otherwise("/home");

    $stateProvider
        .state('home', {
            url: '/home',
            templateUrl: 'home.html'
        })
        .state('aboutus', {
            url: '/aboutus',
            templateUrl: 'aboutus.html'
        })
        .state('contactus', {
            url: '/contactus',
            templateUrl: 'contactus.html'
        });

});
So if you see above code carefully, Here I have created a angular app module called routerDemoApp and I have injected dependency of UI-Router. Then in config function we have created different states for Home, About Us and Contact Us. You can see I have passed two parameter url and template url for each state with respective html pages. Also I have written otherwise function which will return home state by default.

Now let's run this application in browser.

demo-application-browser-ui-router-angularjs

So by default Home page is loaded as you can see and in URL also you have /home now when you click on About us it will load about us page like following.

about-us-demo-page-in-browser-ui-angular-js

So it's very easy to create routing with Angular UI-Router in future post we will see how we can use nested view and multiple view.
You can find complete source code of this application at github on- https://github.com/dotnetjalps/AngularUIRouter
Hope you like it. Stay tuned for more!.
Share:
Friday, September 18, 2015

Why it's the right time to learn TypeScript.

In Today's world, If you are an web developer and you don't know JavaScript then you will feel left behind. It's never been a good time to be a JavaScript developer than now. With the rise of Node.js  JavaScript is everywhere now. But as you know when Size and Complexity of your JavaScript is Increased it's very difficult to maintain and mange. That's where TypeScript comes into picture. It is a life saver some times. So in this blog post we will see Why It's the right time to learn TypeScript.

What is TypeScript?


TypeScript is a free and open sourced programming language developed and Maintained by Microsoft. It works as a super set of JavaScript. As we all know that JavaScript is very liberal language by nature. So that we tend to make more mistakes and we does not know all the errors at run time. TypeScript is a strict super set of JavaScript so that you can get most of errors at compile time only.  As per official website of TypeScript it's a language that lets you write JavaScript in the way you really want to. TypeScript offers all the features that you need for Object oriented programming. You can find more information about TypeScript on it's official web site on below link.

http://www.typescriptlang.org/

ECMAScript and TypeScript:


ECMAScript is the specification standard of the JavaScript. So right not standard stable version if ECMAScript 5 and some of the browsers support ECMAScript 6. ECMAScript 6 features are being adopted by latest browsers.While TypeScript follows most of syntax of ECMAScript 6 so that you don't have a feel of the learning new language. As per official road map of Typescript 1.6 comes with ES6 Generator so you can convert your script code into ECMAScript6. Your can find more about that on following blog post.

http://blogs.msdn.com/b/typescript/archive/2015/09/16/announcing-typescript-1-6.aspx

TypeScript is everywhere:


As we know TypeScript is a fully Object Oriented language, It's provide great productivity boosts than JavaScript and it's super set of JavaScript so it will be compiled into JavaScript itself. So because of this lots of great framework started using TypeScript like following.
  1. Angular JS
  2. Iconic Framework for creating frond end mobile App
  3. Native Script from Telerik is also completely written TypeScript itself.
Take a example of AngularJs, It is one of the most popular JavaScript Framework on earth. With Angular.js 2.0 it will be fully written with TypeScript.

Tooling:


Most of Web Development editor whether it's paid or free are having TypeScript tooling.  Most popular editors like Visual Studio, Visual Studio Code, WebStorm, Atom, Sublime text and Eclipse are having great tooling for TypeScript.

Why to use TypeScript:


Followings are reason why we should use TypeScript instead of JavaScript.
  1. Fully Object Oriented support with classes and interfaces. So It's a great productivity boost for any developer and easily maintainable and understandable.
  2. It's provide most of the errors compile time while JavaScript is more liberal than this. So less run time error means less bugs for your application.
  3. Refactoring is very easy in TypeScript compare to JavaScript.
So it's never been late. It is the right time to learn TypeScript. Hope you like it. Stay tuned for more!.
Share:
Thursday, April 10, 2014

How to convert C# object into JSON string with JSON.NET

Before some time I have written a blog post – Converting a C# object into JSON string in that post one of reader Thomas Levesque commented that mostly people are using JSON.NET a popular high performance JSON for creating for .NET Created by James Newton- King. I agree with him if we are using .NET Framework 4.0 or higher version for earlier version still JavaScriptSerializer is good. So in this post we are going to learn How we can convert C# object into JSON string with JSON.NET framework.

Share:
Saturday, April 5, 2014

Converting a C# Object into JSON string

Some people might think why I am writing so much about basics but the things but in reality  I got lot of questions through email and other communities about very basic things. So I thought instead of replying them into single thread. It is a good idea to write blog post about it and as a result I am writing this blog post.

In this post we are going to learn how we can convert a object into JSON string It is very simple. Let’s first see how we can convert C# Object into JSON string.

Converting a C# object into JSON string:


So to demo this, I have created a employee class like following.

public class Employee
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

Now let’s create object of this class and assign some value like following.

Employee employee=new Employee
                    {FirstName = "Jalpesh",
                    LastName = "Vadgama"};

For this demo we are using console application so we have to add System.Web and System.Web.Extensions  reference to access the JavaScript Searilizer class through which we are going to convert this object into JSON string. We are going to add reference like following.

add-reference-serializtion-web-convert-chsarp-object-into-json

Now with JavaScript Searilizer class which belongs to System.Web.Script.Serialization namespace we can easily convert C# object into JSON string. Following is a code for that.

var javaScriptSerializer = new 
    System.Web.Script.Serialization.JavaScriptSerializer();
string jsonString = javaScriptSerializer.Serialize(employee);
Console.WriteLine(jsonString);

Now when run this console application. Following is a output as expected.

convert-c#-object-to-json-string-javascriptsearializer

Here its serialize object into JSON string. Same you can desterilize the JSON string into C# object with Deserialize function.

That’s it. It’s very easy. Hope you like it. Stay tuned for more..
Share:

ASP.NET Checkbox button Attributes in JavaScript.

This is a follow up post I have just written before some time- Getting tooltip of ASP.NET Radio button in java script. In that post I have explained that to render all properties properly in ASP.NET renders checkbox and radio button surrounded by Span tag. So one of the friend message me on facebook how we can add JavaScript attribute on ASP.NET Controls like checkbox or radio button. So I thought it will be good idea to write a quick blog post about it.

Adding JavaScript attribute to ASP.NET Checkbox and Radio button:


So Let’s see how we can write JavaScript attribute from server side with ASP.NET Checkbox and same will be applied to ASP.NET Radio button also. Following is a HTML code for ASP.NET checkbox.

<asp:CheckBox runat="server" ID="myCheckBox" 
Text="Yes" ToolTip="Yes"/>

Now I want to write a onBlur event for JavaScript so I have written a following function in JavaScript.

function onBlur() {
alert('Onblur Fired');
}

Normally we write JavaScript attribute from server side like below in page load event.

protected void Page_Load(object sender, EventArgs e)
{
myCheckBox.Attributes.Add("onblur", "onBlur();");
}

Now when you run this code in browser and see that in browser with View Source it will apply onblur event to span tag.

javascript-css-attribute-of-asp-net-checkbox-control

So it will not fire ‘onblur’ event of checkbox as this event is right now applied to span tag. So what should we do? Here is the fix. ASP.NET Checkbox and Radio Button provides InputAttributes attribute collection. So you can directly assign attributes to checkbox like below.

protected void Page_Load(object sender, EventArgs e)
{
myCheckBox.InputAttributes.Add("onblur", "onBlur();");
}

That's it. If you see in view source now it will assign JavaScript attribute in correct way and now it will fire event also.

javascript-css-attribute-of-asp-net-checkbox-control-correct-way

Note: You can add CSS Attribute in the same way as you do with JavaScript attribute.

Hope you like it. Stay tuned for more..
Share:

Getting tooltip of ASP.NET Radio button in java script.

This post in regards to a question that I have answered on stack overflow. Getting Tool tip of the Radio button in JavaScript. Where user asks why he is not able to get tooltip with document.GetElementById and Client Id of ASP.NET Radio button control like following.

document.getElementById('<%= rbSelectedIds.ClientID %>').title

While answering this question, I have found that there are lots of people not aware about this. So I thought it is a good idea to write a blog post about it.

By default ASP.NET Radio button and check box controls rendered under span when you have attribute like tooltip. Because System.Web.UI.WebControls namespace may render differently in  different browsers and to achieve same functionality in all the browsers they are rendering with span.

There is a complete discussion there one in one of the StackOverFlow.com

Why does ASP.Net RadioButton and CheckBox render inside a Span?

Example : Getting ASP.NET Radio button tooltip in JavaScript:


So let’s take same example as mentioned in that question. Following is my HTML Code. Below is radio button HTML code.
<div>
       <ASP:RadioButton runat="server" ID="myRadioButton" 
            Text="Yes" ToolTip="Yes"/>
</div>

Now when you run this in browser it will render this radio button is render with surrounded by span like follow.

how-to-get-tooptip-of-radio-button-in-java-script

You can see that title attribute is given to span tag instead of radio button. Now let’s create a ASP.NET button to get tooltip of that radio button like below.

<asp:Button runat="server" Text="Get Tooltip" 
        OnClientClick="getToopTip();"/>

So we are done with button now it’s time to write a JavaScript. Following is a code for JavaScript.
function getToolTip() {
    var sParentElement = document.getElementById("<%=myRadioButton.ClientID%>").parentElement;
    var tooltip = sParentElement.title;
    alert(tooltip);
}

So we are done with code. Now it’s time to run this code in browser. And when you click on button it will show alert with tool tip of radio button.

getting-tooltip-in-javascript-asp-net-radio-button-and-checkbox

That’s it. Hope you like it. Stay tuned for more.
Share:
Sunday, August 11, 2013

Knockout.js Introduction

We all know about jQuery It makes Java Script developers life very easy. But in Some scenarios jQuery does not help. For example there is no way where UI and data communicates with each other without writing complex code.  Here JavaScript library knockout comes very handy.  Knockout.js implement Model-View-View-Model pattern to JavaScript. 

Knockout js basics

Key Features:


Declarative bindings: It provides an easy way to bind your data with UI declaratively. You can use knockout observables with some html attributes. Whenever data changes it will automatically updates UI.

Dependency Tracking:  With this features it will automatically updates the UI whenever data changes.

Extensibility: It can be easily extensible with new declarative bindings and it can recused every where.

Templating: Knockout.js has a built in template engine which you can use with declarative bindings. It also supports third party template engines like jQuery templates and UnderScore.

Share:
Sunday, July 14, 2013

How to to select all p in div with jQuery

Recently I was discussing something with friend about jQuery and question comes from friend that how we can select the all p in Div with jQuery. With jQuery selector its very easy to select all p in div tag. But from this conversation I came to know that lots of people does not know about it. So I thought it will be great idea to write a blog post about it.

As you know with jQuery selectors we can have single selection but lots of people does not know that jQuery is also provide multiple selection also. Let’s take an example. You have following html structure.
Share:
Wednesday, June 26, 2013

Extending jQuery with jQuery.Extend

We all know that jQuery is a great JavaScript framework. It’s provide lots of functionalities and most used framework in programming world. But sometimes we need a functionality that does not provided by jQuery by default. At that time we need to extend jQuery. We can extend jQuery with jQuery.Extend  Method. You can get complete information from the following link.

http://api.jquery.com/jQuery.extend/

It merges the contents of two or more objects together into the first object.
Share:
Saturday, February 2, 2013

How to hide title bar in jQuery UI modal dialog?

jQuery UI is a great open source set of user controls and it’s very easy to use. Recently one of my friend asked question that how we can hide title bar in jQuery UI Dialog? so this post is a reply to him. Let’s create a simple html and use jQuery Ui modal dialog. Following is a code for that.

Here in the above code you can see I have create a hello world pop up with asp.net jQuery CDN.
<html>
<head>
    <title>Hello World  Popup</title>
    <link type="text/css" href="http://ajax.aspnetcdn.com/ajax/jquery.ui/1.10.0/themes/smoothness/jquery-ui.css"
        rel="stylesheet" />
    <script language="javascript" src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.9.0.min.js"></script>
    <script language="javascript" src="http://ajax.aspnetcdn.com/ajax/jquery.ui/1.10.0/jquery-ui.min.js"></script>
    <script type="text/javascript">
        function Show() {

            $("#dialog:ui-dialog").dialog("destroy");

            $("#dialog-modal").dialog({
                height: 300,
                width: 200,
                modal: true
            });
        }
    </script>
</head>
<body>
    <div id="dialog-modal" title="Hello Word" style="display: none">
        Hello World Juqry UI popup
    </div>
    <input type="button" onclick="javascript: Show()" value="click me" />

</body>

</html>


Share:
Friday, December 23, 2011

Async file upload with jquery and ASP.NET

Recently before some I was in search of good asynchronous file upload control which can upload file without post back and I have don’t have to write much custom logic about this. So after searching it on internet I have found lots of options but some of the options were not working with ASP.NET and some of work options are not possible regarding context to my application just like AsyncFileUpload from Ajax toolkit.As in my application we were having old version of Ajax toolkit and if we change it than other controls stopped working. So after doing further search on internet I have found a great Juqery plugin which can easily be integrated with my application and I don’t have to write much coding to do same.

So I have download that plug from the following link. This plug in created by yvind Saltvik

After downloading the plugin and going through it documentation I have found that I need to write a page or generic handler which can directly upload the file on the server. So I have decided to write a generic handler for that as generic handler is best suited with this kind of situation and we don’t have to bother about response generated by it.

So let’s create example and In this example I will show how we can create async file upload without writing so much code with the help of this plugin. So I have create project called JuqeryFileUpload and our need for this example to create a generic handler. So let’s create a generic handler. You can create a new generic handler via right project-> Add –>New item->Generic handler just like following.

GenericHandlerForJqueryFileUploadwithASPNET

I have created generic handler called AjaxFileuploader and following is simple code for that.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.IO;

namespace JuqeryFileUPload
{
   /// <summary>
   /// Summary description for AjaxFileUploader
   /// </summary>
   public class AjaxFileUploader : IHttpHandler
   {

       public void ProcessRequest(HttpContext context)
       {
           if (context.Request.Files.Count > 0)
           {
               string path = context.Server.MapPath("~/Temp");
               if (!Directory.Exists(path))
                   Directory.CreateDirectory(path);

               var file = context.Request.Files[0];

               string fileName;

               if (HttpContext.Current.Request.Browser.Browser.ToUpper() == "IE")
               {
                   string[] files = file.FileName.Split(new char[] { '\\' });
                   fileName = files[files.Length - 1];
               }
               else
               {
                   fileName = file.FileName;
               }
               string strFileName=fileName ;
               fileName = Path.Combine(path, fileName);
               file.SaveAs(fileName);

              
               string msg = "{";
               msg += string.Format("error:'{0}',\n", string.Empty);
               msg += string.Format("msg:'{0}'\n", strFileName);
               msg += "}";
               context.Response.Write(msg); 

              
           }
       }

       public bool IsReusable
       {
           get
           {
               return true;
           }
       }
   }
}


As you can see in above code.I have written a simple code to upload a file from received from file upload plugin into the temp directory on the server and if this directory is not there on the server then it will also get created by the this generic handler.At the end of the of execution I am returning the simple response which is required by plugin itself. Here in message part I am passing the name of file uploaded and in error message you can pass error if anything occurred for the time being I have not used right now.

As like all jQuery plugin this plugin also does need jQuery file and there is another .js file given for plugin called ajaxfileupload.js. So I have created a test.aspx to test jQuery file and written following html for that .

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

<!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="jquery.js"></script>
   <script type="text/javascript" src="ajaxfileupload.js"></script>
</head>
<body>
   <form id="form1" runat="server">
   <div>
         <input id="fileToUpload" type="file" size="45" name="fileToUpload" class="input">
         <button id="buttonUpload" onclick="return ajaxFileUpload();">Upload</button>
         <img id="loading" src="loading.gif" style="display:none;">
   </div>
   </form>
</body>
</html>

As you can see in above code there its very simple. I have included the jQuery and ajafileupload.js given by the file upload give and there are three elements that I have used one if plain file input control you can also use the asp.net file upload control and but here I don’t need it so I have user file upload control. There is button there called which is calling a JavaScript function called “ajaxFileUpload” and here we will write a code upload that. There is an image called loading which just an animated gif which will display during the async call of generic handler. Following is code ajaxFileUpload function.

<script type="text/javascript">
   function ajaxFileUpload() {
       $("#loading")
   .ajaxStart(function () {
       $(this).show();
   })
   .ajaxComplete(function () {
       $(this).hide();
   });

   $.ajaxFileUpload
   (
       {
           url: 'AjaxFileUploader.ashx',
           secureuri: false,
           fileElementId: 'fileToUpload',
           dataType: 'json',
           data: { name: 'logan', id: 'id' },
           success: function (data, status) {
               if (typeof (data.error) != 'undefined') {
                   if (data.error != '') {
                       alert(data.error);
                   } else {
                       alert(data.msg);
                   }
               }
           },
           error: function (data, status, e) {
               alert(e);
           }
       }
   )

       return false;

   }
</script>

As you can see in above code I have putted our generic handler url which will upload the file on server as url parameter. There is also parameter called secureURI is required to be true if you are uploading file through the secure channel and as a third parameter we have to pass a file upload control id which I have already passed and in fourth parameter we have to passed busy indicator which I have also passed. Once we passed all the parameter then it will call a method for plugin and will return response in terms of message and error. So There is two handler function written for that.

That’s it. Our async file upload is ready. As you can easily integrate it and also it working fine in all the browser. Hope you like it. Stay tuned for more. Till then happy programming..
Share:
Thursday, September 8, 2011

Jquery and ASP.NET- Set and Get Value of Server control

Yesterday one of my reader asked me one question that How can I set or get values from Jquery of server side element for example. So I decided to write blog post for this. This blog post is for all this people who are learning Jquery and don’t know how to set or get value for a server like ASP.NET Textbox. I know most of people know about it as Jquery is very popular browser JavaScript framework. I believe jquery as framework because it’s a single file which has lots of functionality.

For this I am going to take one simple example asp.net page which contain two textboxes txtName and txtCopyName and button called copyname. On click of that button it will get the value from txtName textbox and set value of another box. So following is HTML for this.

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

<!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>
       
</head>
<body>
    <form id="form1" runat="server">
    <div>
            <asp:TextBox ID="txtName" runat="server" />
            <Br />
            <asp:TextBox ID="txtCopyName" runat="server"/>
            <Br />
            <asp:button ID="btnCopyName" runat="server" Text="Copy"  OnClientClick="javascript:CopyName();return false;"/>
    </div>
    </form>
</body>
</html>

As you can see in following code there are two textbox and one button which will call JavaScript function called to CopyName to copy text from one textbox from another textbox.Now we are going to use the Jquery for this. So first we need to include Jquery script file to accomplish the task. So I am going link that jquery.js file in my header section like following.

<head >
    <title></title>
    <script src="http://ajax.aspnetcdn.com/ajax/jquery/jquery-1.6.2.js"></script>  
</head>

Here I have used the ASP.NET Jquery CDN. If you want know more about Jquery CDN you can visit this link.

http://www.asp.net/ajaxlibrary/cdn.ashx

Now it’s time to write query code. Here I have used val function to set and get value for the element. Following is the code for CopyName function.

function CopyName() {
    var name = $("#<%=txtName.ClientID%>").val(); //get value
    $("#<%=txtCopyName.ClientID%>").val(name); //set value
    return false;
}

Here I have used val function of jquery to set and get value. As you can see in the above code, In first statement I have get value in name variable and in another statement it was set to txtCopy textbox. Some people might argue why you have used that ClientID but it’s a good practice to have that because when you use multiple user controls your id and client id will be different. From this I have came to know that there are lots of people still there who does not basic Jquery things so in future I am going to post more post on jquery basics.That’s it. Hope you like it.Stay tuned for more.. Happy programming and Namaste!!

Shout itkick it on DotNetKicks.com
Share:
Saturday, January 22, 2011

JQuery UI 1.8.9 new version launch today

JQuery UI contains great controls and it’s very useful when developing sites. Today a new version of Jquery UI is launched.

You can find more details about that from following link.

http://blog.jqueryui.com/2011/01/jquery-ui-1-8-9/

It’s contains Bug fixes for Datepicker, Tabs and other things and also contains some localization improvements on the date picker.

Technorati Tags: ,
Shout it
Share:
Sunday, January 9, 2011

Converting a generic list into JSON string and then handling it in java script

We all know that JSON (JavaScript Object Notation) is very useful in case of manipulating string on client side with java script and its performance is very good over browsers so let’s create a simple example where convert a Generic List then we will convert this list into JSON string and then we will call this web service from java script and will handle in java script.

To do this we need a info class(Type) and for that class we are going to create generic list. Here is code for that I have created simple class with two properties UserId and UserName

public class UserInfo
{
public int UserId { get; set; }
public string UserName { get; set; }
}
Now Let’s create a web service and web method will create a class and then we will convert this with in JSON string with JavaScriptSerializer class. Here is web service class.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;

namespace Experiment.WebService
{
/// <summary>
/// Summary description for WsApplicationUser
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
[System.Web.Script.Services.ScriptService]
public class WsApplicationUser : System.Web.Services.WebService
{

[WebMethod]
public string GetUserList()
{
List<UserInfo> userList = new List<UserInfo>();
for (int i = 1; i <= 5; i++)
{
UserInfo userInfo = new UserInfo();
userInfo.UserId = i;
userInfo.UserName = string.Format("{0}{1}", "J", i.ToString());
userList.Add(userInfo);

}
System.Web.Script.Serialization.JavaScriptSerializer jSearializer = new System.Web.Script.Serialization.JavaScriptSerializer();
return jSearializer.Serialize(userList);
}
}
}

Note: Here you must have this attribute here in web service class ‘[System.Web.Script.Services.ScriptService]’ as this attribute will enable web service to call from client side.Now we have created a web service class let’s create a java script function ‘GetUserList’ which will call web service from JavaScript like following
function GetUserList() {
Experiment.WebService.WsApplicationUser.GetUserList(ReuqestCompleteCallback, RequestFailedCallback);

}
After as you can see we have inserted two call back function ReuqestCompleteCallback and RequestFailedCallback which handle errors and result from web service. ReuqestCompleteCallback will handle result of web service and if and error comes then RequestFailedCallback will print the error. Following is code for both function.
function ReuqestCompleteCallback(result) {

result = eval(result);
var divResult = document.getElementById("divUserList");
CreateUserListTable(result);

}
function RequestFailedCallback(error) {

var stackTrace = error.get_stackTrace();
var message = error.get_message();
var statusCode = error.get_statusCode();
var exceptionType = error.get_exceptionType();
var timedout = error.get_timedOut();

// Display the error.
var divResult = document.getElementById("divUserList");
divResult.innerHTML = "Stack Trace: " + stackTrace + "<br/>" +
"Service Error: " + message + "<br/>" +
"Status Code: " + statusCode + "<br/>" +
"Exception Type: " + exceptionType + "<br/>" +
"Timedout: " + timedout;
}

Here in above there is a function called you can see that we have use ‘eval’ function which parse string in enumerable form. Then we are calling a function call ‘CreateUserListTable’ which will create a table string and paste string in the a div. Here is code for that function.
function CreateUserListTable(userList) {

var tablestring = '<table ><tr><td>UsreID</td><td>UserName</td></tr>';

for (var i = 0, len = userList.length; i < len; ++i)
{
tablestring=tablestring + "<tr>";
tablestring=tablestring + "<td>" + userList[i].UserId + "</td>";
tablestring=tablestring + "<td>" + userList[i].UserName + "</td>";
tablestring=tablestring + "</tr>";
}
tablestring = tablestring + "</table>";
var divResult = document.getElementById("divUserList");
divResult.innerHTML = tablestring;
}
Now let’s create div which will have all html that is generated from this function. Here is code of my web page. We also need to add a script reference to enable web service from client side. Here is all HTML code we have.
<form id="form1" runat="server">
<asp:ScriptManager ID="myScirptManger" runat="Server">
<Services>
<asp:ServiceReference Path="~/WebService/WsApplicationUser.asmx" />
</Services>
</asp:ScriptManager>

<div id="divUserList">
</div>
</form>
Now as we have not defined where we are going to call ‘GetUserList’ function so let’s call this function on windows onload event of javascript like following.
window.onload=GetUserList();
That’s it. Now let’s run it on browser to see whether it’s work or not and here is the output in browser as expected.

JSON string output in browser

That’s it. This was very basic example but you can crate your own JavaScript enabled grid from this and you can see possibilities are unlimited here. Stay tuned for more.. Happy programming..
Shout it
Share:
Sunday, April 4, 2010

How to call a web service from JavaScript with asp.net Ajax

Calling a web service from JavaScript was easy task earlier you need to create a proxy class for JavaScript and then you need to write lots of java script but with Microsoft ASP.NET Ajax you can call web services from JavaScript very easily with some line of JavaScript and even better you can also handle the errors if web service failed to return result. Let’s create a simple hello world web service which will print Hello world string and then we will call that web service into JavaScript. Following is a code for web service.

namespace DotNetJapsSocial
{
/// <summary>
/// Summary description for HelloWorld
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
[System.Web.Script.Services.ScriptService]
public class HelloWorld : System.Web.Services.WebService
{
[WebMethod]
public string PrintHelloWolrdMessage()
{
return "Hello World";
}
}
}
Here we have created a web method called PrintHelloWorldMessage which will return a string “Hello world”. Please see the [System.Web.Script.Services.ScriptService] attribute of HelloWorld Service class which will enable web service to invoked by any ECMA Script and here we are using JavaScript to call web service.

Now lets create three functions in JavaScript CallWebService,ReuqestCompleteCallback and RequestFailedCallback. Following is the code for that.

<script type="text/javascript">
function CallWebService() {
DotNetJapsSocial.HelloWorld.PrintHelloWolrdMessage(ReuqestCompleteCallback, RequestFailedCallback);
}
function ReuqestCompleteCallback(result)
{
// Display the result.
var divResult = document.getElementById("divMessage");
divResult.innerHTML = result;
}
function RequestFailedCallback(error) {
var stackTrace = error.get_stackTrace();
var message = error.get_message();
var statusCode = error.get_statusCode();
var exceptionType = error.get_exceptionType();
var timedout = error.get_timedOut();

// Display the error. 
var divResult = document.getElementById("Results");
divResult.innerHTML = "Stack Trace: " + stackTrace + "<br/>" +
"Service Error: " + message + "<br/>" +
"Status Code: " + statusCode + "<br/>" +
"Exception Type: " + exceptionType + "<br/>" +
"Timedout: " + timedout;
}


</script>
The CallWebService function will call the web service method. Here we have to pass web service method will complete path like DotNetJapsSocial.HelloWorld.PrintHelloWolrdMessage. The another function ReuqestCompleteCallback will return result call back of web service as parameter in our case it will be a string. Another function RequestFailedCallback is failed callback of web service. If web service returns some error then it will goes to that function. So here you can handle errors.

Now Let’s Create div which will print message and a button to call web service like following.
<div>
<input type="button" value="Call Web Service"
onclick="CallWebService();"/>
</div>
<div id="divMessage">
</div>
so when you click button then it will crate output like following.

WebServicePage call from JavaScript,Javascript

Hope this will help you..Happy coding..

Shout it
kick it on DotNetKicks.com
Share:
Thursday, July 23, 2009

Javascript is not working with update panel- Microsoft Ajax

As an asp.net developer we all must have to use update panel for the ajaxifying our application in today’s ajax world. No one likes postaback now. But when we add the some content with the java script under update panel then some times it’s stop working because of the update panel server side behavior. So what we should do? … Here is the trick. Normally we code java script in the asp.net page like following…

string alertScript = "javascript:alert('Alter From asp.net page')";
ClientScript.RegisterStartupScript(typeof(Page),"alertscript", alertScript);
Instead of this you should use.

string alertScript = "javascript: alert('This is aler from asp.net page')";
ScriptManager.RegisterStartupScript(this, this.GetType(), "alertScript",
                                alertScript,true);
This will work. Happy coding..

Technorati Tags: ,,,,
Share:
Thursday, May 28, 2009

JavaScript Events

Following are some of the events that are provided by JavaScript

OnChange:

Occurs when user changes values in an input control. In text controls this event fire after user changes focus to other controls

OnClick:

This event occurs when a user clicks on the button control.This event is also occurs when a form is submitted to server.

OnMouseOver:

This events occur when user moves the mouse pointer over a control.

OnMouseOut:

Occurs when the user move mouse pointer over a control.

OnKeyUp:

Occurs when user release a pressed key.

OnSelect:

Occurs when the User selects a portion of a text in a user control.

OnFocus:

Occurs when a control receive focus.

OnBlur:

Occurs when a focus leaves controls.

OnAbort:

Occurs when user cancels image download.

OnError:

Occurs when an image can’t be downloaded

Onload:

Occurs when a new page finishes downloading.

OnUnLoad:

Occurs when a page is unloaded(This typically occurs when a new url has been entered_

Share:

Support this blog-Buy me a coffee

Buy me a coffeeBuy me a coffee
Search This Blog
Subscribe to my blog

  

My Mvp Profile
Follow us on facebook
Blog Archive
Total Pageviews