May 31, 2013

Top 5 Mistakes People Make, When Looking for a New Job

Today I read an article which had written by "Catherine Conlan", monster's contributor writer. In this article Conlan quoted the thoughts of "Lisa Arnold", director of recuriting at Versique in Minneapolis.  

She identified those five mistakes which is commonly occur when someone is trying to search a job. In this article I try to combine their thoughts along with generous advices of Amir Zahoor, Chair IEEE Sweden GOLD Section. I hope that after reading this article, you will try to avoid these mistakes in future if you already did. :-) 

There are many ways to give yourself, the best odds when you’re looking for a job -- and just as many ways to ruin them. Here are five common mistakes that people make that keep them from getting the job of their dreams. 

Apply Without a Plan:

Suppose If you don't have a job you might feel like, desperately applying to every possible job that can help you and increase your chances of finding something that can work for you. In fact, this does not help at all and can distract you from going hard after the jobs you really have a chance with. “People who say ‘I need to consider anything and everything’ are really doing themselves a disservice,” says Lisa Arnold. A person who is general in looking for a job or in talking about what you have done is really going to be left behind in this market. Instead of this, a good approach is to identify the job that you really want and what you need to do to get it.

Ignore Your Online Presence:

A strong, professional online presence can be a big plus when you’re looking for a job. “I see a lot more clients really using those tools to do more due diligence on a candidate,” Arnold says. One of the first thing clients ask is, ‘How many connections do you have on LinkedIn?’ That’s starting to matter.” Sharing information through your social networks about issues in your field can show hiring managers that you are plugged-in and keeping up with changes in your industry. “It will display your brand,” Arnold says.

I agree with Lisa Arnoldbecause online presence helps us to keep our knowlegde upto date (now a days it becomes upto minute). Without online presence, there is a risk factor involve regarding what you know and how you adopt new things. “One in five employers use social networking sites to research job candidates, and close to 59% of them are influenced by your online presence,” says CareerBuilder.com. Online presence can do so much more; it can help you create a name for yourself and provide you with endless networking and career opportunities. There are five points related to "Why online presence is important?" by Forbes.com.

Make a Laundry-List Resume:

Many people put together resumes that are simply a travelogue of where they’ve been over their working years. This step-by-step plodding through your jobs is neither compelling nor useful to people making hiring decisions. Instead of highlighting the position and dates you worked at, talk about skills you gained, problems you solved, and any recognition or promotions you got because of them. "Make your resume less about descriptions and more about actions related what you have done when critical time came and how you manage the complex situations during development,"  Amir says.

Underestimate Your Value:

Once you’ve identified the job you want, spiffed up your resume and online presence, and done your homework on the company, don’t settle for less than you deserve. Find out what similar positions pay and your opportunities for advancement. “Go out there and know what your value is in the market and don’t deviate from that,” Arnold says. Too many times, she says, people tend to settle for something less. That affects the entire profession, lowering the value for the skill set.

May 28, 2013

Short Q/A's

This post will grow dynamically with the passage of time. It contains Short Q/A's related to some little queries.


Q1.  Why data is not submit on first time button click?

Ans. 
This is a normal behaviour of Asp.Net, you have to click somewhere else after entering the text before you hit the submit button. A solution is to provide instructions that user should use TAB key to enter data. That way the text in entered on hitting the TAB key and form then will be submit on first time.


Q2.  What is difference between ID and ClientID in jQuery/JavaScript?

Ans. 
ID: The ID generated in the final HTML is not guaranteed to remain the same as the one in your aspx source. When you'll put the controls inside naming containers the ID will have prepended one or several parent ids to ensure its uniqueness. 
ClientID: The ClientId property will always give you the final form of the ID attribute as it ends up in the HTML so it's always recommended to use that in your javascript.


Q3.  How to handle exception without Try Catch block?

Ans. 
You can get the exception on Application_Error method in Global.asax method. But keep in mind that it's not an alternative way you can use instead of try catch methods to handle exceptions. This will fire whenever an unhandled exception occur within your application. Other than that, you can't handle the exception here. 

void Application_Error(object sender, EventArgs e)
{
   Exception ex = Server.GetLastError();
}


Q4.  How to get last inserted ID from Sql Server?

Ans.  
     1) SELECT @@IDENTITY
     2) SELECT SCOPE_IDENTITY()
     3) SELECT IDENT_CURRENT(‘TableName’)

All of the above three will get the identity value but in different approches.


  • @@IDENTITY will return the last generated identity value produced on a connection, without based on the table that produced the value. While @@IDENTITY is limited to the current session, it is not limited to the current scope. This means that if we insert some record in Table1 which has a trigger on the insert and the trigger inserts a record in some other table2 then the @@IDENTITY will return the identity value inserted in Table2.
  • SCOPE_IDENTITY() will return the last IDENTITY value produced on a connection and by a statement in the same scope, without based on the table that produced the value. So we can say that this function is some identical to @@IDENTITY with one exception like @@IDENTITY will return the last identity value created in the current session, but it will also limit it to your current scope as well. So that means it will return identity value inserted in Table1.
  • IDENT_CURRENT will reutrn returns the last IDENTITY value produced in a table, Without based on the connection that created the value, and Without based on the scope of the statement that produced the value. IDENT_CURRENT is not limited by scope and session, so it will retrieve the last generated table identity value.


Q5.  What is difference between Override and new in OOPs?

Ans.
The override modifier extends the base class method, and the new modifier hides it. 
Override: Override concept comes when you have parent class and child class sceneriao.
new: New key word is used when you want to create an object for any class.

Encrypt and Decrypt Query String

On web, there are a lot of encryption decryption methods are available, you can choose any of them.

Redirecting from one page to another page using query string is done by every developer around the world but best approach is to encode your query parameter and decode it in next page. 

But here I'm using simple way of encoding and decoding using ASCII encode decode class. So, let's get down to the code here is basic encryption.

-------------------------------
ASPX CODE  (PAGE 1) :
-------------------------------
<div>
    <p>
        <asp:TextBox ID="InputText" runat="server" />
    </p>
    <p>
        <asp:Button ID="SubmitButton" runat="server" Text="Submit" OnClick="SubmitButton_Click" />
    </p>
</div>
------------------------------------------
ASPX CODE-BEHIND  (PAGE 1) :
------------------------------------------
protected void SubmitButton_Click(object sender, EventArgs e)
{
    string inputText = InputText.Text.Trim();

    if (inputText != "")
    {
        string encodeString = 
            Convert.ToBase64String(ASCIIEncoding.ASCII.GetBytes(inputText));
        Response.Redirect("Page2.aspx?search=" + encodeString);
    }
}
------------------------------------------
ASPX CODE-BEHIND  (PAGE 2) :
------------------------------------------
protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        string decodeString =
            ASCIIEncoding.ASCII.GetString(Convert.FromBase64String(Request.QueryString["search"]));

        if (decodeString == "1")
        {
            Response.Write("Hello World");
        }
        else 
        {
            Response.Write(decodeString);
        }
    }
}

Output will be as:



Cheers

Display Images From Database in DataList Control

In this post, I'm showing you how to bind images directly from database using Asp.net control DataList. Directly from database means images are not store on physical place and need to retrieve it from database, where it present as binary format. 

First we convert image from binary format into byte format then using Asp.Net Handle (.ashx) bind image to DataList Image controller.

------------------
ASPX Code : 
------------------

<asp:Repeater ID="rImages" runat="server">
    <ItemTemplate>
        <li><a href='<%# "Images/" & ImageHandler.ashx?ID=" + Eval("TranID") %>' 
            class="highslide" onclick="return hs.expand(this)"><img src='<%# "Images/" & 
            ImageHandler.ashx?ID=" + Eval("TranID") %>' width="130" height="100" /></a></li>
    </ItemTemplate>
</asp:Repeater>

------------------
ASHX Code: 
------------------

public void ProcessRequest(HttpContext context)
{
    int tranId = Convert.ToInt32((context.Request.QueryString["ProductMasterID"]));

    if (tranId > 0)
    {
        var memoryStream = new MemoryStream();
        /*
        // Connect to database -- Here I am using LINQ to SQL architecture
         * 
         * var dataContext = new DatabaseDataContext(Classes.Constant.GetConnectionString());
         * var getImageName = dataContext.MapImage.Where(p => p.TranId == tranId).Single();
         * 
         * if (getImageName.ImageName.Trim() != "") 
         * {
         *    byte[] imageFile = (byte[])getImageName.Trim();
         *    memoryStream.Write(imageFile, 0, imageFile.Length);
              context.Response.Buffer = true;
            
              if (file.Length > 0)
              {
                 context.Response.BinaryWrite(imageFile);
                 memoryStream.Dispose();
              }
         * }
         */
    }
}

Hope you understand now how to bind images from database using Asp.net Handler. Stay tune!

May 27, 2013

ModalPopup like effect using simple JavaScript and CSS

In Ajax control toolkit, you find many fantastic controls, one of them is "ModalPopupExtender". This extender is not always a desirable choice to use because sometimes you are not using control kit in your project.

To start with, you can seen ModalPopup effect here. But in this post, I try to elaborate simple way of creating this effect using JavaScript and CSS.

What is ModalPopup? 

Its nothing but a page that is inaccessible because it is cover with div having z-index (Like of 3D) set to make it blocking. The opacity of overlaying div can be set to make it see through so that you can seen in background but blurred and frozen.

Another div is also present in same page (hidden by default) becomes visible and its z-index is set higher than that of overlaying div making it clearly and also accessible.

Let starts coding. 
  • Create a website in Visual Studio or Visual Web Developer and there you see a .aspx page named as (Default.aspx). 
  • Open Default.aspx page, here we need controls like (1 TextBox and 1 Button. 2 Div's, we'll use one div for display as modal popup and other to overlay screen).
  • Firstly, create a div which we will display as ModalPopup like:

<div id="modalMsg" style="width: 200px; height: 100px; border-color: Black; border-style: solid;
    color: Red;" class="HideModal">
    This is modalpopup window
    <asp:LinkButton ID="lnkOk" runat="server" OnClientClick="return RemoveModal();" Text="OK" />
</div>
  • Now create a div for overlay screen as:
<div id="overlay"></div>
  • To set overlay screen and making popup visible functionality, here we need to add some CSS as:

<style type="text/css">
    .ShowModal
    {
        top: 200px;
        left: 250px;
        z-index: 1000;
        position: absolute;
        background-color: White;
        display: block;
    }
    .HideModal
    {
        display: none;
    }
    .OverlayEffect
    {
        background-color: black;
        filter: alpha(opacity=70);
        opacity: 0.7;
        width: 100%;
        height: 100%;
        z-index: 400;
        position: absolute;
        top: 0;
        left: 0;
    }
</style>
  • After CSS applied on page, add Javascript function has to be created which will assign css class to overlay and modal message div's as:

<script type="text/javascript">
    function DisplayModal()
    {
        document.getElementById("overlay").style.height = document.body.clientHeight + 'px';
        document.getElementById("overlay").className = "OverlayEffect";
        document.getElementById("modalMsg").className = "ShowModal";
    }
    function RemoveModal()
    {
        document.getElementById("modalMsg").className = "HideModal";        
        document.getElementById("overlay").className = "";
        return false;
    }
</script>

  • Now finally add these lines in Default.aspx code behind which call JavaScript function and update label in modal div. This all works using RegisterStartupScript method as: 

protected void SubmitButton_Click(object sender, EventArgs s) 
{
    ClientScript.RegisterStartupScript(this.GetType(), "JsModal", "DisplayModal()", true);
}

After button clicked, DisplayModal function will be called which will set the CSS class of both overlay and modalmessage div.

CSS class takes care of giving appropriate effect. The RemoveModal function used by "OK" button present in modal popup window to vanish the effect.

This method uses only CSS and javascript. so, it works in every browser.

The output is displayed as this



For whoever interested, here is complete page code to get going:


<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_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>Modal Popup using JavaScript and CSS</title>
    <style type="text/css">
        .ShowModal
        {
            top: 200px;
            left: 250px;
            z-index: 1000;
            position: absolute;
            background-color: White;
            display: block;
        }
        .HideModal
        {
            display: none;
        }
        .OverlayEffect
        {
            background-color: black;
            filter: alpha(opacity=70);
            opacity: 0.7;
            width: 100%;
            height: 100%;
            z-index: 400;
            position: absolute;
            top: 0;
            left: 0;
        }
    </style>

    <script type="text/javascript">
        function DisplayModal()
        {
            document.getElementById("overlay").style.height = document.body.clientHeight + 'px';
            document.getElementById("overlay").className = "OverlayEffect";
            document.getElementById("modalMsg").className = "ShowModal";
        }
        function RemoveModal()
        {
            document.getElementById("modalMsg").className = "HideModal";        
            document.getElementById("overlay").className = "";
            return false;
        }
    </script>

</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:Button ID="SubmitButton" runat="server" Text="Click Here" OnClick="SubmitButton_Click" />
    </div>
    <div id="overlay"></div>
    <div id="modalMsg" style="width: 200px; height: 100px; border-color: Black; border-style: solid;
        color: Red;" class="HideModal">
        This is modalpopup window
        <asp:LinkButton ID="lnkOk" runat="server" OnClientClick="return RemoveModal();" Text="OK" />
    </div>
    </form>
</body>
</html>

protected void SubmitButton_Click(object sender, EventArgs s) 
{
    ClientScript.RegisterStartupScript(this.GetType(), "JsModal", "DisplayModal()", true);
}

May 25, 2013

Leaders VS Manager - Robyn Benincasa

Today I read a article in which Robyn Benincasa clearly identify the difference between Leader & Manager. This will give you a better way to understand both roles separately.

Taking a team from ordinary to extraordinary means understanding and embracing the difference between management and leadership. 

According to writer and consultant Peter Drucker
"Management is doing things right; leadership is doing the right things." 

Manager:

Manager and leader are two completely different roles, although we often use the terms interchangeably. Managers are facilitators of their team members’ success. They ensure that their people have everything they need to be productive and successful; that they’re well trained, happy and have minimal roadblocks in their path; that they’re being groomed for the next level; that they are recognized for great performance and coached through their challenges.

Leaders:

Conversely, a leader can be anyone on the team who has a particular talent, who is creatively thinking out of the box and has a great idea, who has experience in a certain aspect of the business or project that can prove useful to the manager and the team. A leader leads based on strengths, not titles.

The best managers consistently allow different leaders to emerge and inspire their team-mates (and themselves!) to the next level.

When you’re dealing with ongoing challenges and changes, and you’re in uncharted territory with no means of knowing what comes next, no one can be expected to have all the answers or rule the team with an iron fist based solely on the title on their business card. It just does not work for day-to-day operations. Sometimes a project is a long series of obstacles and opportunities coming at you at high speed, and you need every ounce of your collective hearts and minds and skill sets to get through it.

This is why the military style of top-down leadership is never effective in the fast-paced world of adventure racing or, for that matter, our daily lives (which is really one big, long adventure, hopefully!). I truly believe in Tom Peters’s observation that the best leaders don’t create followers; they create more leaders. When we share leadership, we’re all a heck of a lot smarter, more nimble and more capable in the long run, especially when that long run is fraught with unknown and unforeseen challenges.

Change leadership styles:

Not only do the greatest team-mates allow different leaders to consistently emerge based on their strengths, but also they realize that leadership can and should be situational, depending on the needs of the team. Sometimes a team-mate needs a warm hug. Sometimes the team needs a visionary, a new style of coaching, someone to lead the way or even, on occasion, a kick in the bike shorts. For that reason, great leaders choose their leadership style like a golfer chooses his or her club, with a calculated analysis of the matter at hand, the end goal and the best tool for the job.

My favourite study on the subject of Kinetic Leadership is Daniel Goleman’s Leadership. That Gets Results, a landmark 2000 Harvard Business Review study. Goleman and his team completed a three-year study with over 3,000 middle-level managers. Their goal was to uncover specific leadership behaviors and determine their effect on the corporate climate and each leadership style’s effect on bottom-line profitability.

The research discovered that a manager’s leadership style was responsible for 30% of the company’s bottom-line profitability! That’s far too much to ignore. Imagine how much money and effort a company spends on new processes, efficiencies, and cost-cutting methods in an effort to add even one percent to bottom-line profitability, and compare that to simply inspiring managers to be more kinetic with their leadership styles. It’s a no-brainer.

Here are the six leadership styles Goleman uncovered among the managers he studied, as well as a brief analysis of the effects of each style on the corporate climate:

1.    The pace-setting leader expects and models excellence and self-direction. If this style were summed up in one phrase, it would be “Do as I do, now.” The pacesetting style works best when the team is already motivated and skilled, and the leader needs quick results. Used extensively, however, this style can overwhelm team members and squelch innovation.

2.   The authoritative leader mobilizes the team toward a common vision and focuses on end goals, leaving the means up to each individual. If this style were summed up in one phrase, it would be “Come with me.” The authoritative style works best when the team needs a new vision because circumstances have changed, or when explicit guidance is not required. Authoritative leaders inspire an entrepreneurial spirit and vibrant enthusiasm for the mission. It is not the best fit when the leader is working with a team of experts who know more than him or her.

3.  The affiliative leader works to create emotional bonds that bring a feeling of bonding and belonging to the organization. If this style were summed up in one phrase, it would be “People come first.” The affiliative style works best in times of stress, when team-mates need to heal from a trauma, or when the team needs to rebuild trust. This style should not be used exclusively, because a sole reliance on praise and nurturing can foster mediocre performance and a lack of direction.

4. The coaching leader develops people for the future. If this style were summed up in one phrase, it would be “Try this.” The coaching style works best when the leader wants to help team-mates build lasting personal strengths that make them more successful overall. It is least effective when team-mates are defiant and unwilling to change or learn, or if the leader lacks proficiency.

5. The coercive leader demands immediate compliance. If this style were summed up in one phrase, it would be “Do what I tell you.” The coercive style is most effective in times of crisis, such as in a company turnaround or a takeover attempt, or during an actual emergency like a tornado or a fire. This style can also help control a problem team-mate when everything else has failed. However, it should be avoided in almost every other case because it can alienate people and stifle flexibility and inventiveness.

6. The democratic leader builds consensus through participation. If this style were summed up in one phrase, it would be “What do you think?” The democratic style is most effective when the leader needs the team to buy into or have ownership of a decision, plan, or goal, or if he or she is uncertain and needs fresh ideas from qualified team-mates. It is not the best choice in an emergency situation, when time is of the essence for another reason or when team-mates are not informed enough to offer sufficient guidance to the leader.

7Cs of Success - Brian Tracy

Yesterday I read Brian Tracy article related to 7Cs of Success which helped me a lot to boost my passion and knowledge. That's why I share this with all of you and I'm sure that it will help you understand things clearly.

Clarity:
80% of success comes from being clear on who you are, what you believe in and what you want. 

Competence:
You can't climb to the next rung on the ladder until you are excellent at what you do now. 

Constraints: 
80% of all obstacles to success come from within. Find out what is constraining in you or your company and deal with it. 

Concentration: 
The ability to focus on one thing single-mindedly and see it through until it's done takes more character than anything else. 

Creativity: 
Flood your life with ideas from many sources. Creativity needs to be exercised like a muscle; if you don't use it you'll lose it. 

Courage: 
Most in demand and least in supply, courage is the willingness to do the things you know are right. 

Continuous learning: 
Read, at the very least, one book a week on business to keep you miles ahead of the competition. And just as you eat and bathe, organize your time so you spend 30 minutes a day exploring email, sending messages, going through websites, because like exercise, it's the only way you can keep on top of technology. If you get away from it, you'll lose your edge.

May 22, 2013

Approaches in Entity Framework

Entity Framework is preferred method of Microsoft  to access data in NET applications. It supports strongly-typed access through LINQ and allow  developers to program against a conceptual model that reflects application logic rather than a relational model that reflects the database structure. 

There are three types of approaches in Entity framework.
  1. Code First
  2. Model First
  3. Database First

Code First:

In Code First approach, it provides a new development pattern that provides an alternative approach to Model First and Database First and create databases of us based on our classes. 

In this approach, there is no EDM at all and the database is generated from the data access code that you write. With this you write the code you want as plain classes, then the EF models are inferred from that at run-time. These models are used to generate the database, if you like, as well as provide the mapping from your hand-written classes. Just because you can’t see the EDM though doesn’t mean it’s not there. The metadata is still created under the covers and the code you write is used to create it at runtime. You should note that this approach is only enabled by the downloadable CTP 'add on'.

Model First:

In Model First approach, where you have a clean slate to start and freely able to use expressive power to design whatever you like. You can use this feature using EF Designer.

If you have a pre-existing database or would like to design the database first exactly how you’d like it, you can import the database into EF and the EDMX will be created from it. This will include all the usual metadata, CSDL, SSDL and the mapping between them just as model-first does. However it’s likely that you will want to change the model once you have imported the database to better map the database tables onto the entities and hierarchical relationships in your model. With this it cannot be inferred what the original model’s hierarchy and structure was and so the generated model can be tweaked accordingly to your taste. 

Database First:

In Database First approach, it provides an alternative to the Code First and Model First approaches to the EDM and it creates model codes (classes, properties, DbContext etc.) from the database in the project and those classes become the link between the database and controller.

Hope you understand well all these concept.

May 21, 2013

Parameterized IN Clause with ADO.Net and LINQ

Now a days on Asp.Net forum, many newbie developers asked questions related to parametrized IN clause with ADO.Net. In this post, I am showing you the way to use it in both (ADO.Net & LINQ).

Just in case if you don't know how to use IN clause and what is IN clause, IN clause takes a sub-query or expression. The expression is a comma-separated list of values like:

SELECT * FROM Student WHERE StudentID IN (2, 5)

Above query will pick all students that have a StudentID of 2 or 5. Above query saves your multiple OR clauses in WHERE condition like:


SELECT * FROM Student WHERE StudentID = 2 OR StudentID = 5

If you allow the user to choose multiple options using CheckBoxes or similar. You probably doing like this:


SELECT * FROM Student WHERE StudentID IN (@List)
Command.Parameters.AddWithValue("@List", values);

But it doesn't work because SQL Server doesn't know it should parse whatever @List has as a value into a series of individual values, unless you tell it what to do. There are a many SQL Server-specific solutions available for this, which are detailed and maintained by SQL Server MVP's. But they all require that you have access to the SQL Server to create stored procedures etc.  Or if you are not using a database such as Access which doesn't support stored procedures containing control of flow code. Then? What we really want is a solution that can be applied using purely application code.

parametrized query consists of a SQL statement and a collection of Parameter objects. What we really need to do is construct something like the follow:


SELECT * FROM Student WHERE StudentID IN (@p1, @p2, @p3)

Since an IN clause contains a variable number of values in its expression, it is impossible to know at design time how many parameters are needed, so these along with the SQL itself need to be constructed at runtime. And once you get your head around that, the rest should fall nicely into place.

I'm going to make this easy and illustrate using Checkboxes - the elements are raw HTML inputs of type checkbox:


<input type="checkbox" name="Student" value="1" />John<br />
<input type="checkbox" name="Student" value="2" />Martin<br />
<input type="checkbox" name="Student" value="3" />Smith<br />
<input type="checkbox" name="Student" value="4" />Micheal<br />
<input type="checkbox" name="Student" value="5" />Steave<br />
<input type="checkbox" name="Student" value="6" />Bevan<br />
<input type="checkbox" name="Student" value="7" />Andrew<br />
<input type="checkbox" name="Student" value="8" />James<br />
<input type="checkbox" name="Student" value="9" />Kallis<br />

Moving on, in the Button_Click event of this page, the following code appears:


protected void Button1_Click(object sender, EventArgs e)
{
  var sqlQuery = "SELECT * FROM Student WHERE StudentID IN ({0}) ORDER BY StudentID";
  var studentIDs = "1, 5, 9";
  var studentArray = studentIDs.Split(',');

  var parameters = studentArray.Select((s, i) => "@p" + i.ToString()).ToArray();
  var inClause = string.Join(",", parameters);

  using (var connection = 
            new SqlConnection(
              ConfigurationManager.ConnectionStrings["TestDB"].ConnectionStringt))
  {
    var command = new SqlCommand(string.Format(sqlQuery, inClause), connection);

    for (var i = 0; i < studentArray.Length; i++)
    {
       command.Parameters.AddWithValue(parameters[i], studentArray[i]);
    }

    connection.Open();
    var reader = command.ExecuteReader();
    GridView1.DataSource = reader;
    GridView1.DataBind();
  }
}

If you are using LINQ To SQL, or LINQ with the Entity Framework, the answer is much easier. You simpy use the Contains() extension method:



protected void Button1_Click(object sender, EventArgs e)
{
  var db = new TestDBDataContext();
  var studentIDs = "1, 5, 9";
  var output = Array.ConvertAll(studentIDs, s => int.Parse(s));

  var query = db.Students
                  .Where(s => output.Contains(s.StudentID))
                  .OrderBy(s => s.StudentID);

  GridView1.DataSource = query;
  GridView1.DataBind();
}

If you encouter an issue from compiler around the Contains() method, it might be possible that Student.StudentID is by default a nullable int. The compiler is mightily satisfied if you explicitly cast s.StudentID to an int:


.Where(s => output.Contains((int)s.StudentID))

Hope you understand whole article very well. Stay tune! :)

May 20, 2013

Model Binding Feature in Asp.Net 4.5

In Asp.Net 4.5, many new features has been shipped. Here I discuss about Model Binding feature which is creating their own space among others.

Data bound controls are the major part of typical web form applications and we spend a lot of time in writing code related to different events of that control.

The new functionality makes task easier so that you as a developer can focus on data and entities. To better understand the code let me first explain the scenario.

We want to display all the records of above table in GridView control which  also supports Paging and Sorting functionality. How would we do this?

OLDER WAY

To display data in Gridview, we required markup like that:

<asp:GridView ID="EmployeeGridView" runat="server" AllowSorting="true"
OnSorting="EmployeeGridView_Sorting">
</asp:GridView>


To populate GridView from code-behind, we required code as:

var dataContext = new DatabaseDataContext(Classes.GetConnectionString);
var employeeList = (from e in dataContext.Employees
                   select e).ToList();

if (employeeList.Count > 0) 
{
   EmployeeGridView.DataSource = employeeList;
   EmployeeGridView.DataBind();
}


And we need to create separate events of GridView, in order to use Paging or Sotring like,

protected void EmployeeGridView_Sorting(object sender, GridViewSortEventArgs e)
{
    var dataContext = new DatabaseDataContext(Classes.GetConnectionString);
    var employeeList = (from e in dataContext.Employees
                   select e).ToList();

    if (employeeList.Count > 0) 
    {
       EmployeeGridView.DataSource = employeeList;
       EmployeeGridView.DataBind();
    }
}



NEW WAY

Asp.Net 4.5 introduce a new feature called Model Binding which take advantage of System.Linq.IQueryable type.

public IQueryable<Employee> GetEmployeesList()
{
    var dataContext = new DatabaseDataContext(Classes.GetConnectionString);
    IQueryable<Employees> employeeList = (from e in dataContext.Employees
                   select e).ToList();
    return employeeList;
}


Now write a Gridview control markup as:

<asp:GridView ID="EmployeeGridView" runat="server" 
    ItemType="DataBindingSample.Employees" SelectMethod="GetEmployees">
</asp;GridView>

Here:
  • ItemType refers to table name define within IQueryable tag
  • SelectMethod refers to name of method

Now run the application, it will show you all records from table "Employee" in GridView. If you want to add Paging or Sorting functionality, go ahead just allow both functionality in GridView markup and rest of things will be handle by Model Binding itself.

It would change the way how data controls were generally managed in web form applications. Stay tuned!

May 16, 2013

Compare similarity of two strings in terms of percentage

In this post, I am showing you how to check the similarity between two string in terms of percentage which is acceptable by end user. To check similarity we have a formula which helps us to find match in %. In below example, I am showing two pattern of string:

  • One is to use string array
  • Other one is to user string sentence and split it to make array
The formula to check similarities are:

Similarity (%) = 100 * (commonItems * 2) / (total item in string1 + total item in string2)

Lets start coding, here I show the code logic both in C# and VB.Net.

------
C# :
------
----------------------
String as Array:
----------------------
// The formula to calculate similarity between two string is:
// Similarity (%) = 100 * (commonItems * 2) / (total item in string1 + total item in string2)

int list1Length, list2Length, commonItemLength;

var list1 = new string[] { "1", "2", "3", "4", "5", "6" };
var list2 = new string[] { "2", "3", "4" };
var commonList = list1.Intersect(list2);

list1Length = list1.Length;
list2Length = list2.Length;
commonItemLength = commonList.Count();

double similarity = 100 * (commonItemLength * 2) / (list1Length + list2Length);
Console.WriteLine("Similarity b/w strings: " + similarity + "%");
----------------------------
String as Sentence:
----------------------------
// The formula to calculate similarity between two string is:
// Similarity (%) = 100 * (commonItems * 2) / (total item in string1 + total item in string2)

int list1Length, list2Length, commonItemLength;

string string1 = "jedan, dva, tri, cetri, PET, sest45 sedamytyty osam";
string string2 = "dva, cetri, pet, sedam88 dvadeset osamdeset";

var string1Split = string1.Split(',');
var string2Split = string2.Split(',');

var commonList = string1Split.Intersect(string2Split);

list1Length = string1Split.Length;
list2Length = string2Split.Length;
commonItemLength = commonList.Count();

double similarity = 100 * (commonItemLength * 2) / (list1Length + list2Length);
Console.WriteLine("Similarity b/w strings: " + similarity + "%");

--------------
VB.NET :
--------------
----------------------
String as Array:
----------------------
' The formula to calculate similarity between two string is:
' Similarity (%) = 100 * (commonItems * 2) / (total item in string1 + total item in string2)

Dim list1Length As Integer, list2Length As Integer, commonItemLength As Integer

Dim list1 = New String() {"1", "2", "3", "4", "5", "6"}
Dim list2 = New String() {"2", "3", "4"}
Dim commonList = list1.Intersect(list2)

list1Length = list1.Length
list2Length = list2.Length
commonItemLength = commonList.Count()

Dim similarity As Double = 100 * (commonItemLength * 2) / (list1Length + list2Length)
Console.WriteLine("Similarity b/w strings: " + similarity + "%")
----------------------------
String as Sentence:
----------------------------
' The formula to calculate similarity between two string is:
' Similarity (%) = 100 * (commonItems * 2) / (total item in string1 + total item in string2)

Dim list1Length As Integer, list2Length As Integer, commonItemLength As Integer

Dim string1 As String = "jedan, dva, tri, cetri, PET, sest45 sedamytyty osam"
Dim string2 As String = "dva, cetri, pet, sedam88 dvadeset osamdeset"

Dim string1Split = string1.Split(","C)
Dim string2Split = string2.Split(","C)

Dim commonList = string1Split.Intersect(string2Split)

list1Length = string1Split.Length
list2Length = string2Split.Length
commonItemLength = commonList.Count()

Dim similarity As Double = 100 * (commonItemLength * 2) / (list1Length + list2Length)
Console.WriteLine("Similarity b/w strings: " + similarity + "%")

Password Encryption Decryption


To secure the data of any type is the critical issue now a days. There are plenty of method available on internet to secure your data from breaching / hacking. Developers around the world using different techniques to secure the password of their applications. In this post I add another method to secure your passwords.

------
C# :
------

------------------
NameSpaces :
------------------

using System.Security.Cryptography;
using System.Configuration;
using System.Data.SqlClient;

------------------
Initialization : 
------------------

const string passphrase = "password";

---------------
Encryption :
---------------

private static string EncryptPassword(string password)
{
    byte[] results;
    var uTF8Encoding = new UTF8Encoding();
    var HashProvider = new MD5CryptoServiceProvider();
    byte[] TDESKey = HashProvider.ComputeHash(uTF8Encoding.GetBytes(passphrase));
    var tDESAlgorithm = new TripleDESCryptoServiceProvider();

    tDESAlgorithm.Key = TDESKey;
    tDESAlgorithm.Mode = CipherMode.ECB;
    tDESAlgorithm.Padding = PaddingMode.PKCS7;
    byte[] dataToEncrypt = uTF8Encoding.GetBytes(password);

    try
    {
        ICryptoTransform Encryptor = tDESAlgorithm.CreateEncryptor();
        results = Encryptor.TransformFinalBlock(dataToEncrypt, 0, dataToEncrypt.Length);
    }
    finally
    {
        tDESAlgorithm.Clear();
        HashProvider.Clear();
    }

    return Convert.ToBase64String(results);
}

---------------
Decryption :
---------------

private static string DecryptPassword(string password)
{
    byte[] results;
    var uTF8Encoding = new UTF8Encoding();
    var hashProvider = new MD5CryptoServiceProvider();
    byte[] tDESKey = hashProvider.ComputeHash(uTF8Encoding.GetBytes(passphrase));
    var tDESAlgorithm = new TripleDESCryptoServiceProvider();

    tDESAlgorithm.Key = tDESKey;
    tDESAlgorithm.Mode = CipherMode.ECB;
    tDESAlgorithm.Padding = PaddingMode.PKCS7;
    byte[] dataToDecrypt = Convert.FromBase64String(password);

    try
    {
        ICryptoTransform Decryptor = tDESAlgorithm.CreateDecryptor();
        results = Decryptor.TransformFinalBlock(dataToDecrypt, 0, dataToDecrypt.Length);
    }
    finally
    {
        tDESAlgorithm.Clear();
        hashProvider.Clear();
    }

    return uTF8Encoding.GetString(results);
}

-------------
VB.Net :
-------------

-----------------
Initialization :
--------------------

Imports System.Security.Cryptography
Imports System.Configuration
Imports System.Data.SqlClient


---------------
Encryption :
---------------


Private Shared Function EncryptPassword(ByVal password As String) As String
 Dim results As Byte()
 Dim uTF8Encoding = New UTF8Encoding()
 Dim HashProvider = New MD5CryptoServiceProvider()
 Dim TDESKey As Byte() = HashProvider.ComputeHash(uTF8Encoding.GetBytes(passphrase))
 Dim tDESAlgorithm = New TripleDESCryptoServiceProvider()

 tDESAlgorithm.Key = TDESKey
 tDESAlgorithm.Mode = CipherMode.ECB
 tDESAlgorithm.Padding = PaddingMode.PKCS7
 Dim dataToEncrypt As Byte() = uTF8Encoding.GetBytes(password)

 Try
  Dim Encryptor As ICryptoTransform = tDESAlgorithm.CreateEncryptor()
  results = Encryptor.TransformFinalBlock(dataToEncrypt, 0, dataToEncrypt.Length)
 Finally
  tDESAlgorithm.Clear()
  HashProvider.Clear()
 End Try

 Return Convert.ToBase64String(results)
End Function



------------------
Dencryption :
------------------


Private Shared Function DecryptPassword(ByVal password As String) As String
 Dim results As Byte()
 Dim uTF8Encoding = New UTF8Encoding()
 Dim hashProvider = New MD5CryptoServiceProvider()
 Dim tDESKey As Byte() = hashProvider.ComputeHash(uTF8Encoding.GetBytes(passphrase))
 Dim tDESAlgorithm = New TripleDESCryptoServiceProvider()

 tDESAlgorithm.Key = tDESKey
 tDESAlgorithm.Mode = CipherMode.ECB
 tDESAlgorithm.Padding = PaddingMode.PKCS7
 Dim dataToDecrypt As Byte() = Convert.FromBase64String(password)

 Try
  Dim Decryptor As ICryptoTransform = tDESAlgorithm.CreateDecryptor()
  results = Decryptor.TransformFinalBlock(dataToDecrypt, 0, dataToDecrypt.Length)
 Finally
  tDESAlgorithm.Clear()
  hashProvider.Clear()
 End Try

 Return uTF8Encoding.GetString(results)
End Function

May 14, 2013

Adding Dynamic Rows in ASP.Net GridView Control with TextBoxes

Now a days on Asp.Net Forum, many people ask how to add rows dynamically to gridview. In this example I am show you to generate a row in Gridview on button click.

To get started, lets use GridView control. Modify the markup of code as:

<asp:GridView ID="GridView1" runat="server" ShowFooter="true" AutoGenerateColumns="false">
    <Columns>
        <asp:BoundField DataField="RowNumber" HeaderText="Row Number" />
        <asp:TemplateField HeaderText="Name">
            <ItemTemplate>
                <asp:TextBox ID="NameText" runat="server" />
            </ItemTemplate>
        </asp:TemplateField>
        <asp:TemplateField HeaderText="Country">
            <ItemTemplate>
                <asp:TextBox ID="CountryText" runat="server" />
            </ItemTemplate>
        </asp:TemplateField>
        <asp:TemplateField HeaderText="City">
            <ItemTemplate>
                <asp:TextBox ID="CityText" runat="server" />
            </ItemTemplate>
            <FooterStyle HorizontalAlign="Right" />
            <FooterTemplate>
                <asp:Button ID="AddRowButton" runat="server" Text="Add New Row" 
                    OnClick="ButtonAdd_Click" />
            </FooterTemplate>
        </asp:TemplateField>
    </Columns>
</asp:GridView>

Now lets switch to the code behind part:

private void SetInitialRowToGrid()
{
    // Initialize and Set initial row of Datatable
    var tempDataTable = new DataTable();
    tempDataTable.Columns.Add("RowNumber");
    tempDataTable.Columns.Add("NameText");
    tempDataTable.Columns.Add("CountryText");
    tempDataTable.Columns.Add("CityText");
    tempDataTable.Rows.Add("1", "", "", "");

    // Store that datatable into viewstate
    ViewState["TempTable"] = tempDataTable;

    // Attach Gridview Datasource to datatable
    GridView1.DataSource = tempDataTable;
    GridView1.DataBind();
}

private void AddNewRowToGrid()
{
    int rowIndex = 0;

    if (ViewState["TempTable"] != null)
    {
        // Get TempTable from viewstate
        var tempTable = (DataTable)ViewState["TempTable"];
        DataRow tempRow = null;

        if (tempTable.Rows.Count > 0)
        {
            for (int i = 1; i <= tempTable.Rows.Count; i++)
            {
                // Get Grid's TextBox values
                var nameText = 
                    (TextBox)GridView1.Rows[rowIndex].Cells[1].FindControl("NameText");
                var countryText = 
                    (TextBox)GridView1.Rows[rowIndex].Cells[1].FindControl("CountryText");
                var cityText = 
                    (TextBox)GridView1.Rows[rowIndex].Cells[1].FindControl("CityText");

                // Create new row and update Row Number
                tempRow = tempTable.NewRow();
                tempRow["RowNumber"] = i + 1;

                tempTable.Rows[i - 1]["NameText"] = nameText.Text;
                tempTable.Rows[i - 1]["CountryText"] = countryText.Text;
                tempTable.Rows[i - 1]["CityText"] = cityText.Text;

                rowIndex++;
            }

            // Add data to datatable and viewstate
            tempTable.Rows.Add(tempRow);
            ViewState["TempTable"] = tempTable;

            // Attach Gridview Datasource to datatable
            GridView1.DataSource = tempTable;
            GridView1.DataBind();
        }
    }

    //Set Previous Data on Postbacks
    SetPreviousData();
}

private void SetPreviousData()
{
    int rowIndex = 0;

    if (ViewState["TempTable"] != null)
    {
        var tempTable = (DataTable)ViewState["TempTable"];

        if (tempTable.Rows.Count > 0)
        {
            for (int i = 0; i < tempTable.Rows.Count; i++)
            {
                var nameText = 
                    (TextBox)GridView1.Rows[rowIndex].Cells[1].FindControl("NameText");
                var countryText = 
                    (TextBox)GridView1.Rows[rowIndex].Cells[2].FindControl("CountryText");
                var cityText = 
                    (TextBox)GridView1.Rows[rowIndex].Cells[3].FindControl("CityText");

                nameText.Text = tempTable.Rows[i]["NameText"].ToString();
                countryText.Text = tempTable.Rows[i]["CountryText"].ToString();
                cityText.Text = tempTable.Rows[i]["CityText"].ToString();

                rowIndex++;
            }
        }
    }
}

protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        this.SetInitialRowToGrid();
    }
}

protected void ButtonAdd_Click(object sender, EventArgs e)
{
    AddNewRowToGrid();
}

Hope you will find this post useful.

May 7, 2013

How To Validate Primary Key

If user enter duplicate Primary Key, then SqlException is raise from ADO.Net. To alert end user about duplication, use Try Catch block to capture this exception and show appropriate error to end user. To do so, use this

try
{
    // Your coding logic
}
catch (SqlException ex)
{
    if (ex.Number.Equals(2627))
    {
          // Display here Primary Key duplicate error
          lblError.Text = "Duplicate Number! Try Different";
    }
}

Stay tune :)