header1.html

Showing posts with label .net articles. Show all posts
Showing posts with label .net articles. Show all posts

Sunday, 21 September 2014

'Thread was being aborted' –Exception for Response.Redirect() method inside try-catch block

If you are monitoring errors of your application you might have noticed that in your error log file lots of 'Thread was being aborted' exception logged.
This Exception occurs when you use Response.Redirect inside of a Try / Catch block. Your code will work and the browser will be redirected but that is reason of getting lots of alerts.
If you are passing QueryString then your application may not work properly because of this issue, so it is important to handle or avoid this kind of exceptions.
There are different ways to resolve this issue,

  • Simplest way to move the Response.Redirect outside the Try/Catch block. 
  • Catch Exception and do nothing, 
                 try 
                    { 
                        if (Condition) 
                          Response.Redirect("newpage.aspx”); 
                    } 
                catch (ThreadAbortException ex) 
                 { // do nothing } 
                 catch (Exception e) 
                  { //Write your Error log logic } 
  • Use overload of Redirect method like, Pass false as second parameter to this overload. Response.Redirect("newpage.aspx”,false); 
I prefer to use 3rd approach as it is easiest one to implement and it works fine in case if you are using QueryString in your application.

Hope this helps you someway. Thank you!!!

Sunday, 20 July 2014

What is XSLT?How to Transform XML data using XSLT?

In this post we are going to discuss about-How we can display XML content?There are multiple ways to do to so,but XSLT is best suitable way.So,what is XSLT?

To know about XSLT: Extensible Stylesheet Language Transformation, we should have the basic idea of following,

What is a Markup Language?

A language specially designed for processing, defining and presenting text/data is called a Markup Language.

To know about XSLT, we should have the basic idea of following.

There are three languages in XSL family,

  1. XSL Transformations(XSLT): XML language for transforming XML Documents.
  2. XSl  Formatting Objects (XSL-FO):XML language for specifying the visual formatting of an XML document.
  3. XML Path Language (XPATH): a non XML language used by XSLT, and also available for use in non-XSLT contexts, for addressing the parts on an XML document.

  • XSLT helps to transform one XML document to another. Output of XSL transformation can be another XML, HTML or PDF. Data from one XML can be read and modified into another applying arithmetic, numeric, string operations based on the need.
  • XSLT was developed by W3C especially for XML. XSLT internally uses XPATH and XSL-FO for navigating, performing calculation and for formatting the data.
  • XSLT documents are well-formed XML documents that describe how another XML document should be transformed. For XSLT to work, it needs an XML document to transform and an engine to make the transformation take place. In addition, parameters can be passed in to XSLTs providing further instructions on how to do the transformation.
Why and where is it used?

In web application, web services sent the business data in form of XML within the Applications and across the applications. Since XML is accepted as the most common mode of storing and passing data, a language is needed to read the XML in different ways for different application.


A medium like XSLT is needed to parse the data from XML and give it to browsers to render the HTML code. XSLT works in between XML and Browser to transform the data.


Example:

Blog.xml

<?xml version="1.0" encoding="utf-8"?>
<?xml-stylesheet type="text/xsl" href="BlogsStyle.xsl"?>
<Blogs>
       <name id="21">
                <bname>Career Web Helper</bname>
                <Topics>Online Quizzes,MCQs and Articles on Microsoft Technologies.</Topics>
       </name>
                   <place>Pune</place>
                   <language>English</language>
</Blogs>

BlogsStyle.xsl

<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version='1.0'>
<xsl:output method="html" indent="yes" omit-xml-declaration="yes" encoding="utf-8"/>
<xsl:template match="Blogs">
<html>
<body>
   <h2>Blog Detail</h2>
   <table border="1">
     <tr>
       <td bgcolor="gray">Blog Id</td>
       <td><xsl:value-of select="name/@id"/></td>
     </tr>
     <tr>
       <td bgcolor="gray">Blog Name</td>
       <td><xsl:value-of select="name/bname"/></td>
     </tr>
      <tr>
       <td bgcolor="gray">Topics Covered</td>
       <td><xsl:value-of select="name/Topics"/></td>
     </tr>
     <tr>
       <td bgcolor="gray">Place</td>
       <td><xsl:value-of select="place"/></td>
     </tr>
     <tr>
       <td bgcolor="gray">Language</td>
       <td><xsl:value-of select="language"/></td>
     </tr>
   </table>
</body>
</html>
</xsl:template>
</xsl:stylesheet>

Output:

Sample Basic XSLT Example

This is only basic of XSLT,we will cover some advance topics in upcoming posts. Hope you like this post. 


Monday, 23 December 2013

New features in Visual Studio 2013 Developers perspective


    Hello All this is my third Article in this blog.Although main Objective of this Blog is to provide set of Online Quizzes and MCQs on Microsoft Technologies & Basics of Computers but after successful response to my Article- CRUD operation using Entity Framework and LINQ
some of my friends suggested me write few more articles and I am happy for that ☺☺☺.
This post is all about new features in Visual Studio 2013 IDE which I like most, We are happy for how Microsoft is managing the excellency in products like .NET Framework,Visual Studio,Windows and many more.
Visual Studio 2013 has new and enhanced features like,
1)Visual Studio languages      2).NET Framework 4.5.1
3)TFS and ALM                   4)SharePoint and Office
5)LightSwitch                        6)Windows Azure Mobile Services etc.etc. but in this post I am not going to discuss all the above.
Here we are going to discuss about Developers perspective of Visual studio 2013 for innovative features for greater productivity,
Following features which I like the most ☺☺☺...
1)Peek Definition(Alt+F12)
2)Move Code Line Up/Down (Alt+Arrow)
3)Inline Navigate To OR Code Lens(Ctrl+,)
4)64bit Edit and Continue
5)Back to Origin (i.e. icon colors)

Features like TFS&ALM(Team Foundation Server & Application Lifecycle Management)are fabulous in VS2013 as they made Developers or Support Team's life very easy for managing applications from Development phase till production deployment.
VS2013 also helps in Agile Portfolio Management for the Projects which are following Agile/Srum methodology of development.
So lets start with our favorite features ☺,
1)Peek Definition:
While coding most of developers are unhappy with F12(Go TO Definition) as after continuous clicking F12 they are getting lost from where they started or what they want actualy :P ,but that problem is getting resolved in this new IDE VS2013 ☺, now we can see the definition on the same file with new window as follow,
sagarphalke.blogspot.com

2)Move Code Line Up/Down:
This is very cool feature added in VS2013,with key (Alt+Arrow) we can move code segment Up or Down with arrow keys.
It will really help in performance improvement for Developers.
3)Inline Navigate To OR Code Lens:
Using this feature (ALT + ,) we can easily check the history of file as it is directly synched with TFS,so this feature can check who worked on this file by checking changeset.We can also check test cases passed/failed for particular code snippet.
new features in VS2013

This feature is helpful for Developers to find References,Find history and also in UTC executions.

4)64bit Edit and Continue:
It enables you to make changes to your source code while your program is in break mode but previous IDE were throwing exceptions for 64 bit,but now VS2013 IDE enables Edit and Continue for 64-bit and support for asynchronous debugging.
new features in Visual Studio 2013

5)Back to Origin:
This is last but very important feature I like as all of us were complaining about Color and Themes of VS2012.
This new IDE is having good themeing functionality and decent color schemes ☺,here we can see light color icons compare to VS2012.
Here I have listed some cool features which I like most but you can find many new features added in VS2013 which are helpful in developers productivity.
Conclusion:
In this article we have seen some cool features of Visual Studio 2013 which helps in improvement of Developers productivity. I hope this post will help you.
Happy Development!!!☺☺☺

Friday, 16 August 2013

CRUD operation using Entity Framework and LINQ



This article is for beginners who are new to EF Terminology and currently working on ADO.NET by creating DAL,BAL to interact with database.
First question comes in to picture is What is Entity Framework?
Lets see the definition given by Microsoft-"The Microsoft ADO.NET Entity Framework is an Object/Relational Mapping (ORM) framework that enables developers to work with relational data as domain-specific objects, eliminating the need for most of the data access plumbing code that developers usually need to write. Using the Entity Framework, developers issue queries using LINQ, then retrieve and manipulate data as strongly typed objects. The Entity Framework’s ORM implementation provides services like change tracking, identity resolution, lazy loading, and query translation so that developers can focus on their application-specific business logic rather than the data access fundamentals."
So,Entity Framework is ORM(Object/Relational Mapping) framework.
ORM helps to keep database design separate from domain Class design and it also improves standard CRUD (Create, Read, Update & Delete)operation.
Entity Framework 4.1 have multiple modeling techniques like code first, model first or database first.Here we are going to implement Database first approach. In this article we are also going to implement LINQ(Language Integrated Query)to perform CRUD operation with entity model.
To implement Database/Model first approach we need to create database first,
Query to create Database in SQL Server:

CREATE DATABASE MYCART

Query To create PRODUCTS table in MYCART Database:

USE MYCART
CREATE TABLE PRODUCTS
(
 Product_ID int IDENTITY(100,1) NOT NULL primary key,
 Product_Name varchar(20),
 Product_Desc varchar(50),
 Product_Price money,
 Quantity int
)

Create New ASP.NET Application:Create application "EF_CRUD" and add AddProduct.aspx page to implement CREATE operation.
structureCareerWebHelper
Sample Structure

Create the First simple Entity Data Model (EDM):
Solution Explorer =>right click on project => Add => New Item. Select the Data Template => ADO.NET Entity Data Model and click Add.
edmx

Rename it as ProductModel.edmx

It opens Entity Data Model Wizard. Select "Generate from database" option and click "Next"

Now enter your credentials and your database details as follows.
CareerWebHelperEM

StepsEF

By double clicking on ProductModel.edmx, it will open EDM designer which displays all the entities for selected tables and relation between them.Now check Entity model will be generated like
ProductModel

CREATE/INSERT Operation:Check AddProduct.aspx.cs ---Download
Create instance of Context MYCARTEntities context = new MYCARTEntities();
protected void btnAdd_Click(object sender, EventArgs e)
        {
            try
            {

                PRODUCT objProduct = new PRODUCT();
                objProduct.Product_Name = txtName.Text;
                objProduct.Product_Desc = txtPdesc.Text;
                objProduct.Product_Price = decimal.Parse(txtPrice.Text);
                objProduct.Quantity = int.Parse(txtQuantity.Text);

                context.AddToPRODUCTS(objProduct);
                int result=context.SaveChanges();
                if (result != 0)
                {
                    lblMsg.Text = "Product Added!!";  
                }
                else
                {
                    lblMsg.Text = "Failed!!";
                }
                

            }
            catch (Exception ex)
            {

                lblMsg.Text = "Failed!!";
                throw ex;
            }
        }

SaveChanges() method on the context to reflect the changes back to database.This will insert the record into the table.

Now, READ,UPDATE and DELETE OPERATION:1.Add ModifyProduct.aspx page to Project
2.Add GridView to page "gvModifyProducts"
3.Use Template fields and Bound Fields to bind Data to GridView.
4.Create following Method to implement READ Operation
private void BindProductDetails()
        {
            try
            {
                var myData = from c in context.PRODUCTS select new { c.Product_ID, c.Product_Name, c.Product_Desc,       c.Product_Price,c.Quantity };
                gvModifyProducts.DataSource = myData;
                gvModifyProducts.DataBind();
            }
            catch (Exception ex)
            {
                
                throw ex;
            }
        
        
        }

5.Now handle Following events
protected void gvModifyProducts_RowEditing(object sender, GridViewEditEventArgs e)
        {
            try
            {
                gvModifyProducts.EditIndex = e.NewEditIndex;
                BindProductDetails(); 
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        protected void gvModifyProducts_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            try
            {
                BindProductDetails();
                gvModifyProducts.PageIndex = e.NewPageIndex;
                gvModifyProducts.DataBind();
           }
            catch (Exception ex)
            {
                throw ex;
            }
         }

        protected void gvModifyProducts_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
        {
          gvModifyProducts.EditIndex = -1;
            BindProductDetails();

        }
        protected void gvModifyProducts_RowUpdating(object sender, GridViewUpdateEventArgs e)
        {
            try
            {
                int intID = int.Parse(gvModifyProducts.Rows[e.RowIndex].Cells[0].Text);
                TextBox txtName = (TextBox)gvModifyProducts.Rows[e.RowIndex].Cells[1].FindControl("txtName");
                TextBox txtDesc = (TextBox)gvModifyProducts.Rows[e.RowIndex].Cells[2].FindControl("txtDesc");
                TextBox txtPrice = (TextBox)gvModifyProducts.Rows[e.RowIndex].Cells[3].FindControl("txtPrice");
                TextBox txtQuant = (TextBox)gvModifyProducts.Rows[e.RowIndex].Cells[4].FindControl("txtQuantity");
//This Code is used to handle Validations like Required field
                if (txtName.Text.Trim() == "")
                {
                    txtName.Focus();

                }
               else if (txtDesc.Text.Trim() == "")
                    txtDesc.Focus();
               else if (txtPrice.Text.Trim()=="")txtPrice.Focus();
                else if (txtQuant.Text.Trim()=="")
               txtQuant.Focus();
                else
                {
              var data =
                    (from c in context.PRODUCTS
                     where c.Product_ID == intID
                     select c).First();

                    data.Product_Name = txtName.Text;
                    data.Product_Desc = txtDesc.Text;
                    data.Product_Price = decimal.Parse(txtPrice.Text);
                    data.Quantity = int.Parse(txtQuant.Text);
                    context.SaveChanges();

                    lblMsg.Visible = true;
                    lblMsg.Text = "Product Updated Successfully!!!";
                    BindProductDetails();
                }

            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        protected void gvModifyProducts_RowDeleting(object sender, GridViewDeleteEventArgs e)
        {
            try
            {
                int intID = int.Parse(gvModifyProducts.Rows[e.RowIndex].Cells[0].Text);
                PRODUCT p = new PRODUCT();
                p = (from c in context.PRODUCTS
                     where c.Product_ID == intID
                     select c).First();
                context.PRODUCTS.DeleteObject(p);
                
                context.SaveChanges();

                lblMsg.Visible = true;
                lblMsg.Text = "Product  deleted Successfully!!!";
                BindProductDetails();

            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

CRUD
READ,UPDATE and DELETE

Hope this article helped you, do write your feedback and comments.
Happy Coding ☺ ☺ ☺
You Can DOWNLOAD Code here
Please write your valuable comments if you liked this.☺

Sunday, 23 June 2013

Serialization in C#.net with binary serialization

Serialization is the process of converting objects in to persistent data formats.
.NET 2.0 provides built-in classes to convert data to formats that are portable, 
or easy to transport to another location. 
This process of converting data into a portable format is called serialization. 
The process of restoring the object or data to its original state is called deserialization.

Portable/persistent format includes text files or series of bytes or we can store in the database.
The process of converting objects and data into these common format for storage 
or transportation is called serialization.

The following are the basic advantages of serialization:
1.Serialization Creates a clone of an object
2.It facilitate the transportation of an object through a network

We can achieve Serialization by any  of the following types:
 1.Binary Serialization
 2.SOAP Serialization
 3.XML Serialization

In this post we are going to discuss about Binary Serialization,

Binary Serialization:
To determine the serialization format for objects, you need to use a formatter.
 
A formatter is required to indicate how you want to format the data that you are going 
to save for deserialization.

This Serialization in implemented by System.Runtime.Serialization.Formatters.Binary.BinaryFormatter class.

BinaryFormatter serializes and deserializes an object, or an entire graph of connected objects, in binary format.

The most common format in which objects and data can be serialized when storing or passing them between threads 
or application domains is the binary format. 

These application domains may reside on the same computer or in a controlled environment such as a network. 

The binary format is a series of bytes that represent the original state of the serialized object or data. 

At times, you may need to transfer data between applications that reside in completely different environments. 

In this situation, you can pass serialized objects and data between applications by using the Web. 

When passing an object or data over the Internet, the object must be serialized to a suitable format.

BinaryFormatter class generates a compact stream when you serialize an object. So it is useful for storage 
and socket-based network streams. 

Serializes all the members of an object, such as properties and enumerations, including the private members.

This allows BinaryFormatter to store all state data.
The following code Snippet shows how we can implement Binary Serialization.
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;

namespace Demo
{
    //create a class whose object can be serialized
    
    [Serializable]      //then mark the type as Serializable by using Serializable attribute
    class Product
    {
        private int prodid;
        private string prodname;

        public Product(int prodid, string prodname)
        {
            this.prodid = prodid;
            this.prodname = prodname;
        }
        public void Show()
        {
            Console.WriteLine("Product id {0}", prodid);
            Console.WriteLine("Product name {0}", prodname);
        }
    }

    class BinarySerializationDemo
    {
        static void Main()
        {
            Product p = new Product(1001, "Computer");

            //Create a object of FileStream to save the serialized data
            FileStream fs = new FileStream("..\\..\\productsData.txt", FileMode.Create, FileAccess.Write);

            //create a BinaryFormatter
            BinaryFormatter fmt = new BinaryFormatter();

            //serialize the object by using Serialize() methode
            fmt.Serialize(fs, p);
            Console.WriteLine("Product object serialized");
            fs.Close();

            //deserialize the object
            fs = new FileStream("..\\..\\productsData.txt", FileMode.Open, FileAccess.Read);
            p = (Product)fmt.Deserialize(fs);
            Console.WriteLine("Product object deserialized");
            p.Show();
            fs.Close();
            
            Console.ReadLine();
        }
    }
}
Hope this post will help you for simple implementation of binary serialization.
Happy Coding !!! Have some look on .NET Quizzes