Search This Blog

Friday, August 10, 2012

Asp.net:secure web-service in Ajax 1.0



This article can be used for .net 1.0(Vs2003) to secure webservices which is called on aspx page throgh core AJAX like xmlhttp. in this article no .net ajax component is used but it can be used for .net2.5 and 3.0 2005 and 2008 with a little bit trick which I will give in my next post.
on aspx page.

you have set the header. and call the web service using get method.
hope this help 
if you find any difficulties  please post your comment.
xmlhttp.setRequestHeader('securityTicket' , SECURITY_TICKET );

on aspx.vb page

Private Sub GenerateSecurityTicket()
        Dim cacheKey As String = User.Identity.Name + ":securityTicket"
        Dim securityTicket As String = Guid.NewGuid().ToString()

        Cache(cacheKey) = securityTicket

        Dim script As String = "<script type=""text/javascript"">" + String.Format("SECURITY_TICKET = '{0}';", securityTicket) + "</script>"

        Page.RegisterClientScriptBlock("securityKey", script)
    End Sub

page_load()
GenerateSecurityTicket()
end sub


asmx Page

Private Sub EnsureTicket()
        Dim context As HttpContext = HttpContext.Current

        Dim headerTicket As String = context.Request.Headers("securityTicket")

        If headerTicket Is Nothing Or headerTicket = String.Empty Then
            Throw New System.Exception("Security ticket must be present.")
        End If

        Dim cacheKey As String = context.User.Identity.Name + ":securityTicket"
        Dim cacheTicket As String = DirectCast(context.Cache(cacheKey), String)

        If String.Compare(headerTicket, cacheTicket, False) <> 0 Then
            Throw New System.Exception("Security ticket mismatched.")
        End If
    End Sub


call EnsureTicket()

from every webmethod

Thursday, March 15, 2012

Sohel's Blog: SharePoint 2010: Add/Delete/update/search list ite...

Sohel's Blog: SharePoint 2010: Add/Delete/update/search list ite...: Managed client Object model is a rich extension to SharePoint 2010. You can almost perform all kinds operations against SharePoint using Cli...

Friday, February 24, 2012

Sudoku list generation program in C-sharp


This is really a  very good program , fast and optimize

class Program
    {
        static void Main(string[] args)
        {

            const int n = 3;

            for (int i = 0; i < n * n; i++)
            {
                for (int j = 0; j < n * n; j++)
                    Console.Write((i * n + i / n + j) % (n * n) + 1);
                Console.WriteLine();
            } Console.ReadLine();
        }
    }

Wednesday, February 22, 2012

Abstract Factory Pattern in .Net with Example (C#)...

Abstract Factory Pattern in .Net with Example (C#)...: Abstract Factory Pattern Abstract Factory pattern is used to create concrete class instances without specifying the exact class type (ie, to...

Tuesday, February 21, 2012

Asp.net: Binding Image in gridview using Handler from image column in databse sql2005/2008


In my pervious article
you have learn how to save image file in binary format in a database column.
In this  post I going to fetch those (Northwind databse product table) record and bind into a grid view. For this I have created a generic handler for binding the image on gridview image control here the code below

HTML PART

<h2>Show the images in the GridView</h2>
 <asp:GridView ID="grdViewProducts" runat="server"
    AllowPaging="True" AutoGenerateColumns="False" TabIndex="1"
    DataKeyNames="ProductID" Width="100%" BackColor="White"
    CellPadding="3" BorderStyle="Solid" BorderWidth="1px"
    BorderColor="Black" GridLines="Horizontal" PageSize="10"
    onpageindexchanging="grdViewProducts_PageIndexChanging">
    <Columns>
        <asp:TemplateField HeaderText="Photo">
            <ItemStyle Width="10%" HorizontalAlign="Center" />
            <ItemTemplate>
                <img id="imgPhoto" src="GetDBImage.ashx?ProductID=<%# Eval("ProductID") %>"
                    width="125px" height="125px" title="<%# Eval("ProductName") %>" />
            </ItemTemplate>
        </asp:TemplateField>
        <asp:BoundField DataField="ProductName" HeaderText="Product Name" >
            <ItemStyle Width="30%" />
        </asp:BoundField>
        <asp:BoundField DataField="CompanyName" HeaderText="Supplier" >
            <ItemStyle Width="25%" />
        </asp:BoundField>
        <asp:BoundField DataField="CategoryName" HeaderText="Category" >
            <ItemStyle Width="20%" />
        </asp:BoundField>
        <asp:BoundField DataField="QuantityPerUnit" HeaderText="Quantity Per Unit">
            <ItemStyle Width="15%" />
        </asp:BoundField>
        <asp:BoundField DataField="UnitPrice" HeaderText="UnitPrice" DataFormatString="{0:#0.00}">
            <ItemStyle Width="15%" />
        </asp:BoundField>
    </Columns>
    <RowStyle BackColor="White" ForeColor="#333333" />
    <FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
    <PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Right" />
    <SelectedRowStyle BackColor="#A5D1DE" Font-Bold="true" ForeColor="#333333" />
    <HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
    <AlternatingRowStyle BackColor="#E2DED6" ForeColor="#284775" />
</asp:GridView>


C# Code


  protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
                BindGrid();
        }

private void BindGrid()
        {
            using (SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["SQLConnection"].ConnectionString))
            {

                SqlCommand command = new SqlCommand(
                        "SELECT ProductID, ProductName, CompanyName, CategoryName, " +
                        "QuantityPerUnit, UnitPrice FROM Products " +
                        "JOIN Suppliers ON Products.SupplierID = Suppliers.SupplierID " +
                        "JOIN Categories ON Products.CategoryID = Categories.CategoryID ", connection);

                connection.Open();
                SqlDataReader dr = command.ExecuteReader(CommandBehavior.CloseConnection);

                IList<ProductView> productViewList = new List<ProductView>();
                while (dr.Read())
                {
                    ProductView productView = new ProductView();
                    productView.ProductID = Convert.ToInt32(dr["ProductID"].ToString());
                    productView.ProductName = dr["ProductName"].ToString();
                    productView.CompanyName = dr["CompanyName"].ToString();
                    productView.CategoryName = dr["CategoryName"].ToString();
                    productView.QuantityPerUnit = dr["QuantityPerUnit"].ToString();
                    productView.UnitPrice = Convert.ToDouble(dr["UnitPrice"].ToString());
                    productViewList.Add(productView);
                }
                grdViewProducts.DataSource = productViewList;
                grdViewProducts.DataBind();
            }
        }

        protected void grdViewProducts_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            grdViewProducts.PageIndex = e.NewPageIndex;
            BindGrid();
        }
    }
    public class ProductView
    {
        public int ProductID { get; set; }
        public string ProductName { get; set; }
        public string CompanyName { get; set; }
        public string CategoryName { get; set; }
        public string QuantityPerUnit { get; set; }
        public double UnitPrice { get; set; }
    }


Handler Code for Image Creation from database
public class GetDBImage : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            using (SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["SQLConnection"].ConnectionString))
            {
                SqlCommand command = new SqlCommand("Select ProductImage from Products where ProductID = '" + context.Request.QueryString["ProductID"] + "'", connection);

                connection.Open();
                SqlDataReader dr = command.ExecuteReader(CommandBehavior.CloseConnection);
                while (dr.Read())
                {
                    if (dr["ProductImage"].ToString().Length > 0)
                    {
                        context.Response.BinaryWrite((byte[])dr["ProductImage"]);
                    }
                }
            }
        }
        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }


here is the output




Thursday, February 16, 2012

File or folder uploading using FTP in c#.net


In this post I am using FTP to upload or download a folder or file into server

FtpWebRequest Class



using System;
using System.Net;
using System.Threading;

using System.IO;
namespace Examples.System.Net
{
    public class FtpState
    {
        private ManualResetEvent wait;
        private FtpWebRequest request;
        private string fileName;
        private Exception operationException = null;
        string status;

        public FtpState()
        {
            wait = new ManualResetEvent(false);
        }

        public ManualResetEvent OperationComplete
        {
            get {return wait;}
        }

        public FtpWebRequest Request
        {
            get {return request;}
            set {request = value;}
        }

        public string FileName
        {
            get {return fileName;}
            set {fileName = value;}
        }
        public Exception OperationException
        {
            get {return operationException;}
            set {operationException = value;}
        }
        public string StatusDescription
        {
            get {return status;}
            set {status = value;}
        }
    }
    public class AsynchronousFtpUpLoader
    { 
        // Command line arguments are two strings:
        // 1. The url that is the name of the file being uploaded to the server.
        // 2. The name of the file on the local machine.
        //
        public static void Main(string[] args)
        {
            // Create a Uri instance with the specified URI string.
            // If the URI is not correctly formed, the Uri constructor
            // will throw an exception.
            ManualResetEvent waitObject;

            Uri target = new Uri (args[0]);
            string fileName = args[1];
            FtpState state = new FtpState();
            FtpWebRequest request = (FtpWebRequest)WebRequest.Create(target);
            request.Method = WebRequestMethods.Ftp.UploadFile;

            // This example uses anonymous logon.
            // The request is anonymous by default; the credential does not have to be specified.
            // The example specifies the credential only to
            // control how actions are logged on the server.

            request.Credentials = new NetworkCredential ("anonymous","janeDoe@contoso.com");

            // Store the request in the object that we pass into the
            // asynchronous operations.
            state.Request = request;
            state.FileName = fileName;

            // Get the event to wait on.
            waitObject = state.OperationComplete;

            // Asynchronously get the stream for the file contents.
            request.BeginGetRequestStream(
                new AsyncCallback (EndGetStreamCallback),
                state
            );

            // Block the current thread until all operations are complete.
            waitObject.WaitOne();

            // The operations either completed or threw an exception.
            if (state.OperationException != null)
            {
                throw state.OperationException;
            }
            else
            {
                Console.WriteLine("The operation completed - {0}", state.StatusDescription);
            }
        }
        private static void EndGetStreamCallback(IAsyncResult ar)
        {
            FtpState state = (FtpState) ar.AsyncState;

            Stream requestStream = null;
            // End the asynchronous call to get the request stream.
            try
            {
                requestStream = state.Request.EndGetRequestStream(ar);
                // Copy the file contents to the request stream.
                const int bufferLength = 2048;
                byte[] buffer = new byte[bufferLength];
                int count = 0;
                int readBytes = 0;
                FileStream stream = File.OpenRead(state.FileName);
                do
                {
                    readBytes = stream.Read(buffer, 0, bufferLength);
                    requestStream.Write(buffer, 0, readBytes);
                    count += readBytes;
                }
                while (readBytes != 0);
                Console.WriteLine ("Writing {0} bytes to the stream.", count);
                // IMPORTANT: Close the request stream before sending the request.
                requestStream.Close();
                // Asynchronously get the response to the upload request.
                state.Request.BeginGetResponse(
                    new AsyncCallback (EndGetResponseCallback),
                    state
                );
            }
            // Return exceptions to the main application thread.
            catch (Exception e)
            {
                Console.WriteLine("Could not get the request stream.");
                state.OperationException = e;
                state.OperationComplete.Set();
                return;
            }

        }

        // The EndGetResponseCallback method 
        // completes a call to BeginGetResponse.
        private static void EndGetResponseCallback(IAsyncResult ar)
        {
            FtpState state = (FtpState) ar.AsyncState;
            FtpWebResponse response = null;
            try
            {
                response = (FtpWebResponse) state.Request.EndGetResponse(ar);
                response.Close();
                state.StatusDescription = response.StatusDescription;
                // Signal the main application thread that
                // the operation is complete.
                state.OperationComplete.Set();
            }
            // Return exceptions to the main application thread.
            catch (Exception e)
            {
                Console.WriteLine ("Error getting response.");
                state.OperationException = e;
                state.OperationComplete.Set();
            }
        }
    }
}



public static bool DeleteFileOnServer(Uri serverUri)
{
    // The serverUri parameter should use the ftp:// scheme.
    // It contains the name of the server file that is to be deleted.
    // Example: ftp://contoso.com/someFile.txt.
    // 

    if (serverUri.Scheme != Uri.UriSchemeFtp)
    {
        return false;
    }
    // Get the object used to communicate with the server.
    FtpWebRequest request = (FtpWebRequest)WebRequest.Create(serverUri);
    request.Method = WebRequestMethods.Ftp.DeleteFile;

    FtpWebResponse response = (FtpWebResponse) request.GetResponse();
    Console.WriteLine("Delete status: {0}",response.StatusDescription);  
    response.Close();
    return true;
}

Wednesday, February 15, 2012

Anonymous Type IN C# .NET3.0/4.0 Part2


Anonymous Functions

An anonymous function is an "inline" statement or expression that can be used wherever a delegate type is expected. You can use it to initialize a named delegate or pass it instead of a named delegate type as a method parameter.

There are two kinds of anonymous functions

1)   Lambda Expressions 
A lambda expression is an anonymous function that can contain expressions and statements, and can be used to create delegates or expression tree types.

All lambda expressions use the lambda operator =>, which is read as "goes to". The left side of the
lambda operator specifies the input parameters (if any) and the right side holds the expression or statement block. The lambda expression x => x * x is read "x goes to x times x." This expression can
be assigned to a delegate type as follows:
delegate int del(int i);
static void Main(string[] args)
{
    del myDelegate = x => x * x;
    int j = myDelegate(5); //j = 25
}


using System.Linq.Expressions;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            Expression<del> myET = x => x * x;
        }
    }
}
A lambda expression with an expression on the right side is called an expression lambda. Expression lambdas are used extensively in the construction of Expression Trees. An expression lambda returns the result of the expression and takes the following basic form:

(x, y) => x == y
 In the above example its take two parameter and compare and return a Boolean value

A statement lambda resembles an expression lambda except that the statement(s) is enclosed in braces:

delegate void TestDelegate(string s);
TestDelegate myDel = n => { string s = n + " " + "World"; Console.WriteLine(s); };
myDel("Hello");

note: Statement lambdas, like anonymous methods, cannot be used to create expression trees.

The general rules for lambdas are as follows:
·         The lambda must contain the same number of parameters as the delegate type.
·         Each input parameter in the lambda must be implicitly convertible to its corresponding delegate parameter.
·         The return value of the lambda (if any) must be implicitly convertible to the delegate's return type.

A standard query operator, the Count method
int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 };
int oddNumbers = numbers.Count(n => n % 2 == 1);
The compiler can infer the type of the input parameter, or you can also specify it explicitly. This particular lambda expression counts those integers (n) which when divided by two have a remainder of 1.
The following method will produce a sequence that contains all the elements in the numbers array that are to the left of the 9, because that is the first number in the sequence that does not meet the condition:
var firstNumbersLessThan6 = numbers.TakeWhile(n => n < 6);

Anonymous Type IN C# .NET3.0/4.0 Part1