Quote for the Week

"Learn to enjoy every moment of your life"

Wednesday, September 17, 2014

Object-Oriented Programming Concepts in.NET



Classes, Objects, and Structures in .NET


Summary

The following article kicks off a three-part article series that will present definitions and samples for different Object-Oriented Programming concepts and its implementation in .NET. The first part will examine the concepts of classes, objects, and structures. The second part will examine the concepts of inheritance, abstraction, and polimorphism. The third and last part will examine the concepts of interface, multiple interface inheritance, collections, and overloading.

Introduction

Object-Oriented Programming (OOP) is a software development paradigm that suggests developers to split a program in building blocks known as objects. The OOP paradigm allows developers to define the object’s data, functions, and its relationship with other objects.

Microsoft created the .NET Framework using OOP, and knowing this concepts has helped me to understand the .NET Framework and to design and develop better software components. The purpose of this article is to describe the basic OOP concepts using real world scenarios and to provide some code samples that demonstrate how to work with OOP and .NET.

Class

The most common definition states that a class is a template for an object. Suppose that someone builds a paper pattern for a shirt. All the shirts done with the same paper pattern will be identical (same design, size, etc.). In this sample, the paper pattern is the class and the shirt is the object. To build the same exact shirt over and over, you need the paper pattern as a template.  Another great example are house plans and blueprints. The plans and blueprints define the number of rooms, the size of the kitchen, the number of floors, and more. In this real world sample, the house plans and blueprints are the class and the house is the object. In OOP you program a class as a template for a specific object or groups ob objects that will always have the same features.

Class members

A class has different members, and developers in Microsoft suggest to program them in the following order:

Namespace: 
The namespace is a keyword that defines a distinctive name or last name for the class. A namespace categorizes and organizes the library (assembly) where the class belongs and avoids collisions with classes that share the same name.

Class declaration: Line of code where the class name and type are defined.

Fields: Set of variables declared in a class block.

Constants: Set of constants declared in a class block.

Constructors: A method or group of methods that contains code to initialize the class.

Properties: The set of descriptive data of an object.

Events: Program responses that get fired after a user or application action.

Methods: Set of functions of the class.

Destructor: A method that is called when the class is destroyed. In managed code, the Garbage Collector is in charge of destroying objects; however, in some cases developers need to take extra actions when objects are being released, such as freeing handles or deallocating unmanaged objects. In .NET, there is no concept of deterministic destructors. The Garbage Collector will call the Finalize() method at a non-deterministic time while reclaiming memory for the application.

Access keywords:Access keywords define the access to class members from the same class and from other classes. The most common access keywords are:

Public: Allows access to the class member from any other class.

Private: Allows access to the class member only in the same class.

Protected: Allows access to the class member only within the same class and from inherited classes.

Internal: Allows access to the class member only in the same assembly.

Protected internal: Allows access to the class member only within the same class, from inherited classes, and other classes in the same assembly.

Static: Indicates that the member can be called without first instantiating the class.

The following sample code illustrates a sample class in C#:

/// C#
///Imported namespaces
using System;

/// Namespace: Consider using CompanyName.Product.ComponentType
namespace DotNetTreats.OOSE.OOP_CSharp {
    
    ///Class declaration
    public class employee {
    
        ///Fields
        private string _name;
        private int _salary;
        
        ///Constants
        private const int anualBonus = 1000;
        
        ///Constructor
        public employee(){
        }

        ///Properties
        public string Name {
            get {
                return _name;
            }
            set {
                _name = value;
            }
        }
        public int Salary {
            get {
                return _salary;
            }
            set {
                _salary = value;
            }
        }

        /// Event handlers
        public event EventHandler OnPromotion {
            add {
            }
            remove {
            }
        }

        /// Methods
        public void DuplicateSalary() {
            _salary = _salary*2;
        }

    }
}

Object


Objects are the building blocks of OOP and are commonly defined as  variables or data structures that encapsulate behavior and data in a programmed unit. Objects are items that can be individually created, manipulated, and represent real world things in an abstract way.

Object composition

Every object is composed by:

Object identity: Means that every object is unique and can be differentiated from other objects.  Each time and object is created (instantiated) the object identity is defined.
Object behavior: What the object can do. In OOP, methods work as functions that define the set of actions that the object can do.
Object state: The data stored within the object at any given moment. In OOP, fields, constants, and properties define the state of an object.
Structures

Not everything in the real world should be represented as a class. Structures are suitable to represent lightweight objects. Structures can have methods and properties and are useful for defining types that act as user-defined primitives, but contain arbitrary composite fields. The .NET Framework defines some structures such as System.Drawing.Rectangle, System.Drawing.Point, and System.Drawing.Color.

The following code sample represents a structures in C#:

/// C#
struct Point {
    private int _x;
    private int _y;

    Point(int x, int y){
        this._x = x;
        this._y = y;    
    }

    public int X {
        get {
            return _x;
        }
        set {
            _x = value;
        }
    }

    public int Y {
        get {
            return _y;
        }
        set {
            _y = value;
        }
    }
}

Conclusion

OOP is full of abstract concepts, and the best approach to understand them is practical and not only theoretical. I learned more OOP after making some designs and after implementing some components. The concepts presented in this article might clarify the meaning, but I strongly recommend to go and have fun playing around with OOP. In this article, I examined the concept of classes, objects, and structs. The second part will examine the concepts of inheritance, abstraction, and polimorphism.

Reference

Matt Weisfeld,  The Object-Oriented Thought Process, SAMS, 2000.
Don Box, Chris Sells,  Essential .NET, Addison-Wesley, 2002.

Tuesday, September 16, 2014

How to Store and Retrieve images from SQL server database using asp.net?


Introduction


In this article, I will show you how to store images into sql server table and display in gridview control in the page using asp.net and sql server stored procedure.


Prepare Database Table and store procedure:


First design the database table and stored procedure to store and retrieve image information from database table. Execute the below table and store procedure script into your test database before design your asp.net page.

CREATE TABLE [dbo].[tblUploadedImagedetails](
 [ImageID] [int] IDENTITY(1,1) NOT NULL,
 [ImageName] [varchar](100) NOT NULL,
 [ImageContent] [image] NOT NULL,
 [Createdby] [varchar](100) NOT NULL,
 [CreatedDt] [datetime] NOT NULL,
 [Updatedby] [varchar](100) NULL,
 [UpdatedDt] [datetime] NULL,
 [Active] [bit] NOT NULL
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]


Below sql server stored procedure will be used to insert the images details, select all images from database and select specific image from table based on image id.


SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROC [dbo].[SP_ImageUpload]
(        
@pvchImageId   int  =0,        
@pvchImageName  varchar(100)=null,        
@pvchImage   image=null,        
@pvchCreatedBy  varchar(100)=null,        
@pvchAction   varchar(50)=null,        
@pIntErrDescOut  int output
)        
AS        
BEGIN        
  if(@pvchAction='select' and @pvchImageId=0)     
  begin
   select ROW_NUMBER()OVER (ORDER BY ImageID) as rowid ,ImageID, ImageName, ImageContent from tblUploadedImagedetails
   ;
  end
   if(@pvchAction='select' and @pvchImageId!=0)     
  begin
   select ROW_NUMBER()OVER (ORDER BY ImageID) as rowid ,ImageID, ImageName, ImageContent from tblUploadedImagedetails
   where ImageID = @pvchImageId;
  end
  else if(@pvchAction='insert')
  begin
  
  INSERT INTO tblUploadedImagedetails(ImageName,ImageContent,Createdby,CreatedDt,active)
  VALUES(@pvchImageName,@pvchImage,@pvchCreatedBy,GETDATE(),1);
  end
    IF (@@ERROR <> 0)         
   BEGIN         
  SET @pIntErrDescOut = 1        
   END        
  ELSE        
   BEGIN        
  SET @pIntErrDescOut = 0        
   END    
END

ASP.NET project


Create an asp.net project and drag the file upload to upload images and gridvew control to display the stored images into the aspx page. Take the below code and place into your aspx page.

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="SaveImagesToDB._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></title>
</head>

<body>
    <form id="form1" runat="server">

    <div>
        <h2 style="color: #0066FF; font-weight: bold;">
            <u>Save Image to SQL server</u></h2>
    </div>

    <div>
        <asp:FileUpload ID="ImageUploadToDB" Width="300px" runat="server" />
        <asp:Button ID="btnUploadImage" runat="server" Text="Save Image to DB" OnClick="btnUploadImage_Click"
            ValidationGroup="vg" /><br />

        <br />
        <asp:Label ID="lblMsg" runat="server" ForeColor="Green" Text=""></asp:Label>
        <h2 style="text-decoration: underline; font-weight: bold; color: #0066FF;">
            Image list Details
        </h2>
        <asp:GridView ID="GridViewUploadedImageFile" runat="server" EmptyDataText="No files found!"
            AutoGenerateColumns="False" Font-Names="Verdana" AllowPaging="true" PageSize="5"
            Width="40%" OnPageIndexChanging="GridViewUploadedImageFile_PageIndexChanging"
            BorderColor="#CCCCCC" BorderStyle="Solid" BorderWidth="1px" OnRowDataBound="GridViewUploadedImageFile_RowDataBound"
            DataKeyNames="ImageID,ImageContent">

            <AlternatingRowStyle BackColor="#FFD4BA" />

            <HeaderStyle Height="30px" BackColor="#FF9E66" Font-Size="15px" BorderColor="#CCCCCC"     BorderStyle="Solid" BorderWidth="1px" />

            <RowStyle Height="20px" Font-Size="13px" HorizontalAlign="Center" BorderColor="#CCCCCC" BorderStyle="Solid"         BorderWidth="1px" />
            <Columns>
                <asp:BoundField DataField="rowid" HeaderText="#" HeaderStyle-Width="10%" />
                <asp:BoundField DataField="ImageID" HeaderText="#" Visible="false" HeaderStyle-Width="10%" />               
                <asp:BoundField DataField="ImageName" HeaderText="Image Name" HeaderStyle-Width="25%" />
                <asp:TemplateField HeaderText="List of Images" HeaderStyle-Width="40%">
                    <ItemTemplate>
                        <asp:Image ID="UsrImages" runat="server" Height="35px" Width="35px" />
                    </ItemTemplate>
                </asp:TemplateField>
            </Columns>
        </asp:GridView>
    </div>
    </form>
</body>
</html>


Namespace Used:

using System;
using System.Web;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.IO;
using System.Data;
using System.Configuration;

Store image to SQL server table :


In code behind part, place the below code in upload button click event and this will store the uploaded image into database table. First we need to verify whether the image is selected or not when clicks on the btnUploadImage button and convert the image into byte array then store into database table. If image is selected then gets the image name using GetFileName method to store the image name into database table. Then get the size of an uploaded image file and store into byte array and using httppostedfile InputStream read method read the file into the byte array and store into database table. Below I’m using sql server stored procedure SP_ImageUpload to insert the images details into table. Once uploaded images saved into table then display the image into page using LoadImages()method.

protected void btnUploadImage_Click(object sender, EventArgs e)
        {
            string ImageName = string.Empty;
            byte[] Image = null;
            if (ImageUploadToDB.PostedFile != null && ImageUploadToDB.PostedFile.FileName != "")
            {
                ImageName = Path.GetFileName(ImageUploadToDB.FileName);
                Image = new byte[ImageUploadToDB.PostedFile.ContentLength];
                HttpPostedFile UploadedImage = ImageUploadToDB.PostedFile;
                UploadedImage.InputStream.Read(Image, 0, (int)ImageUploadToDB.PostedFile.ContentLength);
            }
            using (SqlConnection Sqlcon = new SqlConnection(strCon))
            {
                using (SqlCommand cmd = new SqlCommand())
                {
                    Sqlcon.Open();
                    cmd.Connection = Sqlcon;
                    cmd.CommandType = CommandType.StoredProcedure;
                    cmd.CommandText = "SP_ImageUpload";
                    cmd.Parameters.Add(new SqlParameter("@pvchAction", SqlDbType.VarChar, 50));
                    cmd.Parameters.Add(new SqlParameter("@pvchImageName", SqlDbType.VarChar, 100));
                    cmd.Parameters.Add(new SqlParameter("@pvchImage", SqlDbType.Image));
                    cmd.Parameters.Add(new SqlParameter("@pvchCreatedBy", SqlDbType.VarChar, 100));
                    cmd.Parameters.Add("@pIntErrDescOut", SqlDbType.Int).Direction = ParameterDirection.Output;
                    cmd.Parameters["@pvchAction"].Value     = "insert";
                    cmd.Parameters["@pvchImageName"].Value  = ImageName;
                    cmd.Parameters["@pvchImage"].Value      = Image;
                    cmd.Parameters["@pvchCreatedBy"].Value  = "Admin";
                    cmd.ExecuteNonQuery();
                    int retVal = (int)cmd.Parameters["@pIntErrDescOut"].Value;
                }
            }
            LoadImages();
        }

Retreive image from SQL server table:

Once uploaded images inserted into table then need to display in the aspx page using gridview control. Below LoadImages() method will be used to display the images in gridview control. Here I’m using stored procedure to get all image record from database. To display this uploaded images we need to use http handler, so right click on project and click Add new item then select Generic handler and changed the name as DisplayImage.ashx then place the below code in httphandler class and using this handler we get the specific image from database and convert as memorystream object then create an image from memory stream and save this image in specific stream and specific format.

string strCon = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
        SqlDataAdapter SqlAda;
        DataSet ds;
protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                LoadImages();
            }
        }
        private void LoadImages()
        {
            using (SqlConnection Sqlcon = new SqlConnection(strCon))
            {
                using (SqlCommand cmd = new SqlCommand())
                {
                    Sqlcon.Open();
                    cmd.Connection = Sqlcon;
                    cmd.CommandType = CommandType.StoredProcedure;
                    cmd.CommandText = "SP_ImageUpload";
                    cmd.Parameters.Add(new SqlParameter("@pvchAction", SqlDbType.VarChar, 50));
                    cmd.Parameters["@pvchAction"].Value = "select";
                    cmd.Parameters.Add("@pIntErrDescOut", SqlDbType.Int).Direction = ParameterDirection.Output;
                    SqlAda = new SqlDataAdapter(cmd);
                    ds = new DataSet();
                    SqlAda.Fill(ds);
                    GridViewUploadedImageFile.DataSource = ds;
                    GridViewUploadedImageFile.DataBind();
                }
            }
        }
protected void GridViewUploadedImageFile_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                string ImageID = GridViewUploadedImageFile.DataKeys[e.Row.RowIndex].Values[0].ToString();
                System.Web.UI.WebControls.Image UsrImages = (System.Web.UI.WebControls.Image)e.Row.FindControl("UsrImages");
                UsrImages.ImageUrl = "DisplayImage.ashx?ImgId=" + ImageID;
            }
        }

In the above gridview rowdatabound event, pass the image id to httphandler to display the image from database.

DisplayImage Handler:


public class DisplayImage : IHttpHandler
    {
        public void ProcessRequest(HttpContext context)
        {
             context.Response.Clear();
             context.Response.ContentType = "image/jpeg";           
              if (context.Request.QueryString["ImgId"] != null)
            {
                int imgId = 0;
                imgId = Convert.ToInt16(context.Request.QueryString["imgId"]);
                MemoryStream memoryStream = new MemoryStream(GetImageFromDB(imgId), false);
                System.Drawing.Image imgFromDataBase = System.Drawing.Image.FromStream(memoryStream);
                imgFromDataBase.Save(context.Response.OutputStream, System.Drawing.Imaging.ImageFormat.Jpeg);            }
        }
        private byte[] GetImageFromDB(int ImgId)
        {
            string strCon   = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
            SqlDataAdapter SqlAda;
            DataSet ds;
            byte[] btImage  = null;
            using (SqlConnection Sqlcon = new SqlConnection(strCon))
            {
                using (SqlCommand cmd = new SqlCommand())
                {
                    Sqlcon.Open();
                    cmd.Connection = Sqlcon;
                    cmd.CommandType = CommandType.StoredProcedure;
                    cmd.CommandText = "SP_ImageUpload";
                    cmd.Parameters.Add(new SqlParameter("@pvchAction", SqlDbType.VarChar, 50));
                    cmd.Parameters.Add(new SqlParameter("@pvchImageId", SqlDbType.Int));
                    cmd.Parameters["@pvchAction"].Value = "select";
                    cmd.Parameters["@pvchImageId"].Value = ImgId;
                    cmd.Parameters.Add("@pIntErrDescOut", SqlDbType.Int).Direction = ParameterDirection.Output;
                    SqlAda = new SqlDataAdapter(cmd);
                    ds = new DataSet();
                    SqlAda.Fill(ds);
                    btImage = (byte[])ds.Tables[0].Rows[0][3];
               }
            }
            return btImage; 
        }
        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }


See the below screen shot, after inserting the images into table, gridview displays the list of saved images in the page.




What do you think, is this Article is interesting, please share this Article to your friends.

Any quries? Please send a mail to dotnetcircle@gmail.com

Monday, September 15, 2014

Software Development Life Cycle(SDLC)









What is SDLC? 

SDLC stands for Software Development Life Cycle. A Software Development Life Cycle is essentially a series of steps, or phases, that provide a model for the development and lifecycle management of an application or piece of software. The methodology within the SDLC process can vary across industries and organizations, but standards such as ISO/IEC 12207 represent processes that establish a lifecycle for software, and provide a mode for the development, acquisition, and configuration of software systems.

Benefits of the SDLC Process

The intent of a SDLC process it to help produce a product that is cost-efficient, effective, and of high quality. Once an application is created, the SDLC maps the proper deployment and decommissioning of the software once it becomes a legacy. The SDLC methodology usually contains the following stages: Analysis (requirements and design), construction, testing, release, and maintenance (response). Veracode makes it possible to integrate automated security testing into the SDLC process through use of its cloud based platform.


Phases of the Software Development Life Cycle


  • SDLC starts with the analysis and definition phases, where the purpose of the software or system should be determined, the goals of what it needs to accomplish need to be established, and a set of definite requirements can be developed.
  • During the software construction or development stage, the actual engineering and writing of the application is done. The software is designed and produced, while attempting to accomplish all of the requirements that were set forth within the previous stage.
  • Next, in the software development life cycle is the testing phase. Code produced during construction should be tested using static and dynamic analysis, as well as manual penetration testing to ensure that the application is not easily exploitable to hackers, which could result in a critical security breach. The advantage of using Veracode during this stage is that by using state of the art binary analysis (no source code required), the security posture of applications can be verified without requiring the use of any additional hardware, software, or personnel.





Once the software is deemed secure enough for use, it can be implemented in a beta environment to test real-world usability, and then pushed a full release where it enters the maintenance phase. The maintenance stage allows the application to be adjusted to organizational, systemic, and utilization changes.

SDLC Implementation

There are two different types of SDLC that can be used: waterfall and agile. The major difference between the two is that the waterfall process is more traditional and begins with a well thought out plan and defined set of requirements whereas agile SDLC begins with less stringent guidelines and then makes adjustments as needed throughout the process. Agile development is known for its ability to quickly translate an application that is in development to a full 



Sunday, September 14, 2014

MVC, MVVM, MVP Design Patterns

There are Several Design Patterns in .Net, But basically we have to understand the MVC, MVVM, MVP Design Patterns.

MVC Pattern

MVC stands for Model-View-Controller. It is a software design pattern which was introduced in 1970s. Also, MVC pattern forces a separation of concerns, it means domain model and controller logic are decoupled from user interface (view). As a result maintenance and testing of the application become simpler and easier.

MVC design pattern splits an application into three main aspects: Model, View and Controller


Ff649643.des_MVC_Fig01(en-us,PandP.10).gif


-  Model

The Model represents a set of classes that describe the business logic i.e. business model as well as data access operations i.e. data model. It also defines business rules for data means how the data can be changed and manipulated.

-  View

The View represents the UI components like CSS, jQuery, html etc. It is only responsible for displaying the data that is received from the controller as the result. This also transforms the model(s) into UI.

-  Controller

The Controller is responsible to process incoming requests. It receives input from users via the View, then process the user's data with the help of Model and passing the results back to the View. Typically, it acts as the coordinator between the View and the Model.


MVP Pattern

This pattern is similar to MVC pattern in which controller has been replaced by the presenter. This design pattern splits an application into three main aspects: Model, View and Presenter.

Ff649571.354b3e51-0023-46a2-9288-4cf5744594f0(en-us,PandP.10).png

-  Model

The Model represents a set of classes that describes the business logic and data. It also defines business rules for data means how the data can be changed and manipulated.


-  View

The View represents the UI components like CSS, jQuery, html etc. It is only responsible for displaying the data that is received from the presenter as the result. This also transforms the model(s) into UI.

 - Presenter

The Presenter is responsible for handling all UI events on behalf of the view. This receive input from users via the View, then process the user's data with the help of Model and passing the results back to the View. Unlike view and controller, view and presenter are completely decoupled from each other’s and communicate to each other’s by an interface.

Also, presenter does not manage the incoming request traffic as controller.

This pattern is commonly used with ASP.NET Web Forms applications which require to create automated unit tests for their code-behind pages. This is also used with windows forms.


MVVM Pattern

MVVM stands for Model-View-View Model. This pattern supports two-way data binding between view and View model. This enables automatic propagation of changes, within the state of view model to the View. Typically, the view model uses the observer pattern to notify changes in the view model to model.

The MVVM classes and their interactions


-  Model

The Model represents a set of classes that describes the business logic and data. It also defines business rules for data means how the data can be changed and manipulated.

-  View

The View represents the UI components like CSS, jQuery, html etc. It is only responsible for displaying the data that is received from the controller as the result. This also transforms the model(s) into UI.

-  View Model

The View Model is responsible for exposing methods, commands, and other properties that helps to maintain the state of the view, manipulate the model as the result of actions on the view, and trigger events in the view itself.
This pattern is commonly used by the WPF, Silverlight, Caliburn, nRoute etc.

Do you think this Article useful for you, need to know more, then you can subscribe this blog.

Please your valuable feedback about this blog to dotnetcircle@gmail.com

Thursday, September 11, 2014

Main Difference between Java and .Net



Features of C# Absent in Java


  • C# includes more primitive types and the functionality to catch arithmetic exceptions.

  • Includes a large number of notational conveniences over Java, many of which, such as operator overloading and user-defined casts, are already familiar to the large community of C++ programmers.
  • Event handling is a "first class citizen"—it is part of the language itself.
  • Allows the definition of "structs", which are similar to classes but may be allocated on the stack (unlike instances of classes in C# and Java).
  • C# implements properties as part of the language syntax.
  • C# allows switch statements to operate on strings.
  • C# allows anonymous methods providing closure functionality.
  • C# allows iterator that employs co-routines via a functional-style yield keyword.
  • C# has support for output parameters, aiding in the return of multiple values, a feature shared by C++ and SQL.
  • C# has the ability to alias namespaces.
  • C# has "Explicit Member Implementation" which allows a class to specifically implement methods of an interface, separate from its own class methods. This allows it also to implement two different interfaces which happen to have a method of the same name. The methods of an interface do not need to be public; they can be made to be accessible only via that interface.
  • C# provides integration with COM.
  • Following the example of C and C++, C# allows call by reference for primitive and reference types.


Features of Java Absent in C#


  • Java's strictfp keyword guarantees that the result of floating point operations remain the same across platforms.
  • Java supports checked exceptions for better enforcement of error trapping and handling.
For More Information :