"If at first you don't succeed; call it version 1.0" :-Unknown

Pages

Sunday, August 29, 2010

set Minimum lenght on textbox value

 we can set maxlength of the Textbox to "n" which limits the text to be "n"
characters long.but for Minimum, we can easily do with Regex Validator
with validation Expression

Toset maxlenght
 <asp:TextBox ID="textbox1" runat="server" MaxLength="6"></asp:TextBox>
Toset Minimum Lenght
<asp:TextBox ID="textbox1" runat="server"></asp:TextBox>
<asp:RegularExpressionValidator ID="RegularExpressionValidator1"
ValidationExpression="^[0-9]{13,16}$" runat="server"
ControlToValidate="textbox1" ErrorMessage="error">
</asp:RegularExpressionValidator> 
 
here ValidationExpression="^[0-9]{13,16}$" is the sole part.
This will accept only number and also it should have a minimum 
lenght 13 number and maxmium  length 16. 
 
i think this helped u someways. 
 
Have a nice day... 'N happy Coding :)

Friday, August 27, 2010

Different Ways of using the C# Null Coalescing Operator

Hi frienz,
The C# Null-Coalescing operator or the ?? operator is a binary operator that returns the left-hand operand if it is not null; otherwise it returns the right operand. It can be used with both nullable and reference types.
Here’s a simple example of using the Null-Coalescing operator
int? i = null;
int j = i ?? 2;
// here the resultant value of j is 2
Here are some additional ways of using the Null-Coalescing operator in your code.

Method 1
string address = homeAddress1 ?? homeAddress2 ?? officeAddress
                 ??  "No Address";
returns the first non-null value in this long expression. This expression returns “No Address” if homeAddress1, homeAddress2 and officeAddress are Null.


Method 2
While converting a Nullable Type to Non-Nullable type, we do an explicit cast to avoid assigning null values to a non-nullable type, as shown below:
int? a = NullType(); // returns nullable int
int b = (int)a;
instead you can avoid the explicit cast using a null-coalescing operator and write:
int? a = NullType();
int b = a ?? 0;

Method 3
private IList<Person> person;
public IList<Person> PersonList
{
    get
    {
        return person ?? (person = new List<Person>());
    }
}
Typical usage of the null-coalescing operator in a lazy instantiated private variable.


Method 4

string conn = Connection["TestMachineStr1"]
            ?? AppConnection["ProdMachineStr2"]
            ?? DefaultConnection["DefaultConn"];
Accessing NameValueCollections and choosing the first non-null value.

Note: The Null-Coalescing operator is useful but may sometimes be an overkill, especially when developers use it to flaunt their coding skills. I sometimes choose ‘understandable code’ over ‘terse code’, focusing on the intent.

Feel free to use the comments section to demonstrate how you have used the null-coalescing operator in your projects.
 
 
Have a nice day... 'N happy Coding :)

Tuesday, August 17, 2010

Get Random Password Using GUID

Hi frienz,
Globally unique identifier (GUID) is a special type of identifier used in software  applications to provide a unique reference number. The value is represented as a 32 character hexadecimal character string, such as {21EC2020-3AEA-1069-A2DD-08002B30309D} and usually stored as a 128 bit integer. The term GUID usually, but not always, refers to Microsoft's implementation of the Universally Unique Identifier (UUID) standard.

Here i'm creating a random password Of fixed lenght using GUID.i created a function with a parameter for lenght and it will return the value.

    public string GetRandomPasswordUsingGUID(int length)
    {
        // Getting randam Password
        //Get the GUID
        string guidResult = System.Guid.NewGuid().ToString();

        //Remove the hyphens
        guidResult = guidResult.Replace("-", string.Empty);

        //Make sure length is valid
        if (length <= 0 || length > guidResult.Length)
        {
            throw new ArgumentException("Length must be between 1 and " + guidResult.Length);
        }

        //Return the first length bytes
        return guidResult.Substring(0, length);
    }


Hope this help You...

Have a nice day... 'N happy Coding :)

Monday, August 16, 2010

Set selectedvalue in RadioButtonList dynamically from database

 Hi frienz,
 for this we need to populate radio-button List from database., we can choose a radio item which we want to selected dynamically before the page rendered.

simple code:

aspx.cs 
protected void Page_Load(object sender, EventArgs e)
        {
          if (!IsPostBack)
                bindRadioList();
        }
private DataSet CreateData()
        {
            DataTable table = new DataTable();
            table.Columns.Add(new DataColumn("OptionID",
 System.Type.GetType("System.String")));
            table.Columns.Add(new DataColumn("Option"
System.Type.GetType("System.String")));
 
            DataRow row1 = table.NewRow();
            row1["OptionID"] = "1";
            row1["Option"] = "A";
 
            DataRow row2 = table.NewRow();
            row2["OptionID"] = "2";
            row2["Option"] = "B";
 
            DataRow row3 = table.NewRow();
            row3["OptionID"] = "3";
            row3["Option"] = "C";
 
            table.Rows.Add(row1);
            table.Rows.Add(row2);
            table.Rows.Add(row3);
 
            DataSet ds = new DataSet();
            ds.Tables.Add(table);
 
            return ds;
 
        }
private void bindRadioList()
        {
            DataSet ds = CreateData();
            RadioButtonList1.DataSource = ds;
            RadioButtonList1.DataTextField = "Option";
            RadioButtonList1.DataValueField = "OptionID";
            RadioButtonList1.DataBind();
 
            if (RadioButtonList1.Items.Count > 0)
                RadioButtonList1.Items[0].Selected = true
                   //you can set a selected items you want.
        }
 
On aspx
  <asp:RadioButtonList ID="RadioButtonList1" runat="server" 
        </asp:RadioButtonList>
 
i think this code helped u 
Have a nice day... 'N happy Coding :)

Friday, August 13, 2010

Binding grid with an xml stream

 Hi frienz,
2day i'm binding grid with an xml stream

        DataSet ds = new DataSet();
        System.Xml.XmlDocument doc = new System.Xml.XmlDocument();
        doc.LoadXml("<?xml version='1.0' encoding='utf-8'?><RechargeNow><st-code>77</st-code><st-desc>Wrong Requested IP</st-desc><st-no> 540</st-no><st-tno>-1</st-tno></RechargeNow>");
        ds.ReadXml(new System.IO.StringReader(doc.OuterXml));
        GridView1.DataSource = ds;
        GridView1.DataBind();


i think it will help u...

Have a nice day... 'N happy Coding :)

Binding grid with an xml File from other website

 HI frienz,
In my last post i shown how to bind grid from a local pc.In this post i'm Binding grid with xml from Other website.

        WebRequest wreq = WebRequest.Create("http://your webservice provider/pagename.aspx?qstring="+args);
        WebProxy proxy = new WebProxy("http://your webservice provider/pagename.aspx?qstring="+args, true);
        wreq.Proxy = proxy;
        wreq.Timeout = 5000;
        WebResponse wres = wreq.GetResponse();
        XmlTextReader xmlRead = new XmlTextReader(wres.GetResponseStream());
        DataSet ds = new DataSet();
        ds.ReadXml(xmlRead);


Hope it will help u.

Have a nice day... 'N happy Coding :)

Binding grid with an xml File in Local system

 Hi frienz,

Bind grid with an Xml file. To load an xml file in asp.net we need to class some header file.

using System.Data;
using System.Xml;


 After that u will get the access to use xml files.
this code will bind Xml with Grid

DataSet ds=new DataSet();
ds.ReadXml("your xml file path here");
Gview.DataSource=ds;
Gview.DataBind();


I think It will help u some way's
Have a nice day... 'N happy Coding :)

Wednesday, August 11, 2010

jquery word count

Hi Friends,
I'm counting No of words in a text-box. With the help of two Js File.













Have a nice day... 'N happy Coding :)

unicode of the key pressed in alert box

 Hi friendz,
As every key on keyboard had an Unicode.Some times it help when we run around java-script.

Code

<html>
<head>
<script type="text/javascript">
function whichButton(event) {
alert(event.keyCode)
}
</script>
</head>
<body onkeyup="whichButton(event)">
<p><b>Note:</b> Make sure the right frame has focus when trying this example!</p>
<p>Press a key on your keyboard. An alert box will alert the unicode of the key
pressed.</p>
</body>
</html>


Have a nice day... 'N happy Coding :)

Checking username avillabilty without page refresh or Connecting Javascript with web service

Hi friends,
2day I'm connecting javascript with Webservice Without help of any external js Files.and
i'm show username checking as an example.
Demo

















Code
 on Webservice
    <script runat="server">
        [System.Web.Services.WebMethod, System.Web.Script.Services.ScriptMethod]
        public static string Getadata(string Data)
        {
            System.Threading.Thread.Sleep(1000);// i'm making 1 second sleep here
            string Scriptt ="";
            if (Data == "arun")
                Scriptt = "Not Avilable";
            else
                Scriptt = "Avilable";
           
                return Scriptt;
        }
    </script>

on javascript

    <script language="javascript" type="text/javascript">
        function keyPress(id) {
           // debugger;
            var tb = document.getElementById(id);
            if (tb.value.length > 2) {
                document.getElementById('im').style.display = 'Block'; // Display Image
                document.getElementById('label1').innerHTML = "";
                PageMethods.Getadata(tb.value, myFunction);
               }
            return false;
        }
        function myFunction(msg) {
           // debugger;
            // alert(msg);
            hideimage();
            document.getElementById('label1').innerHTML = msg;
        }
        function hideimage() {
            document.getElementById('im').style.display = 'none'; 
// DOM3 (IE5, NS6) Hide Image
        }
    </script>

on Body
<body onload="hideimage();">
    <form id="form1" runat="server">
    <div>
        <asp:ScriptManager ID="ScriptManager" runat="server"
EnablePageMethods="true" />
        asp.net:<asp:TextBox ID="TextBox1" onkeyup="keyPress('TextBox1');"
runat="server"></asp:TextBox><img id="im" src="Image/ajax-loader.gif" alt="" />
        <label id="label1" ></label>
       
        <asp:GridView ID="GridView1" runat="server">
        <Columns>
        <asp:TemplateField>
        <ItemTemplate>
        <asp:Button ID="but" runat="server" Text="data" onclick="but_Click" />
        </ItemTemplate>
        </asp:TemplateField>
        </Columns>
        </asp:GridView>
       
    </div>
    </form>
</body>
 
Have a nice day... 'N happy Coding :)

Monday, August 9, 2010

Execute a Function at Regular Intervals using JavaScript

 The Window.setInterval() contains two parameters: the function name/function call with parameters
and the time of the timer. Using this, you can execute a function at regular intervals. Here’s a small
example:

<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
    <title>Run the Same Function at Regular Intervals 
w/JavaScript</title>
    <script type="text/javascript">
        var cnt = 0;
        setInterval(printDuration, 3000);

        function printDuration() {
            cnt += 1;
            document.getElementById("para").innerHTML = cnt;
        }
    </script>
</head>
<body>
<div>
    <p id="para">0</p></div>
</body>
</html>
As you can see, we have set a timer of 3000 millisecond or 3 seconds. 
The printDuration() gets called after every 3 seconds and by manipulating t
he paragraph (para) element's innerHtml , we are able to print the value 
of the counter in it.


Have a nice day... 'N happy Coding :)

Friday, August 6, 2010

Creating Windows Services in C#

Hi frienz,
To create a Windows service, start Visual Studio, select the Visual C# projects section
and select Windows Service as the project type:
http://dotnet.dzone.com/sites/all/files/1_15.png


Once created, you will see that there is no designer. To jump into the code,
press F7 and you should see a code structure similar to this:


using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;

namespace testService
{
    public partial class Service1 : ServiceBase
    {
        public Service1()
        {
            InitializeComponent();
        }

        protected override void OnStart(string[] args)
        {

        }

        protected override void OnStop()
        {

        }
    }
}
 
on that add a new timer code like this:
 
System.Timers.Timer SentTimer = new System.Timers.Timer();
        public Service1()
        {
            InitializeComponent();
        } 
 
The OnStart event happens when the service starts and the 
OnStop
event occurs when the service stops. For this specific example,
I am 
going to create an application that keeps a log of running
processes. 
Therefore, in the OnStart event I am going to use the following 
sample code: 
SentTimer.Start();
SentTimer.Enabled = true;
SentTimer.Interval = 60000; // 1 minute gap
SentTimer.Elapsed += new System.Timers.ElapsedEventHandler(_Timer_Elapsed);
 
private void _Timer_Elapsed(object sender,System.Timers.ElapsedEventArgs e)
{
 sentmail();
System.Console.WriteLine("myTimer event occurred");
}
 
This basically puts a line in the log file that indicates that the service was started.
If the file exists, the line is appended. If not – the file is created in the specified folder.
Also, the list of current processes is written to the text file.
When the service stops, it is a good idea to insert a log entry as well. So here goes a
snippet for the OnStop event handler:

SentTimer.Stop();
 
Besides the OnStop and OnStart event handlers, the developer can also
work with OnPause and OnContinue.
Let’s customize the service a bit. Return to the initial designer-less page.
There, in the bottom right corner you will see the list of available properties:
 
 

 











Instead of the default name (Service1) I named it TestService, so I can easily
identify it in the service list later on.
The actual service cannot be installed on the local machine without an installer. To
add an installer, right click on the gray background in the designer-less view and
select the Add Installer option.
Now, you should see the installer listed:

Select the service process installer (in this case – serviceProcessInstaller1) and
change the Account property to LocalService (otherwise authentication will be used):




NOTE: If you are testing on Windows Vista or Windows 7, you might want
to set this option to LocalSystem to avoid an Access Denied error.
To test the above code, I need to install the service, since I cannot test it directly
from the IDE. Press Ctrl+Shift+B to build the solution. Once the build succeeded,
head over to the folder that contains the executable file that was just compiled.
For my specific case, the folder is the following:
C:\Users\Dennis\Documents\Visual Studio 2010\Projects
\testService\testService\bin\Debug
There, I can see an executable called testService.exe. That’s exactly the one
I was looking for. Now, launch the Visual Studio Command Prompt
(in the Start Menu -> Programs -> Microsoft Visual Studio -> Visual Studio Tools)
. From here, I am going to use INSTALLUTIL to install a service on the local
Windows machine. To do this, type the following:
installutil <path to executable>
Once you press ENTER, you should see something like this:


Once you see the message that says that the service was successfully installed,
press Win + R on the keyboard to open the Run dialog and type services.msc –
this will open the list of services installed on the current machine.
There, you can see the newly installed service:


The startup is set to Manual, so you can right click on it and start the service.
Once started, go to the folder that was specified for the log file and see if there
is the log entry.
In case you don’t need the service anymore or you want to test another build,
use this command to uninstall the service:
installutil <path to executable> /u

Finish :)

Now i need to say thanks to this url which helped me a lot in this 
http://dotnet.dzone.com/articles/creating-windows-services-c


I think it helped u a bit

Thursday, August 5, 2010

Display dynamic images as per some criteria in aspx page

Hi friendz,
In my last project i faced Display dynamic images as per some criteria in a grid. Here i'm sharing the code

Code

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <script runat="server">
        public string GetImage(object status)
        
        {
            if (status != null)
            {
                int s = int.Parse(status.ToString());
                if (s == 1) return "~/img/yes.jpg";
                else if (s == 0) return "~/img/no.gif";
                return "~/img/na.gif";
            }
            return "~/img/na.gif";
        }
    </script>
</head>
<body>
    <form id="form1" runat="server">
         ########   grid Starts here  #########
       Item templete
       <asp:Image ID="ImportantImage" runat="server" ImageUrl='<%# this.GetImage(Eval("status"))  %>' /><br />
    ########   grid Ends here  #########
    </form>
</body>
</html>




Have a nice day... 'N happy Coding :)

FileUpload Javascript Validation

Hi friends,
It's better to avoid validation through server side even we can do through client side.
this code is for fileupload validation . It wil accept only ".xls", ".xlsx", ".XLS",".XLSX" 
Fileuploader Id is FileUpload1 

Code
    <script type="text/javascript">        function CheckFileExtension() {             var ctrlUpload = document.getElementById('<%=FileUpload1.ClientID%>'); //Does the user browse or select a file or not.             if (ctrlUpload.value == '') {alert("Select a file first!");ctrlUpload.focus();return false;} //Extension List for validation. Add your required extension here with comma separator.             var extensionList = new Array(".xls", ".xlsx", ".XLS", ".XLSX"); //Get Selected file extension             var extension = ctrlUpload.value.slice(ctrlUpload.value.indexOf(".")).toLowerCase(); //Check file extension with your required extension list.             for (var i = 0; i < extensionList.length; i++) { if (extensionList[i] == extension) return true; } alert("You can only upload an Excel File Type i.e.\n" + extensionList.join(" or\n")); ctrlUpload.focus(); return false;         } </script>
now call the function CheckFileExtension() on button onclientclick event it solved 
have a nice day 'n happy coding :)
 JavaScript: The Good PartsJavaScript: The Definitive GuideObject-Oriented JavaScript: Create scalable, reusable high-quality JavaScript applications and libraries
 

Wednesday, August 4, 2010

Displaying page load time through javascript

Hi friends,
now it's to show page load time in web-pages and it's very simple
Demo






Sample Code
<head>
<title>Calculating Page Loading Time</title>
<SCRIPT LANGUAGE="JavaScript">
//calculate the time before calling the function in window.onload
beforeload = (new Date()).getTime();
function pageloadingtime()
{

                 //calculate the current time in afterload
                afterload = (new Date()).getTime();
                 // now use the beforeload and afterload to calculate the seconds
                secondes = (afterload-beforeload)/1000;
//Fixing to 2 decimal point
secondes = secondes.toFixed(2);
                 // If necessary update in window.status
                window.status='You Page Load took  ' + secondes + ' seconde(s).';
                 // Place the seconds in the innerHTML to show the results
                document.getElementById("loadingtime").innerHTML =
"<font color='red'>(You Page Load took " + secondes + " seconde(s).)</font>";
               
}
 
window.onload = pageloadingtime;
</SCRIPT>
</head>
<body >

</body>
</html>


Have a nice day... 'N happy Coding :)