Long back one of my cousins Rajesh gives me an introduction to Operator overloading in C++, but at that time I was VB 6.0 guy and I didn’t give much importance to it. But yesterday I got a chance to work on some sample applications where I tried operator overloading on C#.
I overloaded the + operator for adding two persons objects, and here is the code.
//Person class.
public class Person
{
//Name of the Person
public string Name
{
get;
set;
}
//Operator overloading.
public static Person operator +(Person first, Person second)
{
//Returning person, by adding the Names.
return new Person()
{
Name = first.Name + " " + second.Name
};
}
}
And here is the void Main()
static void Main(string[] args)
{
Person firstPerson = new Person()
{
Name = "Person 1"
};
Person secondPerson = new Person()
{
Name = "Person 2"
};
//Adding Person objects
Person resultPerson = firstPerson + secondPerson;
//It will return Person 1 Person 2
Console.WriteLine(resultPerson.Name);
}
You can find Operator Overloading Tutorial in MSDN
In my first WinForms application, I have to create various wizard screens, I couldn’t find any ready made Controls for it from Microsoft. Then one of my colleague suggested a way to tweak it, like Add a Tab Control, Set the Alignment property to bottom and add a panel on top of the Tab Control, which contains Next / Previous / Cancel buttons. It was working fine. Few days back again I got the same situation for one of my personal project, and I thought about writing a control for the same. After doing some research I found a simple code snippet, which helps to hide the Tab Pages title in Runtime.
Here is the code, in this I am extending the Tab control and overriding the WndProc event.
protected override void WndProc(ref Message m)
{
// Hide tabs by trapping the TCM_ADJUSTRECT message
if (m.Msg == 0x1328 && !DesignMode)
{
m.Result = (IntPtr)1;
}
else
{
base.WndProc(ref m);
}
}
You can find more details about TCM_ADJUSTRECT Message on MSDN.
HTTP modules differ from HTTP handlers. An HTTP handler returns a response to a request that is identified by a file name extension or family of file name extensions. In contrast, an HTTP module is invoked for all requests and responses. It subscribes to event notifications in the request pipeline and lets you run code in registered event handlers. The tasks that a module is used for are general to an application and to all requests for resources in the application.
You can get more information on MSDN – HTTP Handlers and HTTP Modules Overview
Today I got a problem from my colleague, that he is getting FileNot Found exception in Application Error event in Global.asax, which is used to log application errors. But the application was working fine and good. We thought it may be because of missing images that was referring in Stylesheets. But all the image references are valid and we couldn’t find any issue. We couldn’t find anything suspicious in stack trace.
Stack Trace from the exception
at System.Web.StaticFileHandler.GetFileInfo(String virtualPathWithPathInfo, String physicalPath, HttpResponse response)
at System.Web.StaticFileHandler.ProcessRequestInternal(HttpContext context)
at System.Web.DefaultHttpHandler.BeginProcessRequest(HttpContext context, AsyncCallback callback, Object state)
at System.Web.HttpApplication.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously)
After doing some search we got an option where we can find the file causing the exception. We created a string variable and put a break point over there and debugged the code. It will display the filename causing the exception. In our case it was a HTML file which was used in a Javascript to set an IFRAME source, unfortunately the developer who copied the script missed the HTML and it was causing the exception.
Here is the code.
void Application_Error(object sender, EventArgs e)
{
Exception err = Server.GetLastError();
//Insert a break point and run in debug mode.
string fileName = Context.Request.FilePath;
Application["UnhandledException"] = err;
}
One of my colleague asked how to get all the text boxes with no text entered in Windows form without using a For Loop. I thought of writing it with LINQ. And here is my implementation.
var controls = from control in this.Controls
select control;
But this will generate a compile time error – Could not find an implementation of the query pattern for source type ‘System.Windows.Forms.Control.ControlCollection’. ‘Select’ not found. Consider explicitly specifying the type of the range variable ‘control’. But the error was self explanatory, I need to specify the type of the control. And here is the modified version.
var controls = from Control control in this.Controls
select control;
And if you want to select specific type of controls you need to apply a where condition.
var textboxes = from Control textbox in this.Controls
where textbox is TextBox
select textbox;
There is some other inbuilt operators is also available to select specific controls, like OfType()
var textboxes = from textbox in this.Controls.OfType<TextBox>()
select textbox;
In this method we don’t need to specify the type of the control in the from statement. And one of interesting LINQ extension method is the Cast<> method, which helps to enable the standard query operators to be invoked on non-generic collections by supplying the necessary type information. You can get more information from here.
Today one of my colleague talked about a simple basic issue with Dropdownlist, the FindByText() method works as case sensitive. Because of this issue, we are getting some exceptions. So I starting looking for alternatives and one way I found it looping the items and compare it. Like the following.
this.ddlItems.SelectedIndex = -1;
foreach (ListItem item in this.ddlItems.Items)
{
if (item.Text.Equals("Item", StringComparison.CurrentCultureIgnoreCase))
{
item.Selected = true;
break;
}
}
It is a nice option, I rewrote it as an extension method and works fine. Later I thought of wrting more generic FindByTextMethod() and here the extension method.
/// <summary>
/// Searches the Collection of ListItem with a ListItem.Text property contains the specified text
/// </summary>
/// <param name="items"></param>
/// <param name="text">The text to search for.</param>
/// <param name="stringComparison">One of the System.StringComparison values.</param>
/// <returns>ListItem if the collection contains the text, null otherwise.</returns>
public static ListItem FindByText(this ListItemCollection items,
string text,
StringComparison comparisonType)
{
ListItem result = items.OfType<ListItem>().
FirstOrDefault(_string => _string.Text.Equals(text, comparisonType));
return result;
}
And you can use it like this
this.ddlItems.Items.FindByText("Item", StringComparison.CurrentCultureIgnoreCase).Selected = true;
Happy Coding