Objects in this mirror are closer to Microsoft Technologies. DNM objective is to help users on Microsoft technologies by providing Articles, snippets, Interview Questions.
Showing posts with label Snippet. Show all posts
Showing posts with label Snippet. Show all posts

15 September 2012

Iterating/Looping through rows without using cursors in Sql server


In this snippet we will see how to  iterating the table rows data with out using cursor in SQL server.
 
set nocount on
go

declare @tempEmpTable table(EmpID int , EmpName nvarchar(100))
declare  @varEmpID int, @varEmpName nvarchar(100)

insert into @tempEmpTable
select 1, '1st Employee' union all
select 2, '2nd Employee' union all
select 3, '3rd Employee' union all
select 4, '4th Employee' union all
select 5, '5th Employee' union all
select 6, '6th Employee' union all
select 7, '7th Employee' union all
select 8, '8th Employee' union all
select 9, '9th Employee'

select top 1 @varEmpID = EmpID, @varEmpName = EmpName  from @tempEmpTable  

while @varEmpID is not null
begin
                print @varEmpName
                delete  @tempEmpTable   where @varEmpID = EmpID
                set @varEmpID = null         
                select top 1 @varEmpID = EmpID, @varEmpName = EmpName  from @tempEmpTable  
end
Output:
1st Employee
2nd Employee
3rd Employee
4th Employee
5th Employee
6th Employee
7th Employee
8th Employee
9th Employee

03 September 2012

convert IP address to binary format using IPAddress Class in C#


In this snippet we will see how to convert an IP address to binary format using System.Net.IPAddress class.

static List<string> ConvertIPAddressToBinary(string input)
        {
           IEnumerable<string> binaries= IPAddress.Parse(input).GetAddressBytes().Select( x=> Convert.ToString(Convert.ToInt32(x), 2).PadLeft(8, '0'));
           return binaries.ToList();
        }
 
  static void Main()
        {
            List<string> listBinaries = ConvertIPAddressToBinary(“192.168.0.1”)
            foreach (string binary in listBinaries)
            {
                Console.Write(binary + " ");
            }
        }
Output : 11000000 10101000 00000000 00000001

IPAddress class contains the address of a computer on an IP network and supports IPv4 or IPv6.

31 August 2012

Remove special characters (!@#$%.etc) with empty string from a string using JavaScript


Using java script if you want to remove special characters from a string, we can achieve using regular expression.

The below code will allow alphabets (lower and upper case) and numbers in a string.
var str = '@This is sample sting from <.NET Mirror> Ready! 1#2%3*Go';
var rStr = str.replace(/[^a-zA-Z0-9]+/g, '');
alert(rStr);
Output : ThisissamplestingfromNETMirrorReady123Go

If you want allow some of special characters then add them to expression. In the below code we will try to add space and dot.  so now the expression allows alphabets, numbers space and dot.

var rStr1 = str.replace(/[^a-zA-Z0-9 .]+/g, '');
alert(rStr1);
Output: This is sample sting from .NET Mirror Ready 123Go

17 August 2012

Reading Web.Config values of Appsettings and connection string in Javascript using ASP.NET


In this snippet, we will see how to read values which are defined in appsettings and connectionStrings sections of web.config in javascript using ASP.NET.

In the following code, we will add values for appSettings and connectionStrings sections in web.coinfig file then from ASPX javascript we will try to read the values.

Web.config
                <appSettings>
                                <add key="appKeyPI" value="3.15"/>
                </appSettings>
                <connectionStrings>
                                <add name="conStr" connectionString="Here is my connectoin string"/>
                </connectionStrings>

ASPX Page
<head>
   <script type="text/javascript">
       var appKeyVal = '<%=ConfigurationSettings.AppSettings["appKeyPI"].ToString()%>';
       var conStrVal = '<%=ConfigurationManager.ConnectionStrings["conStr"].ConnectionString %>';
       alert("AppSettings value is: " + appKeyVal);
       alert("Connection string value is: " + conStrVal);
    </script>
</head>

31 July 2012

Reverse string using Array.Reverse function in .NET


In this snippet we will a simple program to reverse a string using Array.Reverse function in .NET.
Array.Reverse Method - Reverses the order of the elements in a one-dimensional Array or in a portion of the Array.

Reverse string using Array.Reverse function
   class ReverseString
    {
        static void Main()
        {
            Console.WriteLine(ReverseStr("DotNetMirror"));
            Console.WriteLine(ReverseStr(".NET Mirror"));      
            Console.ReadLine();
        }
        public static string ReverseStr(string s)
        {
            char[] arr = s.ToCharArray();
            Array.Reverse(arr);
            return new string(arr);           
        }

    }

Output:
rorriMteNtoD
rorriM TEN.

Program to find number of occurrences of a character/letter in a sentence in .NET


In this snippet we will see the program to find number of occurrences of a character in a sentence.

   class NoOfTimesLetterAppearedInSentence
    {
        public static void Main()
        {
            char letterToFind = 'r';
            string sentence = "dotnetmirror reflects your knowledge";
            int count = GetLetterCountInSentence(letterToFind, sentence);
            Console.WriteLine("letter {0} found {1} Times in '{2}'",letterToFind,count, sentence);
            Console.ReadLine();
        }
        public static int GetLetterCountInSentence(char letter, string sentence2check)
        {
            int noOfTimes=0;
            for (int i = 0; i < sentence2check.Length; i++)
            {
                if (sentence2check[i] == letter)//if found, increase the count
                {
                    noOfTimes += 1; 
                }
            }
            return noOfTimes; //returns the count of noOfTimes
        }
    }

Output:
letter r found 5 Times in ' dotnetmirror reflects your knowledge'


25 July 2012

swapping three variables without using temp/fourth variable in C#.NET

In some of interviews, interviewers will ask write a program to swap three numbers without using a fourth variable or temporary (temp) variable. So in this snippet we will see how to swap three numbers without using fourth/temp variable.

Program : Swapping 3 numbers Without temp variable
class SwapThreeNumbersWithoutUsingFourthVariable
{
public static void Main()
{
Console.WriteLine("/****** Program to swap 3 numbers without using temporary variable *******/");
int a = 10, b = 20,c=30;
Console.WriteLine(" Values before swapping a={0} , b={1} , c={2}", a, b,c);
a = a + b + c;
b = a - (b + c);
c = a - (b + c);
a = a - (b + c);
Console.WriteLine(" Values after swapping a={0} , b={1}, c={2}", a, b,c);
Console.ReadKey();
}
}

Output:
Values before swapping a=10 , b=20 , c=30
Values after swapping a=30 , b=10, c=20

24 July 2012

NET Program to check whether the given string is palindrome string or not with out using any builtin funcitons


In this snippet we will write a program to check whether the given string is palindrome string or not.

What is palindrome String?
Palindrome string is a string that remains the same when its chars are reversed
Example: string 'wowow' is a palindrome string.
string 'dotnetmirror'- it not a palindrome string.

Snippet:
class PalindromeString
    {
        static bool CheckPalindrome(string CheckString)
        {
            if (CheckString == null || CheckString.Length == 0)
            {
                return false;
            }
            int strMaxIndex = CheckString.Length - 1;
            for (int i = 0; i < CheckString.Length / 2; i++)
            {
                if (CheckString[i] != CheckString[strMaxIndex - i])
                {
                    return false;
                }
            }
            return true;
        }
        public static void Main()
        {
            Console.WriteLine("********** Palindrome string Check Example ********");
            Console.WriteLine();
            Console.Write("Enter string to you want to check: ");
            string str = Console.ReadLine();
            if (CheckPalindrome(str))
            {
                Console.WriteLine("{0} is a Palindrome String", str);
            }
            else
            {
                Console.WriteLine("{0} is not a Palindrome String", str);
            }
           
            Console.ReadLine();
        }
}

Output:
 Example : Input =wowow (palindrome string)
Fig1 : Palindrome string "wowow"








Example : Input =dotnetmirror (not a palindrome string)
Fig2 : Not a Palindrome string "dotnetmirror"

 Example : Input =maddam(palindrome string)
Fig3 : Palindrome string "maddam"