May 24, 2011

jQuery VS Javascript

It's all about performance and development speed.

-----------
jQuery :
-------------


  1. jQuery is library or you can say that its built on javascript
  2. Jquery is need to be access through jquery patch latest patch is 1.5
  3. Another advantage of jquery is that its less your code rather than using javascript.
  4. In complex situation Jquery will be more helpfull due to less code written and easily manageable
-------------------
JavaScript : 
-------------------



  1. Javascript is client language for which you dont need any requirement.
  2. It is incredibly useful and overused, but that if you really need it, a framework is the way to go.
  3. Javascript is the source, the actual scripts that browser responds to.

Web Site VS Web Application

There is very big difference between Web Site and Web Application, some points are given below, but there is no difference in speed or performance between both of them.............

Web Site

  1. Web Site is just one folder which contains the files and resources
  2. Web Site is open using browser from Visual Studio
Web Application

  1. Web Application creates one solution file which may contain multiple projects in it
  2. If you are working on 3-tier or n-tier application then this type is good
  3. It is easy to maintain, its movable and it contain file in DLL format
  4. All files are compiled in .dll file on time of deployment

Table Like Structure of Div

There is very simple css code to make div which behave like a table but in reality its not a table. It is the composition of CSS on Div to make Div as Table

CODE

<div id="divContainer" style="width:600px; height: 100px">

        <div style="width:50%;height: 100%; float:left;">

                <div style="width:100%; height:25%; display:block; border: 1px solid black; border-bottom:none"></div>

                <div style="width:100%; height:25%; display:block; border: 1px solid black; border-bottom:none"></div>

                <div style="width:100%; height:25%; display:block; border: 1px solid black; border-bottom:none"></div>

                <div style="width:100%; height:25%; display:block; border: 1px solid black"></div>

        </div>

        <div  style="width:50%; height: 100%; float:left;">

                <div id="divWithPadding" style="width:100%; height:50%; display:block; border: 1px solid black; border-bottom:none; border-left:none; padding-top:1px"></div>

                <div style="width:100%; height:25%; display:block; border: 1px solid black; border-bottom:none; border-left:none"></div>

                <div style="width:100%; height:25%; display:block; border: 1px solid black; border-left:none"></div>

        </div>

</div>


Fixed the size of gridview

How can i fixed the size of grid with respect to their hieght and width. Problem occurs on address column when long address placed in it it increase its width and sperad its width from page. Thats why i wants that if address is will increase the width of gridview rather moving forward its terminated line and then placed reamining words in next lines. I fixed the width of gridview and reamins free in auto mode the height of gridview.

There are several ways u can solve that issue by just taking an item template and put your address bounded column in that item template

CODE

<asp:TemplateField HeaderText="Title" SortExpression="Title" ItemStyle-Width=200>
<ItemStyle HorizontalAlign="Left" VerticalAlign="Middle" />
<HeaderStyle VerticalAlign="Middle" />
<ItemTemplate>

<asp:Label ID="Label1" runat="server" Text='<%# Bind("Title") %>'></asp:Label>
</ItemTemplate>
<ControlStyle Width="200px" /> </asp:TemplateField>

Dynamically change the year of copyright

In footer section i placed image of copyright in which 2011 year is mentioned. But its fixed, when 2012 comes footer reamins to 2011 year of copyright how can i change that year when new comes? i want to create a jQuery code for that purpose which pick the desire year pic according to current year and placed it to the footer section automatically because of this it save alot of time every year when changed.

Code is very simple use below code and makes your images name as 2011.png, 2012.png etc

CODE

<img src="/images/<%= DateTime.Now.Year %>.png" alt="Copyright" />

Asp.Net multiline textBox character counting to custom limit via JavaScript

Here's the code to tells that how can I limit the user to certain characters length using javascript along with asp.net Textbox control

ASPX MARKUP


<div>
    <p>
        Asp.Net TextBox Character Counting using Javascript Limit Characters to 135
    </p>
    <asp:TextBox ID="txtMessage" runat="server" TextMode="MultiLine" onKeyUp="CheckLimit();"></asp:TextBox><asp:RequiredFieldValidator
        ID="RequiredFieldValidator2" runat="server" ErrorMessage="*" ControlToValidate="txtMessage"
        Display="Dynamic"></asp:RequiredFieldValidator>
    <font size="1">(Maximum characters: 135)<br />
        You have
        <asp:Label ID="lblCountLimit" runat="server" Text="135" ForeColor="Red"></asp:Label>
        characters left.</font>
</div>

JAVASCRIPT CODE

function CheckLimit() {
var textField =
    document.getElementById("<%=txtMessage.ClientID %>");
var labelCount =
    document.getElementById("<%=lblCountLimit.ClientID %>");

   if (textField.value.length > 135) {
       textField.value = textField.value.substring(0, 135);
   } else {
       labelCount.innerHTML = 135 - textField.value.length;
   }
}

Character Counting from Asp.Net Textbox using JavaScript

Many peoples asked on different forums inc that how can we calculate Textbox character onkeyup events using JavaScript. The way is very simple here is short code of that query. I also functionality that if length of character less than or equal to 160 then total no. of sms is 1 and vice versa.
ASPX MARKUP
<div>
    <p>
        Asp.Net TextBox Character Counting using Javascript If > 160 then Show SMS: 02
    </p>
    <asp:TextBox ID="txtMessageText" runat="server" TextMode="MultiLine" onKeyUp="CountCharacter();"></asp:TextBox>
    <asp:RequiredFieldValidator ID="rfvMessageText" runat="server" ErrorMessage="*" ControlToValidate="txtMessageText"
        Display="Dynamic"></asp:RequiredFieldValidator>
    <font size="1">
        <asp:Label ID="lblCountDown" runat="server"></asp:Label>
    </font>
</div>
JAVASCRIPT CODE
function CountCharacter() {
    var count = 0;
    var mgsLength = 0;

    var textField = 
        document.getElementById("<%=txtMessageText.ClientID %>");
    var labelField = 
        document.getElementById("<%=lblCountDown.ClientID %>");

    var length = textField.value.length;
    var setValue = count + length;

    if (setValue == 0) {
        mgsLength = 0;
        labelField.innerHTML = 
            "Total characters " + setValue + "; No of SMS: " + mgsLength;
    }
    else {
        if (setValue <= 160) {
            mgsLength = 1;
            labelField.innerHTML = 
                 "Total characters " + setValue + "; No of SMS: " + mgsLength;
    }
    else {
        var roundLength = setValue / 160;
        mgsLength = Math.ceil(roundLength);
        labelField.innerHTML = 
                 "Total characters " + setValue + "; No of SMS: " + mgsLength;
    }
  }
}

April 28, 2011

Asp.net DropDownList Selected Value with Jquery

Here's final code



<html xmlns="http://www.w3.org/1999/xhtml">

<head runat="server">

    <title></title>

    <script src="js/JScript.js" type="text/javascript"></script>

    <script type="text/javascript">      



        function btnClick() {



            var countryCode = $('#ddlCountry').val();

            var countryName = $('#ddlCountry').find('option:selected').text();



            $('#txtCode').val(countryCode);

            $('#txtName').val(countryName);

        }

    </script>

</head>

<body>

    <form id="form1" runat="server">

    <div>



        <asp:DropDownList ID="ddlCountry" runat="server" Width="145px" ClientIDMode="Static">

            <asp:ListItem Value="AF">Afghanistan</asp:ListItem>

            <asp:ListItem Value="AL">Albania</asp:ListItem>

            <asp:ListItem Value="DZ">Algeria</asp:ListItem>

            <asp:ListItem Value="AS">American Samoa</asp:ListItem>

            <asp:ListItem Value="AD">Andorra</asp:ListItem>

            <asp:ListItem Value="AO">Angola</asp:ListItem>

            <asp:ListItem Value="AI">Anguilla</asp:ListItem>

            <asp:ListItem Value="PK">Pakistan</asp:ListItem>

        </asp:DropDownList>

        <input id="txtCode" type="text" />

        <input id="txtName" type="text" />

        <input id="btn" type="button" value="OK" onclick="btnClick()" />

    </div>

    </form>

</body>

</html>

LINQ to SQL using JavaScriptSerilizor

For serilization of code in linq to sql might review this code which resolve your error if occurs

[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public string GetEmployee(int employeeId)
{
string returnString = "";
DbTransaction getTransaction = null;
DatabaseDataContext dataContext = null;

try
{
dataContext = new DatabaseDataContext(Classes.Constants.GetConnectionString());
dataContext.Connection.Open();
getTransaction = dataContext.Connection.BeginTransaction();
dataContext.Transaction = getTransaction;

ArrayList ar = new ArrayList();

List getEmployee = dataContext.spEmpSelect(Convert.ToInt64(employeeId)).Select(
p =>
new Employee()
{
A= p.A,
B = p.B,
FirstName = p.FirstName,
LastName = p.LastName

}).ToList();

List getEmAddr= dataContext.sp_getEmAddr(employeeId).Select(
p =>
new EmployeesAddress()
{
Addr = p.Addr,
Address1 = p.Address1,
City = p.City,
Country = p.Country,
ContactNumber1 = p.ContactNumber1,
ContactNumber2 = p.ContactNumber2
}).ToList();


var jss = new JavaScriptSerializer();
ar.Add(getEmployee);
ar.Add(getEmAddr);
returnString = jss.Serialize(ar);
getTransaction.Commit();
}
catch (Exception exception)
{
returnString = exception.Message;
getTransaction.Rollback();
}
finally
{
if (dataContext.Connection.State == System.Data.ConnectionState.Open)
{
dataContext.Connection.Close();
}
}
return returnString;
}

Ajax Modalpopup Extendar

Here is code below to show how to display ajax modalpopup extendar in your web page.

HTML Code

<asp:Button ID="btnShow" runat="server" Text="Show" CausesValidation="false" CssClass="defaultButton"
OnClick="btnShow_Click" />
<asp:HiddenField ID="ShowErrorAlert" runat="server" />
<asp:HiddenField ID="HideErrorAlert" runat="server" />
<asp:ModalPopupExtender ID="ModalPopupExtender1" runat="server" CancelControlID="HideErrorAlert"
TargetControlID="ShowErrorAlert" BackgroundCssClass="popupBackground" PopupControlID="pnlShowErrorAlert" />

<asp:Panel ID="pnlShowErrorAlert" runat="server" Style="display: none;">
<div class="title">
Error Window
</div>
<div class="popupWindow">
<asp:Label ID="lblErrorInfo" runat="server"></asp:Label><br />
<br />
</div>
</asp:Panel>
Button Click Code

protected void btnShow_Click(object sender, EventArgs e)
{
ModalPopupExtender1.Show();
}

Using jQuery to Consume ASP.NET JSON Web Services

jQuery is nowadays a very effective for client side programming as it reduce code and increase the performance of any thing. Calling web service in asp.net using jQuery is very easy as you find a lot of codes on net some of them are so easy and some of them quite complex for the beginners.

First of all here you need to know the output format of web service to pass data to database or retrieve from database. Web Service returns output into two format.
  • XML
  • JSON
Its depend on you which format you like in your coding.

Check this code

Here's the final code which works fine on VS 2008/2010

--------------------------
ASPX MARKUP :
-------------------------------


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

<!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>JSON Call</title>

    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js" type="text/javascript"></script>

    <script language="javascript" type="text/javascript">

        $(function() {

            $("#btnShow").click(function() {

                $.ajax(
                {
                    type: "POST",
                    url: "JsonService.asmx/GetNameById",
                    data: "{'Id':'" + $("#txtID").val() + "'}",
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: function(data, status) {
                        $("#txtName").val(data.d);
                    },
                    error: function(mgs) {
                        alert(mgs.d);
                    }
                });
            });
        });
     
    </script>

</head>
<body>
    <form id="form1" runat="server">
    <div>
        <input id="txtID" type="text" /><br />
        <input id="txtName" type="text" /><br />
        <input id="btnShow" type="button" value="Show" />
    </div>
    </form>
</body>
</html>

--------------------------
WEB SERVICE
--------------------------

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.Script.Services;

namespace Test_Web
{
    /// <summary>
    /// Summary description for JsonService
    /// </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 JsonService : System.Web.Services.WebService
    {

        [WebMethod]
        [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
        public string GetNameById(int Id)
        {
            string returnString = "";

            if (Id == 1)
            {
                returnString = "Alpha";
            }
            else if (Id > 1 && Id <= 10)
            {
                returnString = "Beta";
            }
            else
            {
                returnString = "Gamma";
            }

            return returnString;
        }
    }
}

Web services are great tools that afford you substantial flexibility. It’s important not to overlook them. I believe that to be a short-sighted and counterproductive way to do things.

Using jQuery DateTime Picker to select date and time

There are so many JavaScript / jQuery plugins available for showing both date and time in one picker. Its is quiet easy rather than you add two images one for date and other for time. JavaScript date time picker is easily available on Here

First of all I am going to tell you how to integrate this into your webpage. Below example would help you to do so.

------------------------
Process Life Cycle :
-----------------------------

Select time according to need then click on specified date then complete DateTime will show in TextBox then save this value to database using SQL database type "DateTime"

-----------------------
Code Integration :
-----------------------

Then i modified code according to need Here's the HMTL code.


  1. Download JavaScript file and add it to Head tag of page (Get javascript file from below website Javascript name: My Date Time Picker | Creator: TengYong Ng  | Website: http://www.rainforestnet.com)
  2. Then add these lines into body tag

<div>


        <asp:TextBox ID="txtDate" runat="server" Width="150px" MaxLength="25"></asp:TextBox>
        <a href="javascript: NewCssCal('ctl00_HomeContent_Wizard1_txtDate','mmmddyyyy','arrow',true,12,false)">
            <img src="../../Images/cal.gif" width="16" height="16" alt="Pick a date"></a>
</div>

Convert type string to string[ ]

Many peoples asked about the errors that might be occur while conversion in strings. Error is
Cannot implicitly convert type 'string' to 'string[]'

There is very big difference between Convert.ToString() and string[]

Convert.ToString = It converts your array of string into single string instance

For the following code use this

string[] getRoleType = (string[])Session["Role"];

March 12, 2011

Separate ID's using comma then pass to database

This is simple console program which is used to built only for any sycnerio in which we have to bulk of ID's in string and pass that ID's into database by breaking each ID after comma.

Here's the code

static void Main(string[] args)
{
Console.WriteLine("Please enter name of friut by comma separated");

string data = Console.ReadLine();

string[] dataNos = data.Trim().Split(new char[] { ',' });
for (int i = 0; i < dataNos.Length; i++)
{
if (dataNos[i] != "")
{
string result = dataNos[i];
Console.WriteLine(result);
}
}

Console.ReadLine();
}

English to Native language Transalator

This program is based on Console Application using C#.Net Framework 4.0. This program using Google Transaltion API and you get your transaltion API from Code.Google.com

Here's Code

static void Main(string[] args)
{
Console.WriteLine("Please write some thing here to be translate");

string text = Console.ReadLine();
string fromLanguage = "en"; //English
string toLanguage = "es"; // Spanish
string apiKey = ""; // Enter your APIKey here
string apiUrl = "https://www.googleapis.com/language/translate/v2?key={0}&source={1}&target={2}&q={3}";
string url = string.Format(apiUrl, apiKey, fromLanguage, toLanguage, text);

var translateLanguage = new Translate();
string returnData = translateLanguage.TranslateLanguage(url);
Console.WriteLine("Your translate sentence in spanish is: \n" + returnData);

Console.ReadLine();
}

Class Code

public class Translate
{
public string TranslateLanguage(string url)
{
string returnString = string.Empty;

try
{
WebRequest request = HttpWebRequest.Create(url);
request.Method = "GET";

using (WebResponse response = request.GetResponse())
{
using (var streamReader = new StreamReader(response.GetResponseStream(), Encoding.UTF8))
{
returnString = streamReader.ReadToEnd();
}
}
}
catch (Exception exception)
{
Console.Out.WriteLine(exception.Message);
}
return returnString;
}
}

Playback Sound

This program is based on Windows Form Application using C#.Net Framework 4.0. The conclusion of this program is to built a such type of application who save your voice at runtime and playback your voice after stop saving that voice also user has an option of saving the recoding at the time of play-back.

For this purpose you have to include Microsoft SAPI dll file add in Refernce of your project. For add reference right click on reference in solution explorer then click on reference and on Tab named Browse go to this path

C:\Program Files\Common Files\\Microsoft shared\Speech\Sapi.dll

To enable us to reference the required namespaces directly from code.

using System.Diagnostics;
using System.Threading;
using SpeechLib;

For Creating User Interface you need following controls

3 Buttons named as;

Start -----> btnStart
Stop -----> btnStop
Replay-----> btnReplay

1 checkbox named as

Checkbox -----> chkSaveVoice

1 Textbox named as txtText (Multiline = true)

The GUI of form is as follow;

Playback-Sound-Image

Add these members in form class

private SpeechLib.SpSharedRecoContext objRecoContext;
private SpeechLib.ISpeechRecoGrammar grammar;
private string strData="No recording yet";

Here's the code

public void RecoContext_Recognition(int StreamNumber, object StreamPosition, SpeechRecognitionType RecognitionType, ISpeechRecoResult Result)
{
strData = Result.PhraseInfo.GetText(0, -1, true);
Debug.WriteLine("Recognition: " + strData + ", " + StreamNumber + ", " + StreamPosition);
txt.Text = strData;
}

private void btnStartDictation_Click(object sender, EventArgs e)
{
try
{
if (objRecoContext == null)
{
objRecoContext = new SpeechLib.SpSharedRecoContext();
objRecoContext.Recognition += new _ISpeechRecoContextEvents_RecognitionEventHandler(RecoContext_Recognition);
grammar = objRecoContext.CreateGrammar(1);
grammar.DictationLoad("", SpeechLoadOption.SLOStatic);
}

grammar.DictationSetState(SpeechRuleState.SGDSActive);
}

catch(Exception ex)
{
System.Windows.Forms.MessageBox.Show("Error occurred: " + ex.ToString(),"Error");
}
}

private void btnStopDictation_Click(object sender, EventArgs e)
{
grammar.DictationSetState(SpeechRuleState.SGDSInactive);
}

private void btnReplay_Click(object sender, EventArgs e)
{
try
{
SpeechVoiceSpeakFlags SpFlags = SpeechVoiceSpeakFlags.SVSFlagsAsync;
SpVoice Voice = new SpVoice();
if (chkSaveReplay.Checked)
{
SaveFileDialog sfd = new SaveFileDialog();
sfd.Filter = "All files (*.*)|*.*|wav files (*.wav)|*.wav";
sfd.Title = "Save to a wave file";
sfd.FilterIndex = 2;
sfd.RestoreDirectory = true;
if (sfd.ShowDialog() == DialogResult.OK)
{
SpeechStreamFileMode SpFileMode = SpeechStreamFileMode.SSFMCreateForWrite;
SpFileStream SpFileStream = new SpFileStream();
SpFileStream.Open(sfd.FileName, SpFileMode, false);
Voice.AudioOutputStream = SpFileStream;
Voice.Speak("You recorded the following message " + strData, SpFlags);
Voice.WaitUntilDone(Timeout.Infinite);
SpFileStream.Close();
}
}
else
{
Voice.Speak("You recorded the following message" + strData, SpFlags);
}
}
catch
{
MessageBox.Show("Speak error", "SimpleTTS", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
Important Notes

Every time the Start Dictation button is clicked, we set the DictationState of the grammar object to active.

Every time the Stop Dictation button is clicked, we just sets the DictationSetState of the grammar object to Inactive.

This program saves the recognized words and append the user voice input to the textbox and save it to our string member variable.

If user selected to save the playback recording using checkbox by checked then we display a Save File Dialog and save the user’s playback to the file.

March 11, 2011

Text-to-Speech Recognition (TTS)

There is a lot of examples having place on internet about text-to-speech recognition. Mostly are in vb.net or other source. But here i am introducing code in C#.Net Framework 4.0.


I am using Microsoft Speech SDK 5.1 or you can use built-in SAPI which is already install in every type of windows. This is Windows Form Application using C# and you have to add following controls in your form


3 Buttons named as;
  • Start ----> btnStart
  • Stop ----> btnStop
  • Exit ----> btnExit

1 combo box named as;
  • cmbInstalledVoice (Dropdown style = dropdownlist)

2 Trach control named as;
  • Volume -----> btnVolume (Set minimum = 0 and maximum = 100)
  • Rate -----> btnRate (Set minimum = -10 and maximum = 10)

1 Textbox named as;
  • TextBox ------> txtVoiceText (multiline = true)

Here's also the sketch of form including these controls
Text-To-Speech-Image

Now add web reference in your project, For Web Reference
Right click on reference in solution explorer then click on Add Reference, in tab name .Net add reference name System.Speech

C# Code:


using System.Speech.Synthesis;
using System.Collections.ObjectModel;
using System.Globalization;
using System.Diagnostics;

private SpeechSynthesizer speechSynthesizer = new SpeechSynthesizer();

private void Form1_Load(object sender, EventArgs e)
{
    ReadOnlyCollection(installedvoice) getInstalledVoice = speechSynthesizer.GetInstalledVoices(CultureInfo.CurrentCulture);
    VoiceInfo voiceInfo = getInstalledVoice[0].VoiceInfo;

    foreach (InstalledVoice installedVoice in getInstalledVoice)
    {
       voiceInfo = installedVoice.VoiceInfo;
       cmbInstalledVoice.Items.Add(voiceInfo.Name.ToString());
    }
}
private void btnStart_Click(object sender, EventArgs e)
{
   speechSynthesizer.SelectVoice(cmbInstalledVoice.Text);
   speechSynthesizer.SpeakAsync(txtVoiceText.Text);
}

private void btnVolume_ValueChanged(object sender, EventArgs e)
{
   speechSynthesizer.Volume = btnVolume.Value;
}

private void btnRate_ValueChanged(object sender, EventArgs e)
{
   speechSynthesizer.Rate = btnRate.Value;
}

private void btnStop_Click(object sender, EventArgs e)
{
   speechSynthesizer.SpeakAsyncCancelAll();
}

private void btnExit_Click(object sender, EventArgs e)
{
   this.Close();
}

March 3, 2011

Convert JSON Date to Standard Date Format

Many peoples asked about JSON date conversion into Javascript code or Jquery
Code. The method is very simple and easy. When ever you insert Date into
database using Json and when you retrieve that date from database its in Json
Format which is some thing like that:

My input Date is : 14/2/2011 (for example)
My output Date is : /Date(1297246301973)/ (for example)

So here problems create when u update that date into database again its cause error.
Here's is simple code to formulate the actual date as you inserted before

var date = /Date(1297246301973)/;
var parsedDate = new Date(parseInt(date.substr(6)));
var newDate = new Date(parsedDate);

var getMonth = newDate.getMonth();
var getDay = newDate.getDay();
var getYear = newDate.getYear();

var standardDate = getMonth + '/' + getDay + '/' + getYear;

Now you got your date according to you format....:)