Search This Blog

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


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


Anonymous Types

Anonymous types provide a convenient way to encapsulate a set of read-only properties into a single object without having to explicitly define a type first. The type name is generated by the compiler and is not available at the source code level. The type of each property is inferred by the compiler.
In typical C# you will always carefully spell out your definitions:
string MyString = “Rashmi Kant”;
From the right side of the declaration it is obvious that only one type (string) will ever match this definition. So instead of us doing the work, why not let the compiler figure this out?
var MyString = “Rashmi Kant”;
The above definition will also create a string variable named “MyString”. It is important to note that C# is still strongly typed — unlike scripted languages such as Visual Basic (or PHP) once you have assigned the variable type it sticks. The following will not work:
var MyString2 = “Rashmi Kant”;
MyString2 = 123; //error
The compiler will throw an implicit conversion error as 123 cannot be assigned to a string.
The above was an impressive (if somewhat pointless) example of what an anonymous type is. For simple types such as strings, integer etc anonymous types offer little benefits.
You can create an array of anonymously typed elements by combining an implicitly typed local variable and an implicitly typed array, as shown in the following example.
var anonArray = new[] { new { name = "apple", diam = 4 }, new { name = "grape", diam = 1 }};
Other Example of anonymous class
var person0 = new
{
    FirstName = "Rashmi",
    LastName = "Kant",
    Height = 172
};
var person1 = new
{
    FirstName = "John",
    LastName = "Doe",
    Height = 165
};
var person2 = new
{
    LastName = "Doe",
    FirstName = "John",
    Height = 175
};
var Employee = new { ID = 5, Name= "Rashmi" };
 
Projection in  Anonymous types
Anonymous types also support Projection. So, if we have a declaration as shown below 
var LastName = "Nurk";
var FirstName = "Fred";
var person4 = new { LastName, FirstName};
then a new Anonymous type will be created with the read only properties LastName and FirstName. C# automatically projects the names of the variables to the names of properties in the anonymous class.
This also works while using objects, as shown below –
Person personObject = new Person
{
    LastName = "Doe",
    FirstName = "Jane",
    Height = 156
};
var projectionFromClass = new
{
    personObject.FirstName,
    personObject.LastName
};
In this case, the object projectionFromClass will have an anonymous type that picks up the property names FirstName and LastName, which will hold the values “Jane” and “Doe”.
Usage rules/restrictions
The properties in Anonymous types are all read only and therefore cannot be modified once they are created.
Anonymous types cannot have methods.
Anonymous types are always assigned to vars. This allows the compiler to assign the right type. But, if Anonymous types are used as return values or as parameters in a function, they will have to be passed in as Objects, as var is not a proper type.

Tuesday, February 14, 2012

Asp.net Saving Image in binary into database table in Sql 2005/2008

In this article, I am going to explain how to store image file in database. for this I am using Northwind database and product table.
In this implementation, I have added a  column ProductImage of image datatype for storing the image of each product.

ALTER TABLE Products ADD ProductImage IMAGE


Html Code in aspx part
The code is very simple - the web page contains a text box for getting the Product Id of the record and a file upload control in the page and A button. 

<h2>
       Save Image in Database
    </h2>
    <div>
    <table>
        <tr>
            <td style="vertical-align:top">Product ID</td>
            <td><asp:TextBox ID="txtProductID" runat="server" Width="100px"></asp:TextBox></td>
        </tr>
        <tr>
            <td>Image</td>
            <td><asp:FileUpload runat="server" ID="fuImage" Width="400px" /> </td>
        </tr>
        <tr>
            <td colspan="2" style="text-align:center">
                <asp:Button ID="btnSave" runat="server" Width="80px" Text="Save"
                    onclick="btnSave_Click" />
            </td>
        </tr>
    </table>
</div>
On click of Save button on the page, below code executed
protected void btnSave_Click(object sender, EventArgs e)
        {
            if ((fuImage.PostedFile.FileName.Trim().Length > 0) &&
                (fuImage.PostedFile != null))
            {
                byte[] image = new byte[fuImage.PostedFile.ContentLength];

                fuImage.PostedFile.InputStream.Read(image, 0, (int)fuImage.PostedFile.ContentLength);


                SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["SQLConnection"].ConnectionString);

                SqlCommand command = new SqlCommand();
                command.CommandText = "Update Products set ProductImage = @Image where ProductID = '" + txtProductID.Text + "'";

                command.CommandType = CommandType.Text;
                command.Connection = connection;

                PrepareSQLParameter(command, "@Image", SqlDbType.Image, image.Length, image);

                connection.Open();

                int result = command.ExecuteNonQuery();
                connection.Close();

                txtProductID.Text = "";
            }

        }

        private SqlParameter  PrepareSQLParameter(SqlCommand command, string parameterName, SqlDbType parameterType, int parameterLength, object parameterValue)
        {
            SqlParameter parameter = new SqlParameter(parameterName, parameterType, parameterLength);
            parameter.Value = parameterValue;

            command.Parameters.Add(parameter);
            return parameter;
        }