Thursday, December 27, 2012

Creating Dynamic Controls in JavaScript

Creating dynamic controls in javascript will provide us a great feature for our websites that too will give a flexible data entry pages.  For creating controls dynamically in javascript we can follow some basic rules like - Createing a method for creating a particular control.  We can use this method for creating that particular control in our whole project.

Creating controls in javascript can be done by using "document.createElement()" method by passing tag name as parameter as follows

for example if we want to create a textbox or some input fields, then the code will be as follows

var textBox = document.createElement('input');


then by adding setAttribute method for that control we can set various attributes for that control.

Here the code for this


Creating TextBox i.e., input text field:
function CreateTextBox(id, value) {
    var textBox = document.createElement('input');
    textBox.setAttribute("type", "text");
    textBox.setAttribute("value", value);
    textBox.setAttribute("id", id);
    return textBox;
}

Creating TextArea field:

function CreateTextArea(id, value) {
    var textarea = document.createElement('textarea');
    textarea.setAttribute('id', id);
    textarea.value = value;
    return textarea;
}

Creating button field i.e., input button field:
function CreateButton(id, value, Event) {
    var button = document.createElement('input');
    button.setAttribute('type', 'button');
    button.setAttribute('id', id);
    button.setAttribute('value', value);
    return button;
}

Finally, by using the "appendChile()" method we can add those controls as child controls for any parent like div or paragraph tags as follows

document.getElementById('div1').appendChild(CreateTextBox('txtTTitle', ''));


Happy Coding...

Saturday, October 13, 2012

THREE TIRE ARCHITECTURE

Click Here to download sample project

A three tire architecture application is divided into three platforms namely Data Access Layer, Business Layer and Presentation Layer.
  • Data Access Layer (DAL):This layer performs the operations related to data transfer between business layer and database.
  • Business Layer (BL):This layer performs business logics if necessary or else it just transfers data between the presentation layer and data access layer.
  • Presentation Layer:This layer is used to display the related data to the users.  This layer gets or supplies necessary data to the business layer and presents it to the user with the respective presentation technology.

Advantages of Three tire Architecture:

  • Code Reusability – After writing DAL or BL these logics can be used for any kind of technologies in dotnet.  For example, if you are developing a social networking site in three tire architecture and if you choose asp.net as your front end technology then the same DAL and BL codes can be used to develop the same application for mobile apps and windows applications.
  • Better Exception Handling – Exceptions can be handled easily by identifying them easily due to layered coding.  For example if data is not retrieved then we can check DAL for exceptions.
  • Better Exception Reporting – If we use layers we can report the exceptions to the respective department about the exception.



Different models of three tire architecture (Code level / Development level):

  • Using App_Code – By grouping class of different layers using namespaces we can create three tire architecture.
  • Using Assembly – By creating each assembly for each layer we can create three tire architecture.

Let’s see an example of creating a three tire architecture using App_Code model

Sample Database:



Objects:
namespace ObjectsLayer
{
    interface ICategory
    {
        int CategoryId { get; set; }
        string CategoryName { get; set; }
    }
    interface IProducts
    {
        int ProductId { get; set; }
        string ProductName { get; set; }
        decimal Cost { get; set; }
    }
    public class Category : ICategory
    {
        private int _CategoryId = 0;
        private string _CategoryName;
        public int CategoryId
        {
            get { return _CategoryId; }
            set { _CategoryId = value; }
        }
            
        public string CategoryName
        {
            get { return _CategoryName; }
            set { _CategoryName = value; }
        }

    }
    public class Products : Category, IProducts
    {
        private int _ProductId;
        private string _ProductName;
        private decimal _cost;

        public int ProductId
        {
            get { return _ProductId; }
            set { _ProductId = value; }
        }
    
        public string ProductName
        {
            get { return _ProductName; }
            set { _ProductName = value; }
        }
      
        public decimal Cost
        {
            get { return _cost; }
            set { _cost = value; }
        }
    }
}

Data Access Layer:
namespace DAL
{
    interface ICategory
    {
        DataSet GetCategory() { return null; }
        void InsertCategory(ObjectsLayer.Category ObjCategory) { }
        void UpdateCategory(ObjectsLayer.Category ObjCategory) { }
        void DeleteCategory(ObjectsLayer.Category ObjCategory) { }
    }
    interface IProduct
    {
        DataSet GetProducts() { return null; }
        void InsertProduct(ObjectsLayer.Products ObjProducts) { }
        void UpdateProduct(ObjectsLayer.Products ObjProducts) { }
        void DeleteProduct(ObjectsLayer.Products ObjProducts) { }
    }
    public class Category:ICategory
    {
        SqlConnection con;
        SqlCommand cmd;
        SqlDataAdapter da;
        SqlDataReader dr;
        DataSet ds;
        string query = string.Empty;
        public DataSet GetCategory()
        {
            query = "select CategoryId,CategoryName from Category ";
            da = new SqlDataAdapter(query, con);
            ds = new DataSet();
            da.Fill(ds);
            return ds;
        }

        public void InsertCategory(ObjectsLayer.Category ObjCategory)
        {
            query = "Insert into Category(CategoryName) Values('" + ObjCategory.CategoryName + "')";
            con.Open();
            cmd = new SqlCommand(query, con);
            cmd.ExecuteNonQuery();
            con.Close();
        }

        public void UpdateCategory(ObjectsLayer.Category ObjCategory)
        {
            query = "Update Category Set CategoryName='" + ObjCategory.CategoryName + "' where CategoryId='" + ObjCategory.CategoryId + "'";
            con.Open();
            cmd = new SqlCommand(query, con);
            cmd.ExecuteNonQuery();
            con.Close();
        }

        public void DeleteCategory(ObjectsLayer.Category ObjCategory)
        {
            query = "delete from Category where CategoryId='" + ObjCategory.CategoryId + "'";
            con.Open();
            cmd = new SqlCommand(query, con);
            cmd.ExecuteNonQuery();
            con.Close();
        }
    }
    public class Products:Category,IProduct
    {
        SqlConnection con;
        SqlCommand cmd;
        SqlDataAdapter da;
        SqlDataReader dr;
        DataSet ds;
        string query = string.Empty;
        public DataSet GetProducts()
        {
            query = @"SELECT Products.ProductId,Products.CategoryId,Products.ProductName,Products.Cost,Category.CategoryName FROM
                        Products INNER JOIN Category
                        ON Products.CategoryId=Category.CategoryId";
            da = new SqlDataAdapter(query, con);
            ds = new DataSet();
            da.Fill(ds);
            return ds;
        }

        public void InsertProduct(ObjectsLayer.Products ObjProducts)
        {
            query = "insert into Products(ProductName,Cost,CategoryId)values('" + ObjProducts.ProductName + "','" + ObjProducts.Cost + "','" + ObjProducts.CategoryId + "')";
            con.Open();
            cmd = new SqlCommand(query, con);
            cmd.ExecuteNonQuery();
            con.Close();
        }

        public void UpdateProduct(ObjectsLayer.Products ObjProducts)
        {
            query = "Update Products Set ProductName='" + ObjProducts.ProductName + "',Cost='" + ObjProducts.Cost.ToString() + "',CategoryId='" + ObjProducts.CategoryId + "' where ProductId='" + ObjProducts.ProductId + "'";
            con.Open();
            cmd = new SqlCommand(query, con);
            cmd.ExecuteNonQuery();
            con.Close();
        }

        public void DeleteProduct(ObjectsLayer.Products ObjProducts)
        {
            query = "delete from Products where ProductId='" + ObjProducts.ProductId + "'";
            con.Open();
            cmd = new SqlCommand(query, con);
            cmd.ExecuteNonQuery();
            con.Close();
        }
    }
}

Business layer:
namespace BL
{
       public class Category
       {
       
        DAL.Category dalCat = new DAL.Category();
        public DataSet GetCategory()
        {
            return dalCat.GetCategory();
        }
        public void InsertCategory(ObjectsLayer.Category ObjCategory)
        {
            dalCat.InsertCategory(ObjCategory);           
        }
        public void UpdateCategory(ObjectsLayer.Category ObjCategory)
        {
            dalCat.UpdateCategory(ObjCategory);
        }
        public void DeleteCateogry(ObjectsLayer.Category ObjCategory)
        {
            dalCat.DeleteCategory(ObjCategory);
        }
       }
    public class Products
    {
        DAL.Products dalpro = new DAL.Products();
        public DataSet GetProduct()
        {
            return dalpro.GetProducts();
        }
        public void InsertProduct(ObjectsLayer.Products ObjPro)
        {
            dalpro.InsertProduct(ObjPro);
        }
        public void UpdateProduct(ObjectsLayer.Products ObjPro)
        {
            dalpro.UpdateProduct(ObjPro);
        }
        public void DeleteProduct(ObjectsLayer.Products ObjPro)
        {
            dalpro.DeleteProduct(ObjPro);
        }
    }
}

Presentation Layer
In this layer you can use the business layer as follows
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using ObjectsLayer;
using BL;

public partial class _Default : System.Web.UI.Page
{
    BL.Category blcat = new BL.Category();
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void btnsubmit_Click(object sender, EventArgs e)
    {
        ObjectsLayer.Category ObjCategory = new ObjectsLayer.Category();
        ObjCategory.CategoryName = txtname.Text.Trim();
        blcat.InsertCategory(ObjCategory);
    }
}

Conclusion:
Using this three tier architecture as your code model will be easy but while developing it will be some what lengthy process.

Monday, August 6, 2012

Parsing Json in Asp.net


var obj = JSON.parse(Jsonresult);
            for (var key in obj) {
                if (obj.hasOwnProperty(key)) {
                    var value = obj[key];
                   alert(value.CustomerID);
                }
            }
            document.getElementById('result').innerHTML = html;

Tuesday, June 12, 2012

Truncating tables which are bounded with foreign keys


Truncating a table having primary key and the field is referenced to the some other field of some other table for the foreign key relationship is not possible by using ‘Truncate’ command alone.  This will gives the following error

Cannot truncate table 'tbl_Parent' because it is being referenced by a FOREIGN KEY constraint.


Here I’ll explain how to do this with an example

Steps:
  1.   Delete all the foreign key constraints
  2.  Truncate the tables
  3.  Again create all the foreign key constraints

These are the steps for clearing the database values using the truncate command while using foreign keys.
Example:
Lets create a database as in the following diagram



Here the ParentId in the tbl_Child is the foreign key for the field ParentId in the tbl_Patrent which is a primary key.


Not for truncating all the tables the procedure will be as follows


CREATE PROC sp_DropDB

AS
BEGIN

      BEGIN TRY
     
            BEGIN TRAN
                 
                  ALTER TABLE tbl_Child
                  DROP CONSTRAINT fk_Child_ParentId
                 
                  TRUNCATE TABLE tbl_Child
                  TRUNCATE TABLE tbl_Parent
                 
                  ALTER TABLE tbl_Child
                  ADD CONSTRAINT fk_Child_ParentId FOREIGN KEY(ParentId) REFERENCES tbl_Parent(ParentId)
                 
            COMMIT TRAN
     
      END TRY
     
      BEGIN CATCH
            ROLLBACK TRAN
      END CATCH

END

By executing the above procedure we can clear all the values in the database


Happy Coding…

Thursday, May 17, 2012

Recover or Restore SQLServer Database from Suspect Mode

     Is your SQL Server database is marked with "Suspece", then your database is in suspect mode.

     When your project's Database is in Suspect mode, then you are not able to do any transactions from the database.  This will leads your brain to a big tension mode.  Don't worry, Here are the steps to restore your SQL Server database from Suspect Mode back to Operational Mode.

Run the below script by replacing the text "your database name" to Your database name which you need to restore.


There will not be any data loss.  I have tried two times on my local database and also in the live database.



EXEC sp_resetstatus ' your database name ';
ALTER DATABASE  your database name  SET EMERGENCY
DBCC checkdb(' your database name ')
ALTER DATABASE  your database name  SET SINGLE_USER WITH ROLLBACK IMMEDIATE
DBCC CheckDB (' your database name ', REPAIR_ALLOW_DATA_LOSS)
ALTER DATABASE  your database name  SET MULTI_USER



HAPPY CODING....

Saturday, March 17, 2012

Localizing an ASP.NET Application



Globalization is the process of designing and developing applications that function for multiple cultures, and localization is the process of customizing your application for a given culture and locale. The topics in this section describe how to create ASP.NET Web applications that can be adapted to different languages and cultures.

Example for Localization:-

Imports System.Threading.Thread
Imports System.Threading
Public Class Globalization
    Public Sub New()
        ' Creating a Global Culture specific to our application.
        Dim cultureInfo As New System.Globalization.CultureInfo("en-US")
        ' Creating the DateTime Information specific to our application.
        Dim dateTimeInfo As New System.Globalization.DateTimeFormatInfo()
        ' Defining various date and time formats.
        dateTimeInfo.DateSeparator = "/"
        dateTimeInfo.LongDatePattern = "MM/dd/yyyy"
        dateTimeInfo.ShortDatePattern = "MM/dd/yyyy"
        ' Setting application wide date time format.
        cultureInfo.DateTimeFormat = dateTimeInfo
        ' Assigning our custom Culture to the application current thread.
        'Application.CurrentCulture = cultureInfo;
        Thread.CurrentThread.CurrentCulture = cultureInfo
        Thread.CurrentThread.CurrentUICulture = cultureInfo
    End Sub
End Class

Create an instance for the above class in the base form of your project.  
Now the datetime will be treated in the format of  MM/dd/yyyy