Sponsored Ad

Wednesday, March 31, 2010

Convert Given Time to HH:MM:SS Format in C#

This post will guide you to convert Given H:M:S time format to HH:MM:SS format. The given method you can  also use for your custom format or if you can Hour , Minute and Seconds in different variables and you want to combine it in HH:MM:SS format.

 

       /// <summary>
       /// Purpose : to bring the time in HH:MM:SS format for a given string in H:M:S format
       /// <para>for example, if the time is sent as 8:3:5 then it will be converted to 08:03:05</para>
       /// <para>IN parameter: string time, bool showhour, showminute, showsecond</para>
       /// RETURN value : string in the format HH:MM:SS
       /// </summary>
       public static string GetProperTimeValue(string pTime, bool pShowHour, bool pShowMinute, bool pShowSecond)
       {
           string returnTime = "";

           try
           {
               //STEP 1 : Removing the seconds
               string mHourMinute = pTime.Substring(0, pTime.LastIndexOf(":"));

               //STEP 2 : Extracting hour, minute, seconds values
               string mHour = mHourMinute.Substring(0, mHourMinute.IndexOf(":"));
               string mMinute = mHourMinute.Substring(mHourMinute.LastIndexOf(":") + 1);
               string mSeconds = pTime.Substring(pTime.LastIndexOf(":") + 1);

               //STEP 3 : If the length of hour / minute is 1 then prefix with 0
               mHour = (mHour.Length == 1 ? "0" + mHour : mHour);
               mMinute = (mMinute.Length == 1 ? "0" + mMinute : mMinute);
               mSeconds = (mSeconds.Length == 1 ? "0" + mSeconds : mSeconds);

               returnTime = (pShowHour ? mHour + (pShowMinute ? ":" : "") : "") +
                   (pShowMinute ? mMinute + (pShowSecond ? ":" : "") : "") +
                            (pShowSecond ? mSeconds : "");
           }
           catch
           {
               returnTime = pTime;
           }

           return returnTime.Trim();
       }

How to Copy a DataView Row to a DataTable Row.

This post will illustrate you to how to Copy a DataView Row to a DataTable Row. This have a precondition that both Datarow and Datarowview should have same structure.

To make same structure you can make clone of them.

 

       /// <summary>
       /// PURPOSE : To copy a dataview row to a datatable row.
       /// <para>IN Parameter: Datarow, DataRowView</para>
       /// IMPORTANT NOTE: Both datarow,datarowview should have the same structure
       /// </summary>
       /// <param name="returnRow"></param>
       /// <param name="pDvRow"></param>
       /// <returns></returns>
       public static DataRow CopyDvRowToDtRow(DataRow returnRow, DataRowView pDvRow)
       {
           int maxCnt = pDvRow.DataView.Table.Columns.Count;

           for (int cnt = 0; cnt < maxCnt; cnt++)
           {
               returnRow[cnt] = pDvRow[cnt];
           }

           return returnRow;
       }

How to Construct Full URL from Query String and Site Name

This small utility will guide you to construct a full URL from a given site name and query string collection.

Just pass the site URL without Query string and query string collection in name value format and this method will construct a full URL. It loop through each and every query string in name value collection and construct the URL.

 

public string GetPageUrlWithQueryString(string SiteURL, NameValueCollection
collectionOfQueryStrings)
        {
          try
            {
                mtAdmin = new MTAdmin();
                string url = mtAdmin.GetPageUrl(pageId);
                string queryString = "";
                for (int i = 0; i < collectionOfQueryStrings.Count; i++)
                {
                    queryString = queryString + collectionOfQueryStrings.GetKey(i) + "=" +
collectionOfQueryStrings.Get(i) + "&";
                }
                queryString = queryString.Substring(0, queryString.Length - 1);
                return (url + "?" + queryString);
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
            }
        }

How to Navigate to a Page After Showing Message in C#

This utility will help to show message in JavaScript before redirecting to next page. To use this utility just pass the page url  as input parameter and assign your required message to sMessage string.

This utility will prompt you for customize message and when you click on OK button, the control will navigate to given page.

Use and customize this method as per your requirement. Let me know in case of any queries.

 

        /// <summary>
        /// To Navigate to the Required Page after showing a Message to the User.
        /// </summary>
        /// <param name="PageURL"> Page to be Redirected   </param>
        /// <param name="isRedirect">Set to True </param>

        public void Navigate(string PageURL)
        {
            try
            {
                string url = PageURL;
                string sMessage = “You are about to navigate”;
                StringBuilder str = new StringBuilder();
                str.Append("<script language='javascript'>");
                str.Append(Environment.NewLine);
                str.Append("alert('" + sMessage + "');");
                str.Append(Environment.NewLine);
                str.Append(Environment.NewLine);
                str.Append("var sUrl;");
                str.Append(Environment.NewLine);
                str.Append("sUrl ='" + url.Replace("~", "..") + "';");
                str.Append("window.location.href = sUrl;");
                str.Append(Environment.NewLine);
                str.Append("</script>");
                this.Page.RegisterStartupScript("alertKey", str.ToString());
            }
            catch (Exception ex)
            {
                throw;

               //handle exception
            }
        }

Tuesday, March 30, 2010

How to Create Table in PL/SQL Developer | Create First Database Table

This post will guide you to create your first database table using pl/sql developer.

Please follow this step by step guide to create your first database table.

 

Step 1:  Open PL/SQL developer. Go to Tools –> Browser (Check this option) . A Browser window appears.

PL/SQL Browser window

 

Step 2: Now in Browser window go to table folder and right click in table –> Click New.

PL/SQL Browser Window

 

Step 3: A new Create table window appears. Enter the table name and comments all other fields are optional . You can fill other fields as per your requirement. like if you want to create a global temporary table just check temporary option under Duration.

PL/SQL Create Table

 

Step 4: Enter the columns you need in new table. like i added two columns 1. id_test and it is not null and primary column. and second is name type of varchar 2 and size is 100 characters.

Create Column PL/SQL

 

Step 5:  Add a primary key in keys tab. i added pk_id for column id_test.

pl/sql add primary key

 

Step 6: System already added a index on primary key. you can check in indexes column. You can create more indexed on any column.

pl/sql Create indexs

 

Step 7:  Click on View SQL bottom on bottom right corner and you can check the sql query of all the setting we done for table creation. You can copy this query and save it and you can directly run it from SQL command prompt to create a table.

PL/SQL View SQL

 

Here is text for of the SQL query. You can use this query to create a simple table just remove the SYS. from this query and run on SQL command prompt.

-- Create table
create table SYS.TB_Test
(
  id_test number not null,
  Name    varchar2(100)
)
;
-- Add comments to the table
comment on table SYS.TB_Test
  is 'A Test Table';
-- Add comments to the columns
comment on column SYS.TB_Test.id_test
  is 'primary key';
-- Create/Recreate primary, unique and foreign key constraints
alter table SYS.TB_Test
  add constraint pk_id primary key (ID_TEST);

 

The new table is create “TB_TEST” at browser window. Just Refresh the browser and you will able to see this table at list.

PL/SQL Table list

How to Detect Browser in JavaScript

This sample JavaScript code will help you to find the Browser level details using some standard JavaScript functions.

Sometime while coding we need to have browser details so that make programs browser compatible and your programs can rum on multiple browsers with out any error.

The best way is to handle all the browser related things in JavaScript. and user appropriate action at client side only.

So use this code and enjoy the power of JavaScript.

 

The navigator variable contains all the details of browser level.

navigator.appName returns the browser name.

navigator.appVersion gives the exact browser version details.

navigator.appCodeName returns the browser code

navigator.platform gives the browser code.

navigator.cookieEnabled gives the cookies are enabled or not in current browser.

 

<html>

<body>

<script type="text/javascript">

document.write("Browser Name: ")

document.write(navigator.appName + "<br>")

document.write("Version of Browser: ")

document.write(navigator.appVersion + "<br>")

document.write("Browser Code: ")

document.write(navigator.appCodeName + "<br>")

document.write("Platform / Os: ")

document.write(navigator.platform + "<br>")

document.write("Cookies Enabled: ")

document.write( navigator.cookieEnabled);

</script>

</body>

</html>

How to Attaché/Add AJAX Toolkit in Visual Studio 2005 IDE Toolbox

This post will help you to attaché AJAX toolkit in Visual studio IDE toolbox.

Please follow step by step process to do this task. Screenshots of every step is given.  In case of any queries or questions just comment to this post.

 

Step 1: To attaché AJAX toolkit you need to have an AJAX toolkit DLL. For that just go to http://www.asp.net/ajaxlibrary/download.ashx and download AJAX toolkit DLL.

step 2:  Open toolbox in IDE. Right Click on any tab and click on add tab.

How to Attaché/Add AJAX Toolkit in Visual Studio 2005 IDE Toolbox

 

Step 3: Give the name AJAX Toolkit to newly added tab.

How to Attaché/Add AJAX Toolkit in Visual Studio 2005 IDE Toolbox

 

step 4: Now right click on AJAX Toolkit tab and click on choose items.

How to Attaché/Add AJAX Toolkit in Visual Studio 2005 IDE Toolbox

 

step 5:  Choose toolbox items window opened. Now click on browse button.

How to Attaché/Add AJAX Toolkit in Visual Studio 2005 IDE Toolbox

 

step 6: Locate the AJAXcontrolToolkit.dll and click on open button.

How to Attaché/Add AJAX Toolkit in Visual Studio 2005 IDE Toolbox

 

step 7:  AJAX toolkit items are added and selected in Choose toolbox item window. Now click on ok button.

How to Attaché/Add AJAX Toolkit in Visual Studio 2005 IDE Toolbox

 

Step 8:  congratulations, You have successfully added AJAX Toolkit in you IDE toolbox. Now start enjoying the power of AJAX with ASP.NET.

How to Attaché/Add AJAX Toolkit in Visual Studio 2005 IDE Toolbox

How to Truncate String in C# | Get String of Limited Words

This post will help help you to truncate the given string to a limited word. Just pass the original string and world limit as an input parameter and it will return the truncated string.

This code checks every word of string and count the words in string and if it reaches the maximum word limit, it just returns the limited word string.

 

 

public static string truncate(string originalInput, int wordsLimit)
   {
       if (originalInput != null && originalInput != "")
       {
           StringBuilder output = new StringBuilder(originalInput.Length);
           StringBuilder input = new StringBuilder(originalInput);

           int words = 0;
           bool lastwasWS = true;
           int count = 0;

           do
           {
               if (char.IsWhiteSpace(input[count]))
               {
                   lastwasWS = true;
               }
               else
               {
                   if (lastwasWS) words++;
                   lastwasWS = false;
               }
               output.Append(input[count]);
               count++;
           } while ((words < wordsLimit || lastwasWS == false) && count < originalInput.Length);

           return output.ToString();
       }
       else
       {
           return string.Empty;
       }
   }

Monday, March 29, 2010

How to Change Cursor using CSS | HTML Cursors

 

This sample code demonstrate you all the basic cursors available in HTML. Just copy and paste this html code in your HTML file and run it.

You can mouse over the given text and check all the cursor samples.

 

<html>

<body>

<p>Move the mouse over the words to see the cursor change:</p>

<span style="cursor:auto"> Auto Cursor </span><br /><br />

<span style="cursor:crosshair"> Crosshair Cursor</span><br /><br />

<span style="cursor:default"> Default Cursor</span><br /><br />

<span style="cursor:pointer"> Pointer Cursor</span><br /><br />

<span style="cursor:move"> Move Cursor</span><br /><br />

<span style="cursor:e-resize"> e-resize Cursor</span><br /><br />

<span style="cursor:ne-resize"> ne-resize Cursor</span><br /><br />

<span style="cursor:nw-resize"> nw-resize Cursor</span><br /><br />

<span style="cursor:n-resize"> n-resize Cursor</span><br /><br />

<span style="cursor:se-resize"> se-resize Cursor</span><br /><br />

<span style="cursor:sw-resize"> sw-resize Cursor</span><br /><br />

<span style="cursor:s-resize"> s-resize Cursor</span><br /><br />

<span style="cursor:w-resize"> w-resize Cursor</span><br /><br />

<span style="cursor:text"> text Cursor</span><br /><br />

<span style="cursor:wait"> wait Cursor</span><br /><br />

<span style="cursor:help"> help Cursor</span>

</body>

</html>

Convert Null to Empty String in C#

Some times while coding, We need to check for null string other wise it will throw an exception.

suppose we are using tostring() method on a string, it will throw a exception while using with null string.

To avoid exception either we can use Convert.ToString(input_string) or just replace the input_string null value with empty string.

So using Convert.ToString method is solution for one case only, So we can go with other solution to replace the null string with empty one. It will avoid unwanted exception. This code will help you to convert the null string to empty string.

 

      /// <summary>
      /// Returns a converted null to an empty string.
      /// </summary>
      public static string ConvertNullToEmptyString(string strinput)
      {
          return (strinput == null ? "" : strinput);
      }

Sunday, March 28, 2010

What is Difference between Count(1) , Count(*) and Count(Column_name)

The out put of count(1) and Count(*) is same while Count(1) can provide good performance in some cases, in general both are same.

Count(Column_name) returns the count of all the rows except not null column fields.

For example we have a table employee which have following rows for the column Employee_name.

 

Row 1.  null

Row 2. null

Row 3.  Rajesh

 

So the results will be:

Count(1) will return : 3

Count(*) will return : 3

Count(Employee_name) will return 1

Friday, March 26, 2010

How to check for a Number in JavaScript | IsNumber()

this java script utility will help you to find that a given string is number or not. just pass a string in  this utility and it will return true or false.

 

How to call this method:

IsaNumber(‘123’)

result: true

IsaNumber(‘abc’)

result : false

 

 

function IsaNumber(strString)
{
   var strValidChars="0123456789";
   var strChar;
   var blnResult=true;
   if (strString.length==0) return false;
   for (var i=0;i<strString.length && blnResult==true;i++)
   {
      if (strValidChars.indexOf(strString.charAt(i))==-1)
      {
          blnResult = false;
      }
   }
   return blnResult;
}

How to replace a string in a given string with new string using JavaScript

This JavaScript utility helps you to replace a particular test in a given string with a new text values.

just pass these parameters in given function , for example:

replace(‘Original string’, ‘string’ ,’new string’);

in above call We are replacing ‘string’ values in ‘Original string’ with ‘new string’

 

function replace(string,text,newtext) {
// Replaces text with newtext in string
    var strLength = string.length, txtLength = text.length;
    if ((strLength == 0) || (txtLength == 0)) return string;

    var i = string.indexOf(text);
    if ((!i) && (text != string.substring(0,txtLength))) return string;
    if (i == -1) return string;

    var newstr = string.substring(0,i) +newtext;

    if (i+txtLength < strLength)
        newstr += replace(string.substring(i+txtLength,strLength),text,newtext);

    return newstr;
}

Generic Method to Populate Dropdown Data in C# | Populate Dropdown from Dataset

This post illustrate you about populating the dropdown list from a dataset. Just pass your dropdownlist and value field name(database column name) and text field name (database column name) and dataset in this method and it will automatically populate the drop down list.

this is very generic method to populate combobox and used for number of  dropdown list.

 

public void PopulateCombo(DropDownList oList, string sValueField, string sTextField, DataSet oDs)
      {
          if( oDs == null || oDs.Tables.Count == 0 || oList == null ) return;
          //Enables us to add an empty item to the list
          for (int irow = 0; irow < oDs.Tables[0].Rows.Count; irow++)
          {
              oList.Items.Add(new ListItem(Convert.ToString(oDs.Tables[0].Rows[irow][sTextField]), Convert.ToString(oDs.Tables[0].Rows[irow][sValueField])));
          }

      }

 

How to Use this method:

PopulateCombo(ddlDivision, "ID_DIVISION", "NAME", oDs);

 

Just call this method and pass these  parameters:

ddlDivision : dropdown list

ID_DIVISION: dropdown value field name coming from database column name

NAME: dropdown text field name coming from database column name

oDs: our dataset which have the ID_DIVISION and NAME columns.

How to Get Domain Name from a URL | Extract Domain Name in C#

This utility illustrate you to get domain name from a given URL or Website page location.

The input string for this utility is URL and it returns the exact domain in string format.

 

public static string GetDomain(string url)
  {
      int pos = url.LastIndexOf("://");

      if (pos != -1)
          url = url.Substring(pos + 3);

      pos = url.IndexOf('/');

      if (pos == -1)
          return url;

      return url.Substring(0, pos);

  }

How to call this utility:

  To call this utility just call  from anywhere in code and result will return in a string.

GetDomain(http://csharptalk.com/);


Like i am calling in page_Load event of page.

protected void Page_Load(object sender, EventArgs e)
  {

      Label1.Text = GetDomain("http://csharptalk.com/");
  }

Thursday, March 25, 2010

Convert Date to User Friendly Date Format

This utility will help you to format date in very user friendly format.  It is not formatting date in exact different format while it translate the in day name as well as yesterday and today format.

 

 

public static string Get_Friendly_Date(System.DateTime src)
  {
      System.DateTime currentdate = DateTime.Now;
      int datediff = (src - currentdate ).Days;
      if (datediff == -1)
      {
          return "Yesterday";
      }
      else if (-7 <= datediff && datediff <= -2)
      {
          return "Last " + src.DayOfWeek.ToString();
      }
      else if (datediff == 0)
      {
          return "Today";
      }
      else if (1 <= datediff && datediff <= 7)
      {
          return "This " + src.DayOfWeek.ToString();
      }
      else
      {
          return src.ToString();
      }
  }

Wednesday, March 24, 2010

How to convert image to Thumbnail Image in C#

These are three utilities to convent  a given image to a thumbnail image.

this utility only take the full size image in byte format and convert into the given height and width thumb image.

 

public static byte[] MakeThumb(byte[] fullsize, int newwidth, int newheight)
{
    Image iOriginal, iThumb;
    double scaleH, scaleW;

    Rectangle srcRect=new Rectangle();
    iOriginal = Image.FromStream(new MemoryStream(fullsize));
    scaleH = iOriginal.Height / newheight;
    scaleW = iOriginal.Width / newwidth;
    if (scaleH == scaleW)
    {
        srcRect.Width = iOriginal.Width;
        srcRect.Height = iOriginal.Height;
        srcRect.X = 0;
        srcRect.Y = 0;
    }
    else if ((scaleH) > (scaleW))
    {
        srcRect.Width = iOriginal.Width;
        srcRect.Height = Convert.ToInt32(newheight * scaleW);
        srcRect.X = 0;
        srcRect.Y = Convert.ToInt32((iOriginal.Height - srcRect.Height) / 2);
    }
    else
    {
        srcRect.Width = Convert.ToInt32(newwidth * scaleH);
        srcRect.Height = iOriginal.Height;
        srcRect.X = Convert.ToInt32((iOriginal.Width - srcRect.Width) / 2);
        srcRect.Y = 0;
    }
    iThumb = new Bitmap(newwidth, newheight);
    Graphics g = Graphics.FromImage(iThumb);
    g.DrawImage(iOriginal, new Rectangle(0, 0, newwidth, newheight), srcRect, GraphicsUnit.Pixel);
    MemoryStream m = new MemoryStream();
    iThumb.Save(m, System.Drawing.Imaging.ImageFormat.Jpeg);
    return m.GetBuffer();
}

 

There is another utility to convert a given image to a thumbinal image just by using a given width.

public static byte[] MakeThumb(byte[] fullsize, int maxwidth)
{
    Image iOriginal, iThumb;
    double scale;

    iOriginal = Image.FromStream(new MemoryStream(fullsize));
    if (iOriginal.Width > maxwidth)
    {
        scale = iOriginal.Width / maxwidth;
        int newheight = Convert.ToInt32(iOriginal.Height / scale);
        iThumb = new Bitmap(iOriginal, maxwidth, newheight);
        MemoryStream m = new MemoryStream();
        iThumb.Save(m, System.Drawing.Imaging.ImageFormat.Jpeg);
        return m.GetBuffer();
    }
    else
    {
        return fullsize;
    }
}

 

To convert a given image to a byte array you can use the following utility.

 

public byte[] ConvertimageToByteArray(System.Drawing.Image imageIn)
{
MemoryStream ms = new MemoryStream();
imageIn.Save(ms,System.Drawing.Imaging.ImageFormat.Gif);
return  ms.ToArray();
}

Tuesday, March 23, 2010

How to Write and Execute Client side JavaScript Code in C#

This is sample method in C# to write a JavaScript code and execute it. Just pass your message in this block of code and it will show alert message on the page.

In place of alert you can write your own JavaScript code. We made this method generic so that  we first checking for single quote in string, In case of hard coding the string we can by pass this step.

Let me know if you have any questions?

 

public static void Alert(string message)
       {
           // Cleans the message to allow single quotation marks
           string cleanMessage = message.Replace("'", "\'");
           string script = "<script type='text/javascript'>alert('" + cleanMessage + "');</script>";

           // Gets the executing web page
           Page page = HttpContext.Current.CurrentHandler as Page;

           // Checks if the handler is a Page and that the script isn't allready on the Page
           if (page != null && !page.ClientScript.IsClientScriptBlockRegistered("alert"))
           {
               page.ClientScript.RegisterClientScriptBlock(typeof(JavaScript), "alert", script);
           }
       }

Modal Dialog Window Opens a New window on every Button Click – JavaScript Problem

When you use java script method it opens a new window, whenever you click on any server side button.

 

Modal window code:

var Result = window.showModalDialog("popup.aspx","Popup","");

To fix this problem you need to add a code block into the popup.aspx head section.

 

you need to write a code script:

<base target="_self" />

 

<head runat="server" >
<base target="_self" />
    <title></title>
</head>

Modal Dialog Window in JavaScript | Return Values from Modal Dialog Window | showModalDialog()

 

showModalDialog is java script function to open a popup in model window.

Model window means until you fill now close the popup window, you can not work with the parent window.

So the Simplest way is

var Result = window.showModalDialog("popup.aspx","","");
or
var Result = window.showModalDialog("http://google.com","","");

Now if you want to pass query string with URL

var Result = window.showModalDialog("popup.aspx?Name=abc&Age=23","","");

Now how to open Modal Dialog with custom width and height as well as other custom values.

var Result = window.showModalDialog("popup.aspx","Popup","dialogHeight: 300px; dialogWidth: 600px;
                    dialogTop: 190px;  dialogLeft: 220px; edge: Raised; center: Yes;
                    help: No; resizable: No; status: No;");

Here Result will receive the values from popup.aspx

To return the values from popup page you just have to write a JavaScript code , either on button click, cancel button, close button, save button.. 

window.returnValue = true;

here it is returning 'true' to parent page.

Now if you have to return multiple values from popup page?

You can write
window.returnValue = 'value1,value2, value3';

and in parent page after receiving these vales in result just split it and store in array and use it.

Result = Result.split(',');

Result[0] will be value1
Result[1] will be value2
Result[2] will be value3

Now How will You return Values from popup C# file ?

just write a java script code in C# and register to page.

ClientScript.RegisterStartupScript(ClientScript.GetType() ,"Search Results", "<script>window.returnValue='value1,value2, value3';window.close();</script>");

Monday, March 22, 2010

First Name and Last Name Validation in C# using Regex

      

This is custom utility to validate first name and last name  using regular expressions.

 

It takes string as a input parameter and return the true and false value for valid and invalid string.

remember to user namespace for regular expression using System.Text.RegularExpressions

 

using System.Text.RegularExpressions;

       /// <summary>
       /// Validate firstname and lastname.
       /// </summary>
       public static bool IsValidName(string strToCheck)
       {
           return Regex.IsMatch(strToCheck, "^[a-zA-Z ]+$");
       }

Email Validation in C# | Validate Email Address Format using Regular Expression

While working i found that if we are using any email field, We always need a email validator.

I created a utility using regular expressions to validate the email format.

You just need to pass email is as a input and it will return you that email id is valid or not.

Please go through it and let me know in case of any problem while using it.

use name space using System.Text.RegularExpressions; to compile this code.

 

using System.Text.RegularExpressions;

      /// <summary>
      /// Validate email address format.
      /// </summary>
      public static bool IsValidEmail(string Email)
      {
          return Regex.IsMatch(Email, @"\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*");
      }

Check Date of Birth Validity | Validate DOB in C#

       Here is a utility to get if age is valid against minimum allowed age. We have to pass date of birth and minimum allowed age as a parameter and it will check and return the true if  DOB is valid and false if invalid.

 

       /// <summary>
       /// Validate date of birth.
       /// </summary>
       public static bool IsValidAge(DateTime DOB, int minAllowedAge)
       {
           int AllowedAge;
           AllowedAge = DateTime.Now.Year - DOB.Year;

           if (AllowedAge < minAllowedAge)
           {
               return false;
           }

           if (DOB.Year < DateTime.Now.Year)
           {
               return true;
           }

           return false;
       }

How to Check Numeric Value in C# | IsNumeric() | Convert String to Integer Value

This utility helps you to check a value for integer values. Just pass input string  and it will return true if string is integer value and return false in case of non integer values.

int.Parse will through a exception if value is not integer.

There is another option you can try with

Int32.TryParse Method (string strCheck, int Result)

With this method you can convert string to int without any exception. input parameter for this method is string the original value and second is out parameter as result. if result have non zero value it means conversion successful and the given value is integer. and result for zero value indicate that the given string is non integer.

 

       /// <summary>
      /// Performs validation whether the passed in string is numeric.
      /// </summary>
      public static bool IsNumeric(string strCheck)
      {
          try
          {
              int.Parse(strCheck);
              return true;
          }
          catch
          {
              return false;
          }
      }

Sunday, March 21, 2010

Calculate Word count in String | Get Number of words in String using C#

This utility helps you to calculate number of words in a given string. This method usage the regular expression to calculate word count.

 

        /// <summary>
        /// Returns word count.
        /// </summary>
        public static int WordCount(string strToCount)
        {
            int words;

            Regex reg = new Regex(@"\w+");

            MatchCollection mc = reg.Matches(strToCount);

            if (mc.Count > 0)
                words = mc.Count;
            else
                words = 0;

            return words;
        }

QueryString Validation in C# | Secure QueryString - Remove Harmful Script | Stop SQL Injection

This utility will filter the QueryString Validation and return the secure query string. This will help C# developers to Validate for potential SQL and XSS injection. While our second method will return the true if QueryString is valid otherwise false.

 

       /// <summary>
       /// Performs querystring validation
       /// </summary>
       /// <returns>Validate for potential SQL and XSS injection</returns>
      public string SecureQueryString(string TexttoValidate)
       {
           string TextVal;

           TextVal = TexttoValidate;

           //Build an array of characters that need to be filter.
           string[] strDirtyQueryString = { "xp_", ";", "--", "<", ">", "script", "iframe", "delete", "drop", "exec" };

           //Loop through all items in the array
           foreach (string item in strDirtyQueryString)
           {
               if (TextVal.IndexOf(item) != -1)
               {
                   PageRedirect(1);//Redirect to page not found.
                   break;
               }
           }

           return TextVal;
       }

      

       /// <summary>
       /// Performs querystring validation
       /// </summary>
       /// <returns>Validate for potential SQL and XSS injection</returns>
      public static bool IsQueryStringSecure(string TexttoValidate)
       {
           string TextVal;

           TextVal = TexttoValidate;

           bool IsSecure = true;

           //Build an array of characters that need to be filter.
           string[] strDirtyQueryString = { "xp_", ";", "--", "<", ">", "script", "iframe", "delete", "drop", "exec" };

           //Loop through all items in the array
           foreach (string item in strDirtyQueryString)
           {
               if (TextVal.IndexOf(item) != -1)
               {
                   IsSecure = false;
               }
           }

           return IsSecure;
       }

Saturday, March 20, 2010

How to Filter Harmful Script from Input String | Remove Harmful Scripts C#

Hackers sometimes try to hack very important information from website, This utility helps you to protect against Harmful script in input string. Just copy and paste this utility in your c# code and call this utility and pass the input string. This method will return the filtered string.

 

       /// <summary>
       /// Filters harmful scripts from input string
       /// </summary>
       /// <param name="Text">Input String</param>
       /// <returns>Filtered String</returns>
       public string FormatTextForInput(string Text)
       {
           if (Text == "")
               return "";

           if (Text == null)
               return "";

           string output = Text;

           //Build an array of characters that need to be filter.
           string[] strDirtyInput = { "xp_", ";", "--", "<", ">", "iframe", "script" };

           //Loop through all items in the array
           foreach (string item in strDirtyInput)
           {
               output = output.Replace(item, "");
           }

           output = output.Replace("'", "''");

           return output;
       }

How to Write Custom Page Redirect Utility in C#

This is a sample custom utility to to redirect page to appropriate functionality. This takes a integer value to to redirect the page. You can have more readability by using the enum’s for redirect numbers.

 

   /// <summary>
   /// Handles the page redirection
   /// </summary>
   public void Redirect_Page(int RedirectTo)
   {
       switch (RedirectTo)
       {
           case 1:
               HttpContext.Current.Response.Redirect("pagenotfound.aspx");
               break;
           case 2:
               HttpContext.Current.Response.Redirect("error.aspx");
               break;
           case 3:
               HttpContext.Current.Response.Redirect("submitconfirm.aspx");
               break;
           case 4:
               HttpContext.Current.Response.Redirect("commentpostconfirmation.aspx");
               break;
           case 5:
               HttpContext.Current.Response.Redirect("recipemanager.aspx");
               break;
           case 6:
               HttpContext.Current.Response.Redirect("adminlogin.aspx");
               break;
           case 7:
               HttpContext.Current.Response.Redirect("confirmarticleupdate.aspx");
               break;
       }
   }

Friday, March 19, 2010

How to Check a Selection in Dropdown using ASP.NET Validation | Dropdown Client Validation ASP.NET

This Example illustrate that how to check if any value is selected in dropdown  or not. This validation is totally perform on client site using asp.net RequiredFieldValidator.  just specify  ControlToValidate as dropdown name and InitialValue as whatever dropdown initial value is.

 

<asp:dropdownlist id="cmbDemo" runat=server>

<asp:listitem>Select</asp:listitem>

<asp:listitem >Demo1</asp:listitem>

<asp:listitem >Demo2</asp:listitem>

<asp:listitem >Demo3</asp:listitem>

</asp:dropdownlist>

<asp:RequiredFieldValidator ControlToValidate="cmbDemo" InitialValue="Select" errormessage="You must select a value" runat=server/>

<asp:button type=submit text="Click" runat="server"/>

Get Month Name from Month Number | Convert Given Month to Month Name in C#

This utility converts the given month number to month name. You have to just pass the month number and it will return month name as return string.

 

Please note that we have used this method and static, you can change and make it non static method.

 

        /// <summary>
       /// Converts the given month number to month name.
       /// </summary>
       public static string GetStringMonthName(int MonthNumber)
       {
           string strmonthname = "";
           switch (MonthNumber)
           {
               case 1:
                   strmonthname = "January";
                   break;
               case 2:
                   strmonthname = "February";
                   break;
               case 3:
                   strmonthname = "March";
                   break;
               case 4:
                   strmonthname = "April";
                   break;
               case 5:
                   strmonthname = "May";
                   break;
               case 6:
                   strmonthname = "June";
                   break;
               case 7:
                   strmonthname = "July";
                   break;
               case 8:
                   strmonthname = "August";
                   break;
               case 9:
                   strmonthname = "September";
                   break;
               case 10:
                   strmonthname = "October";
                   break;
               case 11:
                   strmonthname = "November";
                   break;
               case 12:
                   strmonthname = "December";
                   break;

           }

           return strmonthname;
       }

Get Day Name Abbreviation From Day | Short Day Name in C#

This example illustrate that how to get Short day name from a full day name. This is customize function which returns the abbreviate day name and take full day name as input parameter.

Just Copy and paste the whole function and call it appropriate place.

 

      /// <summary>
       /// Converts the given DayNameoftheweek name to abbrevation.
       /// </summary>
       public static string GetDayNameAbbrev(string FullDayName)
       {
           string Shortdayname= "";

           switch (FullDayName)
           {
               case "Sunday":
                   Shortdayname= "Sun";
                   break;
               case "Monday":
                   Shortdayname= "Mon";
                   break;
               case "Tuesday":
                   Shortdayname= "Tue";
                   break;
               case "Wednesday":
                   Shortdayname= "Wed";
                   break;
               case "Thursday":
                   Shortdayname= "Thu";
                   break;
               case "Friday":
                   Shortdayname= "Fri";
                   break;
               case "Saturday":
                   Shortdayname= "Sat";
                   break;
           }

           return Shortdayname;
       }

How to Calculate Date Difference Between Two Dates

This post illustrate you a very common question in C# that how to calculate date difference between two given dates.

The given method takes date1 and date2 as input parameter and return the difference of dates in days as an integer format.

 

      /// <summary>
       /// Returns number of days diff between 2 given dates.
       /// </summary>
    

  public static int DateDiff(DateTime StartDate, DateTime EndDate)
       {
           int NumDaysDiff;
           TimeSpan ts = EndDate.Subtract(StartDate);
           NumDaysDiff = ts.Days;
           return NumDaysDiff;
       }

 

you can contact me in case of any issues.

How to Find Control Recursively from Collection of Controls

 

I am going to write a code script to find controls recursively. This is sample function to search for a control in a collection of controls and if it present in the collection of controls just the return the control.

This public method accept the control id to search for and a collection of controls.

and it return control incase of successful search and null if control not present.

 

public static Control FindControlRecursively(string controlID, ControlCollection controls)
       {
           if (controlID == null || controls == null)
               return null;

           foreach (Control c in controls)
           {
               if (c.ID == controlID)
                   return c;

               if (c.HasControls())
               {
                   Control inner = FindControlRecursively(controlID,      c.Controls);
                   if (inner != null)
                       return inner;
               }
           }
           return null;
       }

Most Common Interview Questions | HR Interview Questions

 

Q. Tell me a little about yourself?

Q. Why are you looking (or why did you leave you last job)?

Q. Tell me what you know about this company?

Q. Why do you want to work at this Company?

Q. What relevant experience do you have?

Q. If your previous co-workers were here, what would they say about you?

Q. Have you done anything to further your experience?

Q. Where else have you applied?

Q. How are you when you’re working under pressure?

Q. What motivates you to do a good job?

Q. What’s your greatest strength?

Q. What’s your biggest weakness?

Q. Let’s talk about salary. What are you looking for?

Q. Are you good at working in a team?

Q. Tell me a suggestion you have made that was implemented.

Q. Has anything ever irritated you about people you've worked with?

Q. Is there anyone you just could not work with?

Q. Tell me about any issues you’ve had with a previous boss.

Q. Would you rather work for money or job satisfaction?

Q. Would you rather be liked or feared?

Q. Are you willing to put the interests of this Company ahead of your own?

Q. Why I should hire you?

Q. Do you have any questions to ask me?

Q. Do you consider yourself successful?

Q. Where you want to see after 10 years?

Q. Do you know anyone who works for us?

Q. How long would you expect to work for us if hired?

Stryker Interview Questions | Gallop Interview Questions

I gone through a Stryker First psychological interview round and here is few question i remember.

 

This round is conducted on phone and was for around 30 min question answering session.

 

Q. What are the qualities you are looking in team manager?

Q. What Qualities you want in your team members?

Q. Are you analytical?

Q. If problem on hand do you have alternate plans or lack of options?

Q. Are you innovative?

Q. Are you outperformer?

Q. Are you out of box thinker or logical thinker?

Q. if Collision between two parties, how will you solve?

Q. have you motivated anyone last week?

Q. What is your reputation in your company?

Q. Rate your self?

Q. Can you take risk?

Q. if you are unpopular in your team?

Q. what you will do if lot of noise at work place?

Q.If somebody says something behind you ?

Q. if you are too busy ?

Q. If you are not agree with your manager?

Q. if your reputation is not good?

Q. Can you work under pressure?

Q. are you confident end of the day?

Q.Overloaded with work and new responsibilities?

Q. you want to join little successful project or more successful project?

Q. Are you always busy?

Q. Can you lead role?

Q. How to beat a target?

Q. How will you plan the day?

Q. What will you prefer long term or short tem goals?

Q. Are you different to different people.

Tuesday, March 16, 2010

Difference between Ref and Out Parameters

You can find these differences, while using these Ref and Out Parameters:

Both the parameters passed by reference, While for the Ref Parameter you need to initialize it before passing to the function and out parameter you do not need to initialize before passing to function.

you need to assign values into these parameter before returning to the function.

 

Ref (initialize the variable)
int getal = 0;
Fun_RefTest(ref getal);


Out (no need to initialize the variable)
int getal;
Fun_OutTest(out getal);

Monday, March 15, 2010

How to Open Link in new Page/Tab using JavaScript

This is a simple example to open link in new page or tab using java Script. The first example is default, just opens a new page for given link while the second example have custom settings.

 

Open new window with default settings:


<html>
<head>
<script language=javascript>
function openwindow()
{ window.open("http://www.SharePointBank.com") }
</script>
</head>
<body>
<form>
<input type=button value="Open Window" onclick="openwindow()">
</form>
</body>
</html>

 

Open new window with custom settings:

This example demonstrate that how to open link in new window with customized settings. You can give the name of window – > my_new_window

toolbar-> specify if you need browser toolbar

width and Height , resizable, menu bar, scrollbar etc.


<html>
<head>
<script type="text/javascript">
function openwindow()
{
window.open("http://www.SharePointBank.com","my_new_window","toolbar=yes, location=yes, status=no, menubar=yes, scrollbars=yes, resizable=no, copyhistory=yes, width=400, height=400")
}
</script>
</head>
<body>
<form>
<input type="button" value="Open Window" onclick="openwindow()">
</form>
</body>
</html>

Sunday, March 14, 2010

How to Copy DataRows from another DataTable

 

In this example, oDs is the original dataset which have datatable inside and multiple rows are there. Now this example demonstrate only copying 3 rows you can set as the counter as per your requirement. In this code first create a datatable using the same structure of table from where you have to copy a row, otherwise create same structure manually. to copy only table structure use .clone method

DataTable dt = oDs.Tables[0].Clone();

and then inside the for loop use importrow() method to copy the exact row.

dt.ImportRow(oDs.Tables[0].Rows[i]);

 //Copy DataRows from another table

        DataSet oDs = getData();
        DataTable dt = oDs.Tables[0].Clone();
        if (oDs != null && oDs.Tables.Count > 0 && oDs.Tables[0].Rows.Count > 2)
        {
            for (int i = 1; i <= 3; i++)
            {
                dt.ImportRow(oDs.Tables[0].Rows[i]);
            }
        }

Saturday, March 13, 2010

C# – SQL – Interview Questions – Mercer Gurgaon 2010

I gone through personal .NET interview in Mercer Gurgaon. I remember some of the interview questions.  I am posting here for your help.

 

C# Interview Questions:

1. What is OOPs?

2. What is Object?

3. What is Abstract Class?

4. What is abstract function?

5. What is Arraylist, what type of data it store?

6. Boxing and Unboxing?

7. Override and New keywords?

8. Sealed Class?

9. How can you stop a class being inherited?

10. How can you stop class being instantiated?

11. What is interface?

12. Multilevel and Multiple inheritance?

13. How can you handle abstract function without implementing it in derive class?

14. List the datagrid events?

15. How many number of times item data bound event will be called for 10 rows in grid? What property will you use to check header in datagrid?

16. What is HTTP handler? How will you implement?

17. Write a code to add a user control to a page?

18. Difference between user control and custom user control?

19. How many master page a project can have?

20. Write a code to add msterpage in a page?

21. Difference between string and string builder?

22. types of Design patterns? Implement one of them?

23. What is UML ? Design a UML diagram?

24. What is MVC?

25. Can we have multiple update panel in AJAX, Write a code to call another update panel on click on another?

26. what are collections?

27. delegate and events?

 

SQL Interview Questions:

1. Difference between procedure and function?

2. What is temprary table, how to use it?

3. what is trigger and how to use it?

4. How many level a trigger can be implemented?

5. How to implement transaction in database?

6. Difference between primary key and unique key?

7. Cluster and Non Cluster index? create it. How many non cluster index can be there?

8. Can we define cluster index on simple column?

9. create a package?

10. What is implicit and explicit cursor?

11. What is difference between refcursor and cursor?

and so many……….

Disclaimer – CSharpTalk.com

 

Neither CSharpTalk.Com nor the respective Organizations/Sites are responsible for any inadvertent error that may have crept in the Information/Code being published on the Net. The Information published on the net are for immediate information to the user and information received from respective Information/Code should only be treated as authentic in this regard.

The Information/Code provided in these pages of CSharpTalk.com or in any other pages on this network are indicative and we are in no way responsible, either directly or indirectly. The information in these pages do no carry any legal warranty or validity. Any part of data on these pages can be modified unconditionally at any time. Use of this information is under your own risks.

We always make sure that the information provided here is correct and accurate at all times. But, as the old saying says "To Err is Human", we may fall in errors by making typos or providing you with incorrect or unclear information.

CSharpTalk.com, its people, employees, Affiliates or Advertisers and/or people involved in the design of these pages our are in no way responsible for any errors, omissions or representations on any of our pages or on any links on any of our pages. We do not endorse in anyway any advertisers on our web pages. Please verify the validity of information on your own before undertaking any reliance.

We would like you - being one of our esteemed Guest, to help us in making these pages more Informative, Educative and Accurate.

Please report any missing / broken links you may find in these pages to rahul@valdot.com

Some of the links, information or data (including Images, Graphics, Sounds, Animations, Logos or other any interactive Content) on these pages may be owned, maintained or designed by other companies or persons. In most cases we get confirmation from them to have their links on these pages. By in very few cases, we may not be able to reach them. Our aim is to make people from round the world to know, visit and learn using the Internet as the best Media. In case you have any sort of Objection or have found a serious error, please let us know of the same. We shall come back to you with a reply at the earliest.

If you find a typo error or wish to make an update to these pages, you may send a E-Mail briefly giving description of the page and updated info. You may post an E-Mail to rahul@valdot.com and we shall make our best to update them accordingly. Alternatively you may please fill out guest book from the link below.

As a last word, let us inform you that we are in no way responsible for any Legal Warranties either directly / indirectly in any case.

.NET Technical Written Test Questions 2010 – Mercer Gurgaon

Hi All,

I gone through Mercer Technical written test for .NET today and followed by Technical Interview. Here is some questions asked in written test:

Around 24 questions were objective type, 5 subjective small questions from OOPs and 3 questions from SQL.

I do not remember all the questions but here some of them.

Multiple Choice Objective Questions:

1.  What is Abstract Class?

2. What is polymorphism?

3. Virtual Functions?

4. In case of multiuser application what is alternate way to store large date and cookies independent browser will be used?

5. What is view state?

6. New and Override keywords?

7. connection pooling ?

8. Data reader and dataset ?

9. Session Object?

10. Can more then one catch block handle exception in one block?

11.  can array have different type of values?

12. String Builder?

13. Delegates and Events?

and ….

 

Subjective Small Answer Questions

1. Difference between application object and cache?

2. How to prevent a class from inheriting?

3. Events of page life cycle?

4.Types of State management

5. how to check page post back ?

 

SQL Subjective Questions

Two tables are given Employee and Salary

Employee table columns: id, manager id, name

Salary table columns: id, Salary

a.  Get the second top salary from these tables?

b. Get the all employees name and their manages?

c. Apply right outer join and show results?

Friday, March 12, 2010

How to Copy DataTable to DataSet from Another DataSet

 

Here is example that how to copy a DataTable to DataSet from another DataSet.

oDs is our original DataSet and it contains one table in it.  Now create another dataset oDsNew using

     DataSet oDsNew = new DataSet();

Now check if dataset is not empty.

Use .Add method to Copy table from another dataset. Please note that you have to use Copy function from original Dataset.

oDsNew.Tables.Add(oDs.Tables[0].Copy());

 

Original Code:


       //Now we have one dataset with and it have one datatable inside
       DataSet oDs = getData();
       //We have to copy it
       DataSet oDsNew = new DataSet();
       if (oDs != null && oDs.Tables.Count > 0)
       {
           oDsNew.Tables.Add(oDs.Tables[0].Copy());
       }

Wednesday, March 10, 2010

JavaScript Date Functions - Get Date, Month and Year , Get Hours, Minutes and Seconds

Here is sample code to use JavaScript inbuilt date functions. This sample includes functions for:

getDate()

getMonth()

getFullYear()

getHours()

getMinutes()

getSeconds()

 

To use these function first need to create a date variable and then call functions.

 

Get Date, Month and Year

<html>

<body>

<script type="text/javascript">

var d = new Date()

document.write(d.getDate())

document.write(".")

document.write(d.getMonth() + 1)

document.write(".")

document.write(d.getFullYear())

document.write(".")

document.write(d.getHours())

document.write(".")

document.write(d.getMinutes())

document.write(".")

document.write(d.getSeconds())

</script>

</body>

</html>

 

Tuesday, March 9, 2010

Differences between EXEC and SP_EXECUTESQL

Today I did some research on the 2 commands of MS SQL 2005 and here is result.

I was looking at the differences between EXEC and SP_EXECUTESQL.

Both these commands are used to run procedures or dynamic queries.

Lets have an example. Suppose we have the following stored procedure:

Create procedure Sample_UsingDynamicQueries
@table varchar(max)
As
Declare @strQuery nvarchar(4000)
Select @strQuery = 'select * from dbo.' + quotename(@table)
exec sp_executesql @strQuery -------- (A)
--exec (@strQuery) ---------------------- (B)

Execute dbo.samplesp_usingdynamicqueries 'EmpDetails'

Now, after running this stored procedure whether we use the line which is marked as (A) or (B) it would give us the same result.

The difference between both is that Exec statement is Unparameterised whereas sp_executeSql is Parameterised.

For example while using execute(), if we write a query which takes a parameter lets say "EmpID". When we run the query with "EmpID" as 1 and 2 it would be creating two different cache entries (one each for value 1 and 2 respectively).

On the contrary, if we use sp_executeSql, the cached plan would be created only once and would be reused 'n' number of times for ‘n’ number of parameters.

So this would have better performance.

For example:

Select @strQuery = 'Select E.EmpName from dbo.empdetails E where E.EmpID = N''1'''
Exec (@strQuery)

Select @strQuery = 'Select E.EmpName from dbo.empdetails E where E.EmpID = N''2'''
Exec (@strQuery)

Select @strQuery = 'Select E.EmpName from dbo.empdetails E where E.EmpID = @EmpID'
Exec sp_executesql @strQuery, N'@EmpID int', 1
Exec sp_executesql @strQuery, N'@EmpID int', 2

Now using Exec, 2 separate execution plans will be created.

But when we are using sp_executesql, the execution plan will be created only once and will be reused for the 2 parameters and hence the time would be saved in this.

Monday, March 8, 2010

Beginners: How to Create First HTML Program

When i was a beginner, to create first program searched a lot. Now i thought i should write a post specifying all the details, that how to write a simple html program and run it. This is very silly post but very helpful.

There few steps to create first html program without using any tool.

Step 1: Open a notepad and write the given code.

 

<html>
<head>
<title>
First Page title
</title>
</head>
<body>

<h1>First Program</h1>
<br>
This my first html program.
<br>
<p> First Paragraph. </p>

</body>

</html>

 

The HTML code file should have <html> tag at top and closing tag </html> at bottom. Then inside <html> tags there should be two tags pair <head> at the top and <body> after <head> tag. Inside <head> you can put <title> tag pair to specify title.

Beginners: How to Create First HTML Program

Step 2:  Save as the file.

Beginners: How to Create First HTML Program

Step 3:  Select Save as type –> ALL and give file name as First Program.htm or First Program.html, both are same.

Beginners: How to Create First HTML Program

After saving the file just open the file with any browser it will display you results.

Beginners: How to Create First HTML Program

Please note that this is basic details for creating a simple HTML program and these is number of html tags, you can read from online sources and create a rich program.

Sponsored Ad

More Related Articles

Website Update

Followers