Monday, July 22, 2013

Saving File To Database

Database Table: 

CREATE TABLE [dbo].[Documents](

[DocumentId] [int] IDENTITY(1,1) NOT NULL CONSTRAINT [PK_Documents] PRIMARY KEY,

[DocumentData] [varbinary](max) NOT NULL,

[DocumentName] [varchar](50) NOT NULL,

[DocumentType] [varchar](50) NOT NULL,

 )

In View,
We need a File Upload control for uploading the file.

 @using (Html.BeginForm("Index", "UploadFile", FormMethod.Post, new { enctype = "multipart/form-data" }))
        {
            < input id="postedFile" name="postedFile" type="file" />
            < input title="Upload File" type="submit" value="Upload File" />
        }

Here UploadFile is the Controller and Index is the action method. "enctype" is important attribute for uploading documents. 

In Controller,
[HttpPost]
public ActionResult Index(HttpPostedFileBase postedFile)
{
   int fileSize = postedFile.ContentLength;
   string fileName = Path.GetFileName(postedFile.FileName);

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

   SqlCommand cmd = new SqlCommand();               
   cmd.CommandText = "INSERT INTO Documents(DocumentName,DocumentType,DocumentData)" +
                                  " VALUES (@DocName,@Type,@DocData)";
    cmd.CommandType = CommandType.Text;
                cmd.Connection = connection;

                SqlParameter DocName = new SqlParameter("@DocName", SqlDbType.VarChar, 50);
                DocName.Value = fileName.ToString();
                cmd.Parameters.Add(DocName);

                SqlParameter Type = new SqlParameter("@Type", SqlDbType.VarChar, 50);
                Type.Value = postedFile.ContentType.ToString();
                cmd.Parameters.Add(Type);

                byte[] documentbinary = new byte[fileSize];
                postedFile.InputStream.Read(documentbinary, 0, fileSize);

                SqlParameter uploadedDocument = new SqlParameter("@DocData", SqlDbType.Binary, fileSize);
                uploadedDocument.Value = documentbinary;
                cmd.Parameters.Add(uploadedDocument);

                connection.Open();
                int result = cmd.ExecuteNonQuery();
                connection.Close();
}
   

Wednesday, October 14, 2009

Enterprise Library - Exception Handling and Logging

Exception handling is one of the key points in any Application. Exception should be handled such that we have to know the source of exception clearly and we can directly point the issue. Whatever exceptions raised first we have to save it some place. This is can be handled using "Logging Application Block" of Enterprise Library.

Exceptions can be of any type. Suppose you want to log only SQL Exceptions. This is can also be done.

First step of Exception handling and Logging, is creating of Exception Handling Application block.

After creating a exception handling application block.

Now right click Exception Handling Application Block -> New -> Exception Policy
Now change the name to a meaningful name. I have given it as "LogPolicy".
Now right click "LogPolicy" -> New -> ExceptionType.
It will display a list of exception which are to be handled by "LogPolicy".


I have choosen "Exception", its obvious that it will handle any exception.
Now right click "Exception" -> New -> Logging Handler

Now click "logging handler" -> Formatter Type
Here I choose the TextExceptionFormatter


Now click "Log Category" -> U will a drop down which points to the Logging Application Block -> Category Sources-> General - Select it

Under Logging Application Block -> Special Sources -> Logging Errors & Warnings -> Formatted Eventlog TraceListener tells that the Logging is done to System Event Viewer - Application

Upon saving this as Web.config or App.config, Enterprise library configuration will generate respective XML in it.

Using it Code:
using Microsoft.Practices.EnterpriseLibrary.ExceptionHandling;
using Microsoft.Practices.EnterpriseLibrary.Logging;

try
{

}
catch (Exception ex)
{
bool rethrow = ExceptionPolicy.HandleException(ex, "LogPolicy");
if (rethrow)
throw;
return;
}

Sunday, December 21, 2008

Enterprise Library - Data Access Application Block

When u install the Enterprise Library Application Block, Enterprise Library Configuration application also be installed in it. In order to create the Data Access Application Block for your Application, Please follow the steps below.


Sunday, November 23, 2008

Microsoft Enterprise Library 3.1 for Web and Windows

While developing any application, We first frame the application architecture i.e dividing the application into different modules or sub projects. There are several predefined application architecture.
But the application architecture should be based on the type of application what we are developing.
Very common application architecture is
0. Data access layer
1. Business Logic
2. Web Service Layer
3. UI Layer
4. Common Layer

The main purpose of Data access layer is same for all application i.e doing CRUD ( Create, Read, Update, Delete) operations. This Enterprise Library will provide blocks to achieve this functionality.

The Enterprise Library is a collection of application blocks intended for use by developers who build complex, enterprise-level applications. These applications are typically deployed widely and have interdependencies with other application and systems.
The Enterprise Library 3.1 release contains the following application blocks:

1. Caching Application Block: Developers can use this application block to incorporate a local cache in their applications.
2. Cryptography Application Block: Developers can use this application block to incorporate hashing and symmetric encryption in their applications.
3. Data Access Application Block: Developers can use this application block to incorporate standard database functionality in their applications.
4. Exception Handling Application Block: Developers and policy makers can use this application block to create a consistent strategy for processing exceptions that occur throughout the architectural layers of enterprise applications.
5. Logging Application Block: Developers can use this application block to include standard logging functionality in their applications.
6. Security Application Block: Developers can use this application block to incorporate authorization and security caching functionality in their applications.
7. Validation Application Block: Developers can use this application block to create validation rules for business objects that can be used across different layers of their applications.
8. Policy Injection Application Block: Developers can use this application block to implement interception policies that can be used to streamline the implementation of common features, such as logging, caching, exception handling, and validation, across an application.

Mostly i used Security, Exception Handling, Data Access, Logging. In my future articles i will provide how to use these blocks on Web and Windows applications.

Wednesday, November 12, 2008

Thanks to My Parents, Teachers and Friends

మాతృదేవో భవ
పితృదేవో భవ
ఆచార్యదేవో భవ
అతిధిదేవో భవ
I am starting this blog by thanking my parents, teachers and friends.

Ajax Libraries

Ajax a commonly used word web technologies. Ajax's core based purly javascript web calls i.e A request will be made from the javascript using XMLHTTPRequest Object. But it involves a lot of javascript coding.
Developers are lazy (Me too) so try to get the things done ASAP with less work. So mainly concentrated on the Javascript libraries for Ajax. Some of the libraries which i want share are

Ajax .NET Professional: This is developed by Micharl Schwartz as a tool primarily used to simplify the data transport mechanism that enables a client javascript routine to communicate with a server program. The source code is available and the package is free.

DoJo: The DoJo toolkit is a client-side library for AJAX developement without ties to any server technology. DoJo has a type system for Javascript and a function for binding script to events from javascript objects or DHTML elements.

Prototype: Prototype script library does not target any server technology for integration. It has a type system for scripting in a more object-priented way along with some shortcut syntaxes for dealing with javascript arrays as well as accessing and manipulating HTML elements on the page.

Ajax.NET: This is an extension for the microsoft web technology ASP.NET 2.0 and integrated part of ASP.NET 3.0 or above.