Monday, March 5, 2012

Print Prime numbers between 1 to 100

int length=100;
for(int  n=2;n<100;n++)
{
bool isprime=true;
for(int j=2;j<n;J++)
{
if(n%j==0)
{
isprime=false;
return;
}
}
if(isprime)
{
Console.Writeline("{0}is prime",n);
}
}

Print Fabanaii series using array and print from 1 to 10 fabinacii numbers

Print Fabinacii series Using Array:

int a[]={10,13,12,15};
int first=0;last,result;
for(int i=0;i<a.length;i++)
{
last=a[i];
result=last+fisrt;
first=result;
console.writeline(result);
}

print from 1 to 10 fabinacii numbers:
result=0;last=1;

for(int i=0;i<10;i++)
{
result=first+last;
last=result;
first=last;
Console.WriteLine(result);
}

Export to Excel in Windows applications

  BindingSource objBinding = new BindingSource();
        private void Form2_Load(object sender, EventArgs e)
        {
            SqlConnection con = new SqlConnection("server=USER9-PC;database=Tasks;user id=sa;password=secure2011");
            SqlDataAdapter da = new SqlDataAdapter("select * from Location", con);
            DataTable dt = new DataTable();
            da.Fill(dt);
            objBinding.DataSource = dt;
            dataGridView1.DataSource = objBinding;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            Microsoft.Office.Interop.Excel.ApplicationClass ExcelApp = new Microsoft.Office.Interop.Excel.ApplicationClass();
            ExcelApp.Application.Workbooks.Add(Type.Missing);

            // Change properties of the Workbook
            ExcelApp.Columns.ColumnWidth = 20;

            // Storing header part in Excel
            for (int i = 1; i < dataGridView1.Columns.Count + 1; i++)
            {
                ExcelApp.Cells[1, i] = dataGridView1.Columns[i - 1].HeaderText;
            }

            // Storing Each row and column value to excel sheet
            for (int i = 0; i < dataGridView1.Rows.Count - 1; i++)
            {
                for (int j = 0; j < dataGridView1.Columns.Count; j++)
                {
                    ExcelApp.Cells[i + 2, j + 1] = dataGridView1.Rows[i].Cells[j].Value.ToString();
                }
            }
            //ExcelApp.ActiveWorkbook.Save();
           // ExcelApp.ActiveWorkbook.SaveCopyAs("C:\\Users\\user 9\\Downloads\\Export DataGridView to Excel\\Export DataGridView to Excel\\test.xls");
            ExcelApp.ActiveWorkbook.Saved = true;
            ExcelApp.ActiveWorkbook.SaveAs("C:\\Users\\user 9\\Desktop\\test.xls",Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing,Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlExclusive , Type.Missing, Type.Missing, Type.Missing, Type.Missing,Type.Missing);
            ExcelApp.Quit();
        }

        private void button2_Click(object sender, EventArgs e)
        {
             Microsoft.Office.Interop.Excel.Application xlApp ;
            Microsoft.Office.Interop.Excel.Workbook xlWorkBook ;
            Microsoft.Office.Interop.Excel.Worksheet xlWorkSheet ;
            object misValue = System.Reflection.Missing.Value;

            xlApp = new Microsoft.Office.Interop.Excel.ApplicationClass();
            xlWorkBook = xlApp.Workbooks.Add(misValue);
            xlWorkSheet = (Microsoft.Office.Interop.Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
            int i = 0;
            int j = 0;

            for (i = 0; i <= dataGridView1.RowCount  - 1; i++)
            {
                for (j = 0; j <= dataGridView1.ColumnCount  - 1; j++)
                {
                    DataGridViewCell cell = dataGridView1[j, i];
                    xlWorkSheet.Cells[i + 1, j + 1] = cell.Value;
                }
            }

            xlWorkBook.SaveAs("C:\\Users\\user 9\\Desktop\\test1.xls", Microsoft.Office.Interop.Excel.XlFileFormat.xlWorkbookNormal, misValue, misValue, misValue, misValue, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue);
            xlWorkBook.Close(true, misValue, misValue);
            xlApp.Quit();

            releaseObject(xlWorkSheet);
            releaseObject(xlWorkBook);
            releaseObject(xlApp);

            MessageBox.Show("Excel file created , you can find the file C:\\Users\\user 9\\Desktop\\test1.xls");
        }

        private void releaseObject(object obj)
        {
            try
            {
                System.Runtime.InteropServices.Marshal.ReleaseComObject(obj);
                obj = null;
            }
            catch (Exception ex)
            {
                obj = null;
                MessageBox.Show("Exception Occured while releasing object " + ex.ToString());
            }
            finally
            {
                GC.Collect();
            }
        }
       

Export to excel in Windows applications using xml

public Form1()
        {
            InitializeComponent();
            DataSet ds = new DataSet();
            ds.ReadXml("C:\\Users\\user 9\\Downloads\\Export DataGridView to Excel\\Export DataGridView to Excel\\Products.xml");
            dataGridView1.DataSource = ds.Tables[0];
        }

        private void button1_Click(object sender, EventArgs e)
        {
            Microsoft.Office.Interop.Excel.ApplicationClass ExcelApp = new Microsoft.Office.Interop.Excel.ApplicationClass();
            ExcelApp.Application.Workbooks.Add(Type.Missing);

            // Change properties of the Workbook
            ExcelApp.Columns.ColumnWidth = 20;

            // Storing header part in Excel
            for (int i = 1; i < dataGridView1.Columns.Count + 1; i++)
            {
                ExcelApp.Cells[1, i] = dataGridView1.Columns[i - 1].HeaderText;
            }

            // Storing Each row and column value to excel sheet
            for (int i = 0; i < dataGridView1.Rows.Count - 1; i++)
            {
                for (int j = 0; j < dataGridView1.Columns.Count; j++)
                {
                    ExcelApp.Cells[i + 2, j + 1] = dataGridView1.Rows[i].Cells[j].Value.ToString();
                }
            }
          
            ExcelApp.ActiveWorkbook.SaveCopyAs("C:\\Users\\user 9\\Downloads\\Export DataGridView to Excel\\Export DataGridView to Excel\\test.xls");
            ExcelApp.ActiveWorkbook.Saved = true;
         
            ExcelApp.Quit();
        }

Convert Number to Words using Web Service in Asp.Net

Introduction.
This sample code describes a Web service through which a client can get the equivalent of a number in words. This can be used in many applications such as accounting packages and invoices.

Requirements.
The following items describe the recommended hardware, software, network infrastructure, skills, prior knowledge, and service packs you will need.


  • Windows 2000 Server
  • IIS version 5.0
  • Internet Explorer 5.5 or 6.0 
To Get The Words For A Given Number.
By using this sample code in an IIS Server, we can have a web service which will
convert a given number into it's equivalent in words. For example, if you are in need of a code which converts a total amount into words, such as, for $ 43.25, if you need the words like Forty three dollars and twenty five cents, you can use this web service.
Here goes the sample code for the same.

******************START******************<%@ WebService Language="VB" Class="NumberToWords" %>Imports SystemImports System.CollectionsImports System.ComponentModelImports System.DataImports System.DiagnosticsImports System.WebImports System.Web.ServicesImports Microsoft.VisualBasic
Public Class NumberToWordsInherits System.Web.Services.WebService
<WebMethod(Description:="Gets the words for a Number", EnableSession:=
False)> _Public Function getWords(ByVal myNumber As String) As StringgetWords = SpellNumber(myNumber)End Function
'Main FunctionPrivate Function SpellNumber(ByVal MyNumber As String)Dim Dollars, Cents, TempDim DecimalPlace, CountDim Place(9) As StringPlace(2) = " Thousand "
Place(3) = " Million "
Place(4) = " Billion "
Place(5) = " Trillion "
' String representation of amountMyNumber = Convert.ToString(MyNumber)' Position of decimal place 0 if noneDecimalPlace = InStr(MyNumber, ".")'Convert cents and set MyNumber to dollar amountIf DecimalPlace > 0 ThenCents = GetTens(Left(Mid(MyNumber, DecimalPlace + 1) & "00", 2))
MyNumber = Trim(Left(MyNumber, DecimalPlace - 1))
End IfCount = 1Do While MyNumber <> ""
Temp = GetHundreds(Right(MyNumber, 3))
If Temp <> "" Then Dollars = Temp & Place(Count) & DollarsIf Len(MyNumber) > 3 ThenMyNumber = Left(MyNumber, Len(MyNumber) - 3)ElseMyNumber = ""End IfCount = Count + 1LoopSelect Case DollarsCase ""
Dollars = "zero Dollars"
Case "One"
Dollars = "One Dollar"
Case ElseDollars = Dollars & " Dollars"End SelectSelect Case CentsCase ""
Cents = " and zero Cents"
Case "One"
Cents = " and One Cent"
Case ElseCents = " and " & Cents & " Cents"End SelectSpellNumber = Dollars & CentsEnd Function'Converts a number from 100-999 into textPrivate Function GetHundreds(ByVal MyNumber As String)Dim Result As StringIf Val(MyNumber) = 0 Then Exit FunctionMyNumber = Right("000" & MyNumber, 3)'Convert the hundreds placeIf Mid(MyNumber, 1, 1) <> "0" ThenResult = GetDigit(Mid(MyNumber, 1, 1)) & " Hundred "End If'Convert the tens and ones placeIf Mid(MyNumber, 2, 1) <> "0" ThenResult = Result & GetTens(Mid(MyNumber, 2))ElseResult = Result & GetDigit(Mid(MyNumber, 3))End IfGetHundreds = ResultEnd Function
'Converts a number from 10 to 99 into text
Private Function GetTens(ByVal TensText As String)Dim Result As StringResult = "" 'null out the temporary function valueIf Val(Left(TensText, 1)) = 1 Then ' If value between 10-19Select Case Val(TensText)Case 10 : Result = "Ten"Case 11 : Result = "Eleven"Case 12 : Result = "Twelve"Case 13 : Result = "Thirteen"Case 14 : Result = "Fourteen"Case 15 : Result = "Fifteen"Case 16 : Result = "Sixteen"Case 17 : Result = "Seventeen"Case 18 : Result = "Eighteen"Case 19 : Result = "Nineteen"Case ElseEnd SelectElse ' If value between 20-99Select Case Val(Left(TensText, 1))Case 2 : Result = "Twenty "Case 3 : Result = "Thirty "Case 4 : Result = "Forty "Case 5 : Result = "Fifty "Case 6 : Result = "Sixty "Case 7 : Result = "Seventy "Case 8 : Result = "Eighty "Case 9 : Result = "Ninety "Case ElseEnd SelectResult = Result & GetDigit(Right(TensText, 1)) 'Retrieve ones placeEnd IfGetTens = ResultEnd Function
'Converts a number from 1 to 9 into text
Private Function GetDigit(ByVal Digit As String)Select Case Val(Digit)Case 1 : GetDigit = "One"Case 2 : GetDigit = "Two"Case 3 : GetDigit = "Three"Case 4 : GetDigit = "Four"Case 5 : GetDigit = "Five"Case 6 : GetDigit = "Six"Case 7 : GetDigit = "Seven"Case 8 : GetDigit = "Eight"Case 9 : GetDigit = "Nine"Case Else : GetDigit = ""End SelectEnd FunctionEnd Class'***************************END***********************************

For making this as a web service,

  1. Open your Notepad 
  2. Copy the code shown above and paste into the Notepad
  3. Save the file as NumberToWords.asmx into c:\InetPub\wwwroot folder in your System
  4. Run the web service by requesting for the file in the browser. (http://localhost/NumberToWords.asmx)
  5. Check the same by giving different numbers with decimals and invoking the service.

new features of wcf

This article explains about the new features introduced in WCF 4.0.
.Net framework comes with new features and improved areas of WCF. It was mainly focused on simplifying the developer experience, enabling more communication scenario and providing rich integration with WWF.
The following items specifies the new features of WCF 4.0
Simplified configuration
This new feature shows simplification of WCF configuration section by providing default endpoint, binding and behavior configuration. It is not mandatory to provide endpoint while hosting service. Service will automatically create new endpoint if it does find any endpoint while hosting service. These changes make it possible to host configuration-free services.
Discovery service
There are certain scenario in which endpoint address of the service will be keep on changing. In that kind of scenario, client who consume this service also need to change the endpoint address dynamically to identify the service. This can be achieved using WS-Discovery protocol.
Routing service
This new feature introduces routing service between client and actual business service. This intermediated service Act as broker or gateways to the actual business services and provides features for content based routing, protocol bridging and error handling

REST Service
There are few features helps while developing RESTful service.
  • Automatic help page that describes REST services to consumer
  • Support for declarative HTTP catching
Workflow service
  • Improves development experience
  • Entire service definition can be define in XAML
  • Hosting workflow service can be done from .xamlx file, without using .svc file
  • Introduce new “Context” bindings like BasicHttpContextBinding, WSHttpContextBinding, or NetTcpContextBinding
  • In .Net4.0, WorkflowServiceHost class for hosting workflow services was redesigned and it is available in System.ServiceModel.Activities assembly. In .Net3.5, WorkflowServiceHost class is available in System.WorkflowServices assembly
  • New messaging activities SendReply and ReceiveReply are added in .Net4.0
Conclusion:
This article explain new featues introduced in WCF 4.0

Specified Time Session Timeout And Redirect To Login Page In ASP.NET

Detecting Session Timeout and Redirect to Login Page in ASP.NET

In this example i'll explain how to detect session timeout and redirect to login page, session timeout occurs when user is idle for the time specified as Session timeout in web.config file using C# And VB.NET.

For this Example i've set time out value in web.config file to 1 minute.






1st Method
In web.config file, set the sessionstate mode to inproc and authentication mode to Forms
<system.web>
<compilation debug="true"/>
<authentication mode="Forms"/>
<sessionState mode="InProc" cookieless="false" timeout="1">
</sessionState>
</system.web> 

I've created three pages in this example , one is login page , when session expires , i redirect to this page , one is navigation page where i'll check if session is valid or not , if it is valid than only user will see this page other wise he gets redirected to login page.

Add Global.asax class file in root of your application or website.
This method works only if Global.asax is present in application.


Write below mentioned code in Page_Init event of the page where we want to check for session timeout.

we can also put this code in in a class and inherit all pages of application from this class acting as base class for all pages to check for session timeout.

C# CODE
protected void Page_Init(object sender, EventArgs e)
    {
        if (Context.Session != null)
        {
if (Session.IsNewSession)
            HttpCookie newSessionIdCookie = Request.Cookies["ASP.NET_SessionId"];
                if (newSessionIdCookie != null)
                {
                    string newSessionIdCookieValue = newSessionIdCookie.Value;
                    if (newSessionIdCookieValue != string.Empty)
                    {
                        // This means Session was timed Out and New Session was started
                        Response.Redirect("Login.aspx");
                    }
                }
            }
        }
    }

VB.NET CODE
Protected Sub Page_Init(sender As Object, e As EventArgs)
 If Context.Session IsNot Nothing Then
  If Session.IsNewSession Then
   Dim newSessionIdCookie As HttpCookie = Request.Cookies("ASP.NET_SessionId")
   If newSessionIdCookie IsNot Nothing Then
    Dim newSessionIdCookieValue As String = newSessionIdCookie.Value
    If newSessionIdCookieValue <> String.Empty Then
     ' This means Session was timed Out and New Session was started
     Response.Redirect("Login.aspx")
    End If
   End If
  End If
 End If
End Sub


2nd Method.
Code for Default.aspx
<%@ Page Language="C#" AutoEventWireup="true"
CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!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>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Button ID="btnSessionStart"
runat="server"
OnClick="btnSessionStart_Click"
Text="Start Session" /><br />
<br />
<br />
<asp:Button ID="btnCheck"
runat="server"
OnClick="btnCheck_Click"
Text="Check Session ID" />
<br />
<asp:TextBox ID="txtSession"
runat="server"
Width="266px">
</asp:TextBox><br />
<br />
<asp:Button ID="btnGO"
runat="server"
OnClick="btnGO_Click"
Text="Go to Other Page" />
<br />
<br />
</div>
</form>
</body>
</html>

And the code behind for this page is like
protected void btnSessionStart_Click
(object sender, EventArgs e)
{
Guid Session_id = Guid.NewGuid();
Session["SessionID"]
= Session_id.ToString();

}
protected void btnCheck_Click
(object sender, EventArgs e)
{
if (Session["SessionID"] != null)
txtSession.Text =
Session["SessionID"].ToString();
else
txtSession.Text =
"Session has expired";
}
protected void btnGO_Click
(object sender, EventArgs e)
{
Response.Redirect("Default2.aspx");
}

On the page where we want to check the session has timed out or not, we need to check it in the Page_Init event of the page , if session is not null than user will be able to go to the page other wise he will be redirected to login page.

In this page I've just put a button to go to home page
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Button ID="btnHome"
runat="server" OnClick="btnHome_Click"
Text="Home" /></div>
</form>
</body>
</html>

And the Code behind for this page is

protected void Page_Init(object sender, EventArgs e)
{
CheckSession();
}
protected void btnHome_Click(object sender, EventArgs e)
{
Response.Redirect("Default.aspx");
}

private void CheckSession()
{
if (Session["SessionID"] == null)
{
Response.Redirect("Login.aspx");
}

}

If we need to check this in all the pages of application than we can create a BaseClass and write the above mentioned code of CheckSession and Page_Init part and drive all ur pages from this class by typing BaseClassName in place of System.Web.UI.Page and it will check all pages for session timeout every time page is loaded