Monday, 30 May 2011

Setting size of control using Css

Problem:
When you have control placed in an web form where you want to modify its size based on the width and height of your browser. Normally when you place the control on form(like image)it does not occupy the entire width and height of the content area in which you place the control. But what if you want the control to stretch itself and occupy the entire content area at run time.
Impact:
You could solve it by randomly fixing the width and height of control using the fixed value but its not the efficient way of doing and what if you need that for more controls on the form.
Solution:
There has to be generalized way to do it. So I found doing it using CSS.
Firstly, Create a Css Class(here I named it as stylefill)

<style type="text/css">
        .stylefill
        {
            width:auto;
            min-width:100%;
            height:auto;
            min-height:100%;
        }
</style>

Then apply this style to the controls as needed. Below I am apply this style to an image.So my image will occupy entire content area in which image is placed.

<asp:Image ID="Image2" runat="server"  CssClass="stylefill"
                      ImageUrl="~/Images/TopImage.JPG"/>

Bulk copy using SqlBulkCopy object

Problem:

What if you need to copy the huge rows of data from one table to another efficiently? Simple way comes in mind is to repeatedly perform the task.

Impact:

If you repeat copying repeatedly then it is not the efficient way and you wont achieve the performance.

Solution:

We can use SqlBulkCopy to copy huge data with good performance in Sql Server Database. The Good thing about this class is that it can copy from variety of datasource including xml.

Here is the copy which copies huge number of rows from one table in database to another.

//Create the connection string
string connStr = @"server =yourSqlServername;
                            integrated security = true;
                            database = myDatabaseName";

//Create the connection object and another for bulkcopy
SqlConnection conn = new SqlConnection(connStr);
SqlConnection blkConn = new SqlConnection(connStr);

//Create the command object and populate it with
//desired query
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "Select id from students";
cmd.CommandType = CommandType.Text;
cmd.Connection = conn;

//open both connections
conn.Open();
blkConn.Open();

// Create the reader and execute the command
SqlDataReader rd = cmd.ExecuteReader();

//Create the SqlBulkcopy object and supply it with
//bulk copy connection object
SqlBulkCopy bcpy = new SqlBulkCopy(blkConn);

//Supply the destination table to copy data           
bcpy.DestinationTableName = "Results";

//Finally execute the method to copy and pass it with
//data in datareader object
bcpy.WriteToServer(rd);

//Lastly close both the connections
conn.Close();
blkConn.Close();

Linq to sql mapping using attributes

Problem:
What if you need access relational database using Linq to Sql? Using Linq to Sql you can provide operations on data stored in Sql Server databases. Linq to Sql uses Data Context to perform the required operations and it can work both in connected and disconnected mode. Now how to map the result of queries onto classes?
Impact:
There are two ways in which you can map the result of queries on the classes.
Firstly using attributes and second using xml
Solution:
We here need to accomplish our task using attributes.
Firstly create a attributes for the class
//Here Customer is name of the Table in Database to mapped to
//CustomerEntity Class and Table attribute defines mapping.
[Table(Name = "Customer")]
public class CustomerEntity
{
    //CustomerID field of Customer Table needs to be mapped to
    //ID member-field of CustomerEntity Class and similarly
    //for other fields.
       
    [Column(Name="CustomerID")]
    public int ID;
    [Column(Name="CustomerName")]
    public string Name;
    [Column(Name="CustomerAddress")]
    public string Address;
    [Column(Name="CustomerDetails")]
    public string Details;
   
    //Note- here if you are mapping members-fields of class with
    //same name as fields of Table in database then you don’t
    //need Name value with Column attribute
    //just mention [Column]
   
}

Then to access data use the following code.
public class Tester
{
    static void Main(string[] args)
    {

        //First create the connection string to your database
        string connString = @"server =yourSqlServername;
                            integrated security = true;
                            database = myDatabaseName";
       
        //Next step is to create datacontext that will help us
        //in all the communication process.
        //Don’t forget to pass the connection 
       //string to datacontext.
        DataContext db = new DataContext(connString);
       
        //Get the data from table. Here GetTable gets the
        //collection of type CustomerEntity which is actually
        //mapped to our Customer Table in DB and we store the
        //returned collection in table of type class
        Table<CustomerEntity> cust =
                        db.GetTable<CustomerEntity>();

        //Now we are using Linq to access data from customer
        //table based on our requirement.Here I am grabbing
        //all customers orderby name whose
        //ID is greater than 5
        
        var custs_query = from c in cust
                          where c.ID > 5
                          orderby c.Name
                          select c;
        //Now the final step to print result of query
        foreach (var cq in custs_query)
            Console.WriteLine("{0}, {1}, {2}, {3}",
               cq.ID,
               cq.Name,
               cq.Address,
               cq.Details );

Serializing and deserializing dataset objects

Problem:

There was a time in my project when I needed to serialize and deserialize my dataset object. Look at the options available for doing it. Normally you can do it as xml or binary.

Impact:

I thought that it would be good to go for binary because size of xml file produced can cause sometimes problems with resources like memory, bandwith etc. But then binary files contain more initial overhead compared to xml files.

Solution:

So after looking at pros and conns of both and my requirement I decided to go with xml serialization.

So here is the code to perform serialization of dataset objects as xml

DataSet ds = new DataSet();
//populate the dataset using data tables
//code for populating is not included here

ds.WriteXml(MapPath("File.xml"));

You can also regulate how the data is written to xml
by using ColumnMapping property of DataColumn object

Now to Deserialize you can perform follwing task

DataSet ds = new DataSet();
           
ds.ReadXml(MapPath("File.xml"));

gridview1.DataSource = ds;
gridview1.DataMember = "TabName";
gridview1.DataBind();

Wednesday, 25 May 2011

Writing client side javascript to validate date.

Problem:
I was working with my project were I got stuck where I want to work with DATE data type at client side. When I click button I need to perform custom validation that validates the date entered by the user. I want to do this task using client side script.

Impact:
If you don’t use javascript then you have to use server side custom function. But then you are sending the request to server for validation.

Solution:
Use client side javascript function and make use of Date functionality available in it. Here the checkDate is the Function.
<script language="javascript"  type="text/javascript">
    function checkDate(sender, arguments) {
        //get the current date
        var tdate = new Date();
       
        //get year from current date
        var tyear = tdate.getFullYear();
        
        // Splits the date entered by userand gets in form of array
        // which contains date,month and year
       var cdate = arguments.Value.split('/');
               
        //check if age is greater than 18 and less than 90
        if ((tyear - cdate[2] > 18) && (tyear - cdate[2] < 90)) {

             //mark page as valid
             arguments.IsValid = true;
        }
        else {
            //mark page as invalid
            arguments.IsValid = false;
        }
    }
</script>

<asp:CustomValidator ID="CalendarCustomValidator"   runat="server" ControlToValidate="ShowDOB_label" 
ClientValidationFunction="checkDate"
Text="Age must be greater that 18 and less than 90">
</asp:CustomValidator>