Tuesday, December 18, 2012

Select All the on focus in WPF textbox

WPF has made it possible to create beautiful and compelling user interfaces in .NET - but there are a few times when the built-in user experience behavior of some of the controls isn't quite what you'd expect.
One of these areas happens to be the focus behavior of text boxes.

The Problem

A common behavior in most Windows applications that users are accustomed to(often without realizing it), is that upon focus entering a textbox, the text is automatically selected. This makes it possible to click or tab in to a textbox and immediately start typing - and content will be automatically replaced. This behavior is part of standard Windows text boxes ... but not the WPF TextBox control.
The approach to resolving this that may occur to you, is to handle focus events on all TextBox control instances and call the convenient SelectAll() method to highlight all content. Unfortunately, it's not quite that simple. Beyond the fact that wiring every TextBox control in your application gets old fast, there are a number of subtle edge cases where this approach fails.
We're going to look at how we can restore this behavior to text box controls in your WPF applications with as little pain as possible - and make it work they way users would expect - in all cases.

The Approach

The first issue we're going to tackle is how to respond to focus behavior on all text boxes throughout an application. It may occur to you to create a global style for text box controls and use an EventSetter to subscribe to Control.GetFocus. Unfortunately, styles have a number of limitations that make them less than ideal for this purpose. You can't apply multiple styles to a single control in WPF - which means that text box styles throughout your application would need to replicate this behavior. The best you can do is create a common style that all other TextBox styles are based on. This is a fragile and awkward approach at best - and at worst it becomes problematic if one of the derived styles needs to apply its own processing on GetFocus.
Fortunately there's a better way: the EventManager class. EventManager provides us with a way to globally subscribe to events for a particular type of control, rather than on an instance-by-instance basis. As it turns out, a convenient place to put this code is in your Application class' OnStartup() method:

protected override void OnStartup(StartupEventArgs e)
{
    EventManager.RegisterClassHandler(typeof(TextBox), UIElement.GotFocusEvent,
                                     
new RoutedEventHandler(SelectAllText), true);
   
    base.OnStartup(e);
}

private static void SelectAllText(object sender, RoutedEventArgs e)
{
    var textBox = e.OriginalSource as TextBox;
    if (textBox != null)
        textBox.SelectAll();
}

So we're done now, right? Well ... not quite. A little experimentation will show that while using the keyboard to set focus works well, using the mouse doesn't work as expected: when clicked, the selection initially appears, and then promptly vanishes. The reason for this is that the TextBox control internally responds to the MouseDown event, which fires after GotFocus. The text box relies on that event to place the insertion caret at the location in the text box where the user clicked. Since all of this happens GotFocus, the selection we set is lost. We're going to fix that.

The Ultimate Solution

The solution presented here is a little different from that above - basically, we're going to divide focus processing into two separation mechanisms - one that deals with focus changes from the keyboard, and another that responds to focus established by clicking the mouse.
Dealing with keyboard focus is easy - WPF has a UIElement.GotKeyboardFocus event that we can respond to instead of the more generalized Control.GotFocus. The mouse is a little bit trickier. First, we don't want to break the default click handling that TextBox implements - so we're going to instead use the PreviewMouseLeftButtonDown event to intercept clicks before the control responds to them. Preview events, also known as tunneling events, are routed events where the direction of the route travels from the application root towards the element that raised the event and is reported as the source in event data. We can use the preview mouse event to selectively handle the mouse click only in those cases when the focus is not yet transferred to the text box.
Now that we've established the approach, let's look at the code:

public partial class App : Application
{
    protected override void OnStartup(StartupEventArgs e)
    {
        EventManager.RegisterClassHandler(typeof(TextBox), UIElement.PreviewMouseLeftButtonDownEvent,
           new MouseButtonEventHandler(SelectivelyHandleMouseButton), true);
        EventManager.RegisterClassHandler(typeof(TextBox), UIElement.GotKeyboardFocusEvent,
          new RoutedEventHandler(SelectAllText), true);

        base.OnStartup(e);
    }

    private static void SelectivelyHandleMouseButton(object sender, MouseButtonEventArgs e)
    {
        var textbox = (sender as TextBox);
        if (textbox != null && !textbox.IsKeyboardFocusWithin)
        {
            if( e.OriginalSource.GetType().Name == "TextBoxView" )
            {
                e.Handled = true;
                textbox.Focus();
            }
        }
    }

    private static void SelectAllText(object sender, RoutedEventArgs e)
    {
        var textBox = e.OriginalSource as TextBox;
        if (textBox != null)
            textBox.SelectAll();
    }
}

So let's break it down. In the OnStartup() method we globally register the GotKeyBoardFocus and PreviewMouseLeftButtonDown events to the handlers below.
The SelectAllText() method is the same as before. The SelectivelyHandleMouseButton() method provides the code that corrects the focus behavior on clicks. First, it checks that we're actually dealing with a TextBox control by casting the sender parameter to the appropriate type. If keyboard focus is not yet in that text box (which we check using the IsKeyboardFocusWithin property), it then marks the event as handled, and calls textbox.Focus() to transfer focus (which will trigger the GotKeyboardFocus event for us).
There's only one last bit of code here that deserves an explanation, the line:

   if( e.OriginalSource.GetType().Name == "TextBoxView" )

The last edge case we need to handle is when the user clicks in the "chrome" portion of a TextBox - things like the border or scroll bars. It would be really awkward to select the text each time the user clicked the scrollbar. To fix this, we need to test that the mouse click originated in the "textual" portion of the control - which happens to be implemented by the TextBoxView class. WPF is helps us out by notifying us of the original source of the event via the RoutedEventArgs.OriginalSource property. Unfortunately, this class is not public outside of WPF infrastructure code - so we have to test for it by it's name. This is by far the least attractive aspect of the code shown above ... but sadly, it's the only reliable solution I've found so far.

Conclusion

So let's look at what we've learned so far.
  1. The built-in WPF TextBox control doesn't automatically select text when it receives focus.
  2. We can globally respond to events from any WPF control using the EventManager.RegisterGlobalHandler() method.
  3. We can use the OnStartup() method of the Application class to centrally register our handlers when the application loads.
  4. Focus behavior in WPF varies slightly depending on whether the control receives focus via the mouse or keyboard.
  5. We can use the PreviewXXX family of events to intercept clicks and supply our own event handling before the TextBox controls responds.
  6. We can use the RoutedEventArgs.OriginalSource property to avoid highlighting a selection when the original click events occurs within a non-content area of the TextBox control.
Put this all together, and we have an elegant, centralized solution to selecting the text inside the TextBox control when it receives focus.

Tuesday, July 10, 2012

Reverse a Linked-list. Write code in C.

There are multiple ways to go about this. Let’s first look at a recursive solution.

Recursive Method:

Node * reverse( Node * ptr , Node * previous)
{
    Node * temp;
    if(ptr->next == NULL) {
        ptr->next = previous;
        return ptr;
    } else {
        temp = reverse(ptr->next, ptr);
        ptr->next = previous;
        return temp;
    }
}
reversedHead = reverse(head, NULL);
 
Non-Recursive Method
 
Node * reverse( Node * ptr )
{
    Node * temp;
    Node * previous = NULL;
    while(ptr != NULL) {
        temp = ptr->next;
        ptr->next = previous;
        previous = ptr;
        ptr = temp;
    }
    return previous;
}

Sunday, July 8, 2012

What is thread safe code?

Thread safety is a programming concept applicable in the context of multi-threaded programs. A method or piece of code is thread-safe if it only manipulates shared data structures in a manner that guarantees safe execution by multiple threads at the same time.

Example: Methods used in Logger, to write a log file, should be threading safe for an application that runs under multi-threading environment.

Difference between Managed code and Native code

Native Code: Native code is computer programming (code) which generally written in C, C++ language and after compilation its IL is specific to the Processor Architecture. With respect to .net programming, Native code is the code is not managed code. The code takes care of allocation and de-allocation of every bit of memory to object. There is no garbage collection, reference counting kind of memory management for the Native code. For example C++ code. C++ code is not a managed code. To dereference the unused object we have to explicitly call Delete. There is no Garbage collector for C++ code. Unfortunately, I haven’t work on C++ language.

Managed Code: Managed code is executed by .Net Framework Common Language Runtime (CLR). It refers the contract of co-operation between natively executing code and the run-time. The memory allocation and de-allocation to an object is done by .Net Framework. User doesn’t have control on it. Dereferencing the unused memory/object has been taken care by Garbage Collector (GC).  Example: we use Finalize() and Dispose() method in our Managed Code implementation.  Garbage Collection runs Finalize() method before an object that is eligible for collection is reclaimed. Dispose() cleans unmanaged resources, like network connections, files etc.

Cheers!

Difference between Singly Linked List and Doubly Linked List

Friends!
We all know how to deal with Singly and Doubly linked list.
Now here I tried to put some differences which will help you to take decisions on the choice of using linked list type in your implementation.
Your inputs are welcome to make this increase the number of differences.


S.No. Singly Linked List Doubly Linked List
1 Singly linked list allows you to go one way direction Doubly linked list has two way directions next and previous
2 Singly linked list uses less memory per node (one pointer) Doubly linked list uses More memory per node than Singly Linked list (two pointers)
3 There is a little-known trick that lets you delete from a singly-linked list in O(1), but the list must be circular for it to work (move the content of next into the current, and delete next). Doubly-linked lists can be used in places where singly-linked lists would not work (a doubly-ended queue), but they require slightly more "housekeeping", and are slightly less efficient on insertions as the result
4 Complexity of Insertion and Deletion at known position is O (n). Complexity of Insertion and Deletion at known position is O (1).
5 If we need to save memory in need to update node values frequently and searching is not required, we can use Singly Linked list. If we need faster performance in searching and memory is not a limitation we use Doubly Linked List
6
For B-Tree, Heap we need doubly linked list. .Net Framework only provides the LinkedList<T> class which is double-linked.
7 If we know in advance that element to be searched is found near the end of the list(for example name 'Yogesh' in a telephone directory), even then singly linked list is traversed sequentially from beginning. In doubly linked list If we know in advance that element to be searched is found near the end of the list(for example name 'Yogesh' in a telephone directory), then the list can traversed from the end thereby saving time
8 In single list Each node contains at least two parts:
a) info
b) link
In doubly linked list Each node contains at least three parts:
a) info
b) link to next node
c) link to previous node

Cheers!

Friday, June 1, 2012

Primary key vs Unique key

A column or a set of columns, which can be used to identify or access a row or a set of rows in a database is called a key. A unique key is a key that can uniquely identify a row in a table in the context of relational databases. A unique key is made up of a single column or a set of columns. A primary key is also a combination of columns in a table that uniquely identify a row. But it is considered to be a special case of the unique key.

What is Unique Key?

As mentioned earlier, unique key is a single column or set of columns that can uniquely identify a row in a table. So, a unique key is constrained such that no two values of it are equal. One important property is that the unique keys do not enforce the NOT NULL constraint. Since NULL represents the lack of a value, if two rows have NULL in a column then it does not mean the values are equal. Column defined as a unique key allows only a single NULL value in that column. Then that can be used to identify that particular row uniquely. For example, in a table that contains student information, student ID can be defined as a unique key. Since no two students can have the same ID it uniquely identifies a single student. So the student ID column satisfies all the properties of a unique key. Depending on the design of a database, a table may have more than one unique key.

What is Primary Key?

Primary key is also a column or a combination of columns that uniquely defines a row in a table of a relational database. A table can have at most one primary key. Primary key enforces the implicit NOT NULL constraint. So, a column that is defined as the primary key cannot have NULL values in it. Primary key can be a normal attribute in the table that is guaranteed to be unique such as social security number or it could be a unique value generated by the database management system such as a Globally Unique Identifier (GUID) in Microsoft SQL Server. Primary keys are defined through the PRIMARY KEY constraint in ANSI SQL Standard. Primary key can also be defined when creating the table. SQL allows primary key to be made up of one or more columns and each column that is included in the primary key is implicitly defined to be NOT NULL. But some database management systems require making the primary key columns explicitly NOT NULL.

Difference Between Primary key and Unique key

Even though both the primary key and unique key are one or more columns that can uniquely identify a row in a table, they have some important differences. Most importantly, a table can have only a single primary key while it can have more than one unique key. Primary key can be considered as a special case of the unique key. Another difference is that primary keys have an implicit NOT NULL constraint while the unique key does not have that constraint. Therefore, unique key columns may or may not contain NULL values but primary key columns cannot contain NULL values.

Saturday, May 12, 2012

Difference between Dictionary and Hashtable

Dictionary
System.Collections.Generic.Dictionary<object,object>

Dictionary<TKey,TValue> is a generic type, allowing:
 
  • static typing (and compile-time verification)
  • use without boxing
If you are .NET 2.0 or above, you should prefer Dictionary<TKey,TValue> (and the other generic collections)

Hashtable
System.Collections.Hashtable

Hashtable is of collection type.
A subtle but important difference is that Hashtable supports multiple reader threads with a single writer thread, while Dictionary offers no thread safety.
If you need thread safety with a generic dictionary, you must implement your own synchronization or (in .NET 4.0) use ConcurrentDictionary<TKey, TValue>.

Best of Luck.

Find the largest contingent array in an array of integers.

A common interview question on Algorithms is to find the set of elements from an Array which has maximum sum.
In other words it is “Find the largest contingent array in an array of integers.”.

You can achieve it in only 3 lines of logical code/algorithm.
I am here pasting the C# solution code for the same problem.


"result" array will contain the Contingent Array and "sum" will contain Max sum from the array.

Hope this will help you a lot.
Best of luck.

Wednesday, April 25, 2012

Setting Up a Team Foundation Server 2010 Project

Reference : http://msmvps.com/blogs/bmains/archive/2010/05/01/setting-up-a-team-foundation-server-2010-project.aspx

I recently installed TFS 2010 and began to setup my projects, so I decided to create this blog post. I’m not going to cover the installation aspect of TFS; rather, I’m going to assume that you successfully installed the base software; this blog doesn’t discuss the use of the proxy or the build service either, just the TFS product and Sharepoint Services 3.0. If you have a SharePoint server, this is supported; however, there are a few more setup procedures available online. To begin, let’s open up Visual Studio 2010, open the project, and open up the Team Explorer tool window on the right. Click the far right icon of the toolbar, Connect to Team Project.


If you have made a connection previously, that entry appears in the “Team Project Collections” list; if you don’t have your target TFS specified, click the Servers button.


On the Add/Remove Server screen, click add, and specify the server to add. Either type in the server name directly, or enter in the full URL. If you type in the server name, specify the path and port in the respective textboxes.



Clicking OK will add the entry to the list. Click close on the Add/Remove TFS screen. In the previous screen (Connect to Team Project), select the newly added server and click Connect. You are connected to the server.

A TFS admin may have to setup a collection for your project; by default, the DefaultCollection is the only collection projects can be added to; having a separate collection means that project can be backed up and restored independently of other projects. These collections setup on the server are what you see in the team explorer. Right click one of the collections, and select New Team Project:


In the opening screen, enter the name and description of the project.



Click next when finished. The next screen asks for the template you would like to use for the project.





Click next to configure the Sharepoint portal site. Team Foundation Server is integrated with SharePoint and installs SharePoint Services 3.0 if you do not have the full SharePoint server installation. By default, if follows a <server>/sites/<collection name>/<project> folder structure. Click configure to change some of the SharePoint settings.

Note: if you don’t have permissions, you may not be able to create the SharePoint site. The SharePoint site can be created manually and linked to the project after installation. If you don’t have permissions, select “Do not configure a SharePoint site at this time”.



Next, specify the location for the project, or branch it from another project.


Finally, view the final statistics and ensure that the project is setup correctly.



This communicates with the server and setups the following project structure within the Team Explorer:




Now our team system project is setup. The following items in this list are:

Work Items – A place to add work items, assign them to members of the team, and so on. Use team queries to get a predefined query of work items, or create your own queries in the “My Queries” option.

Documents – A document library location for you to store documents related to the project.

Reports – Any reports for the project setup in Reporting Services by the installation.

Builds – Any builds defined by the build service for the project.

Source Control – Visit this feature to add your projects to the source control database for the first time.

Reference : http://msmvps.com/blogs/bmains/archive/2010/05/01/setting-up-a-team-foundation-server-2010-project.aspx

Thursday, April 12, 2012

Why don't file uploads work during async postbacks?

Full Reference : http://weblogs.asp.net/leftslipper/archive/2007/03/30/why-don-t-file-uploads-work-during-async-postbacks.aspx

As many people have noticed in their AJAX-enabled pages, file uploads do not work when doing an async postback. To my knowledge there's no way to support this scenario due to the browser's security restrictions. To understand why the upload doesn't work it's important to understand how async postbacks are performed and how that's different from how the browser performs a regular postback.

When the browser performs a regular postback it has the benefit of being actual code with no security restrictions running on the client computer. When you submit a form it creates a web request with all the form fields. When it encounters an <input type="file"> it examines the file the user chose, reads it from disk, and adds it to the web request.

When the AJAX JavaScript code is running in the browser it can do the first part about creating a request with all the form fields. However, when it gets to <input type="file"> fields it doesn't have the necessary security permissions to read those files from disk. Imagine what would happen it it could read those files: You could create a page that when visited will upload the user's c:\passwords.txt to a remote server! And we all know that every user has a file called passwords.txt on their C: drive. I bet just now you renamed it so my evil code couldn't run :)

So what's the workaround? Well, quite simply, the workaround is to do anything that doesn't involve a file upload during an async postback. Here are some solutions:

  1. Have a dedicated "Upload" button that does a regular postback instead of an async postback. You can achieve this using several techniques: Have the button be outside all UpdatePanels; have the button be the target of an UpdatePanel's PostBackTrigger; or call ScriptManager.RegisterPostBackControl() on it.
  2. Have a dedicated file upload page that doesn't have any UpdatePanels. Many web sites already do this anyway.

And now you might wonder, "why don't ASP.NET AJAX and the UpdatePanel handle this better?" We did give this a fair bit of thought and we decided that doing nothing was the best solution. One option we had was to throw some error from JavaScript if we detected any filled out <input type="file"> tags. But what if you wanted to do an async postback that had nothing to do with the file upload? Or perhaps only detect file uploads in certain regions of the document? That would involve even more expensive DOM tree walks that are already causing some performance degradation with UpdatePanels.

In conclusion, if you want a secure browser, you're not going to get file upload functionality from UpdatePanels. If you don't want a secure browser, please get your head checked. If you want to do file uploads, just use one of the two solutions I provided.

Tuesday, April 3, 2012

Check/Uncheck checkboxes in GridView using JavaScript

Reference :- http://wiki.asp.net/page.aspx/281/check-uncheck-checkboxes-in-gridview-using-javascript/

The question regarding how to check/uncheck CheckBoxes within a GridView control using JavaScript has been asked many times. Here is a quick reference you can follow.

First we have the .aspx markup.

<script type="text/javascript">
function SelectAll(id) {
var frm = document.forms[0];
for (i=0;i<frm.elements.length;i++) {
if (frm.elements[i].type == "checkbox") {
frm.elements[i].checked = document.getElementById(id).checked;
}
}
}
</script>
<!-- assuming that SqlDataSource1 is the datasource for my GridView -->
<asp:GridView ID="GridView1" runat="server" DataSourceID="SqlDataSource1" Width="400px">
<Columns>
<asp:TemplateField>
<AlternatingItemTemplate>
<asp:CheckBox ID="CheckBox1" runat="server" />
</AlternatingItemTemplate>
<ItemTemplate>
<asp:CheckBox ID="CheckBox1" runat="server" />
</ItemTemplate>
<HeaderTemplate>
<asp:CheckBox ID="cbSelectAll" runat="server" Text="Select All" />
</HeaderTemplate>
<HeaderStyle HorizontalAlign="Left" />
<ItemStyle HorizontalAlign="Left" />
</asp:TemplateField>
</Columns>
</asp:GridView>

Next we have the code-behind in both VB and C#

VB

Protected Sub GridView1_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles GridView1.RowDataBound
If (e.Row.RowType = DataControlRowType.Header) Then
'adding an attribute for onclick event on the check box in the header
'and passing the ClientID of the Select All checkbox
DirectCast(e.Row.FindControl("cbSelectAll"), CheckBox).Attributes.Add("onclick", "javascript:SelectAll('" & _
DirectCast(e.Row.FindControl("cbSelectAll"), CheckBox).ClientID & "')")
End If
End Sub

C#

protected void GridView1_RowDataBound(object sender, System.Web.UI.WebControls.GridViewRowEventArgs e) {
if (e.Row.RowType == DataControlRowType.Header) {
//adding an attribute for onclick event on the check box in the header
//and passing the ClientID of the Select All checkbox
((CheckBox)e.Row.FindControl("cbSelectAll")).Attributes.Add("onclick", "javascript:SelectAll('" + ((CheckBox)e.Row.FindControl("cbSelectAll")).ClientID + "')");
}
}

The example above is fantastic, but there are a couple things that could be improved.

  1. The JavaScript Pseudo Protocol (Javascript:your method here) should be avoided, it's a fragment from the old Netscape days. Today there are better alternatives
  2. In this case we probably don't need the server-side portion altogether.

An excerpt about the JavaScript Pseudo Protocol:

"The javascript: pseudo-protocol should not be used in event handlers like onclick. It should only be used in attributes that contain a URL, for example in the href attribute of <a> elements and the action attribute of <form> elements. You can also use it to make bookmarlets." - Common JavaScript Mistakes

Another solution the .aspx markup:

<script type="text/javascript">
// Let's use a lowercase function name to keep with JavaScript conventions
function selectAll(invoker) {
// Since ASP.NET checkboxes are really HTML input elements
// let's get all the inputs
var inputElements = document.getElementsByTagName('input');
for (var i = 0 ; i < inputElements.length ; i++) {
var myElement = inputElements[i];
// Filter through the input types looking for checkboxes
if (myElement.type === "checkbox") {
// Use the invoker (our calling element) as the reference
// for our checkbox status

myElement.checked = invoker.checked;
}
}
}
</script>
<!-- assuming that SqlDataSource1 is the datasource for my GridView -->
<asp:GridView ID="GridView1" runat="server" DataSourceID="SqlDataSource1">
<Columns>
<asp:TemplateField>
<AlternatingItemTemplate>
<asp:CheckBox ID="CheckBox1" runat="server" />
</AlternatingItemTemplate>
<ItemTemplate>
<asp:CheckBox ID="CheckBox1" runat="server" />
</ItemTemplate>
<HeaderTemplate>
<asp:CheckBox ID="cbSelectAll" runat="server" Text="Select All" OnClick="selectAll(this)" />
</HeaderTemplate>
<HeaderStyle HorizontalAlign="Left" />
<ItemStyle HorizontalAlign="Left" />
</asp:TemplateField>
</Columns>
</asp:GridView>