Sep 18 2014

Tackling the Arrow head Anti-Pattern

Category: .Net | C# | Design Principles ashish sheth @ 00:13

Frequently you will see following type of code in your code base.

if(result != 1)
{
    if(someOtherResult == 101)
    {
        if(anotherValue == 500)
        {
            // do something
        }
    }
    else
    {
        // do some other thing
    }
}

return;

Here the code forms a shape of an arrow-head, as below:

if
    if
        if
            if
                do something
            end
        end
    end
end

If you see, the main logic is deep down into the nested condition, it increases the cyclomatic complexity of the code.

A better version of the same code could be as below:

if(result == 1)
{
    return;
}

if(someOtherResult == 101 && anotherValue == 500)
{
    // do something
    return;
}

// do some other thing

return;

The above code does a number of things to flatten the code and make it better:

  1. Validations are performed first and it returns at the first opportunity.
  2. Multiple nested conditions are combine into one (with “&&”(logical And) operator. If there are multiple expressions forming one such condition, they can be moved to a separate method returning boolean. That method can then be use in the if condition as below:
if(IsValidResult(someOtherResult, anotherResult)
{
    // do something
    return;
}

bool IsValidResult(int someOtherResult, int anotherResult)
{
    if(someOtherResult == 101 && anotherValue == 500)
    {
        return true;
    }
    return false;
}

Tags: , ,

Sep 16 2014

Podcast that I listen

Category: .Net | Learning | miscellaneous ashish sheth @ 00:45

In the big sea of web, you will find many people telling you the podcast that every developers should listen. Here is my list, and yes, I too think these are the podcast every developer(.Net developer) should listen.

  1. .Net Rocks: This is more than a decade old talk show focusing on Microsoft .Net Technologies. Earlier it used to be a weekly show, but now it has three show a week. Apart from covering anything and everything related to .Net, it also covers mobile app development on Android and iOS.
  2. Hanselminutes: This is the show by Scott Hanselman, which focuses on technology including Microsoft .Net Technology.
  3. HerdingCode: This is a show where discussion goes into nitty-gritty of development tasks. As with the above two, not just the .Net technology, but other aspects of Software development practises are also discussed.
  4. Software Engineering Radio: This is a monthly podcast targeted towards not just .Net developers, but to all software developers in general. So it covers topics which include Software Engineering practises, architecture, design patterns, etc. It also has a rather academic feel and many a times the guests include leading researchers in the field of Computer Science.
  5. MS Dev show: This is relatively a new podcast for Microsoft developers focussing fully to Microsoft technology including topics such as Azure/Cloud, Windows, Windows Phone, .Net etc.
  6. IEEE Software’s On Computing: In this podcast Grady Booch reads from his column “On Computing” in the IEEE Software magazine. In this, he talks software’s impact on humanity.
  7. IEEE Software’s Tools of the Trade: This is again the podcast of an on going column in IEEE Software with the same name. In every episode, it covers software tools to be used within a certain aspect of Software Development, such as documentation, debugging, testing, etc.
  8. HBR IdeaCast: This is a weekly podcast from HBR.org and it is mostly about analysis and advice from leading minds in management.

Let me know what you listen to.

Tags: ,

Jun 17 2011

.Net Guidance Map

Category: .Net | .Net Framework | asp.net ashish sheth @ 18:05

 

I thought these would be very helpful to those who are learning .Net.  J. D. Meier has put up Development Guidance Map for various .Net technologies. This material includes links to technical articles, videos, how-tos, blogs, tutorials, trainings, code samples on various .Net technologies and about everything you might need to know about .net.

Happy Learning.

 

Tags: ,

Sep 16 2010

Use Properties to Encapsulate the Hidden Fields or ViewState in Asp.Net

Category: .Net | asp.net | C# | VS2008 ashish sheth @ 05:16

In asp.net you might be using lot of hidden variables and ViewState to maintain state between page postbacks. This can make your code look cluttered. You can use properties to encapsulate the hidden fields or ViewState.

If you are writing lot of code like this:

if(myHidden.Value == string.Empty)
{
	myHidden.Value = "someValue"; 	
}

someVariable = myHidden.Value

You can use properties to encapsulate the access to myHidden field. For example:

public string MyHiddenFieldValue
{
	get
	{
		if(myHidden.Value == string.Empty)
		{
			myHidden.Value = "someValue"; 	
		}
		return myHidden.Value
	}
	set
	{
		myHidden.Value = value;
	}
}

Then you can access the myHidden field just by the property

someVariable = MyHiddenFieldValue;

Similarly if you are storing some custom values in the ViewState of the page the you can create property for the ViewState also.

public string MyCustomViewState
{
	get
	{
		if(ViewState["MyViewState"] == null)
		{
			ViewState["MyViewState"] = "someValue"; 	
		}
		return ViewState["MyViewState"].ToString();
	}
	set
	{
		ViewState["MyViewState"] = value;
	}
}

Tags: , , ,

Aug 24 2010

VisualStudio ReflectedSchemas folder in ApplicationData

Category: .Net | asp.net | VS2008 ashish sheth @ 23:23

Just now I found out that C:\Documents and Settings\[Username]\Application Data\Microsoft\VisualStudio\9.0\ReflectedSchemas

folder takes lots of space. VS 2008 stores schema files which are dynamically generated when you compile a webcontrol.

To release the space on your drive you can delete the files safely and VisualStudio will re-generate these files whenever needed.

 

For more information see below:

http://blogs.msdn.com/b/mikhailarkhipov/archive/2004/05/14/131949.aspx

http://stackoverflow.com/questions/878345/reflectedschemas-folder-in-the-users-appdata-folder-visual-studio

http://forums.asp.net/t/1264942.aspx

http://www.ureader.com/msg/15364998.aspx

Tags: , ,

Feb 10 2010

Find-n-Replace using Regular Expression in Visual Studio 2008

Category: .Net | VS2008 ashish sheth @ 04:22

Here is a tip how you can convert a multiline text to single line(ie., how to remove newline characters) using regular expression.

Select "Use Regular Expression" in the find-n-replace dialog box. Enter "\n" in the "Find What:" field. Don't provide anything in the "Replace With:" and click the Replace or Replace All button. And voila.. All your contents are in a single lines now.

Here are more resources I found on the net on Find-n-Replace using regular expression:

http://www.aaronlerch.com/blog/2007/03/28/visual-studio-find-and-replace-regular-expressions/
http://msmvps.com/blogs/paulomorgado/pages/visual-studio-find-and-replace-regular-expression-patterns.aspx
http://www.codinghorror.com/blog/archives/000633.html
http://weblogs.asp.net/joelvarty/archive/2008/03/25/find-replace-in-visual-studio-with-regular-expressions-and-variables.aspx
http://developers.de/blogs/scott_munro/archive/2006/07/14/_2700_Find-and-Replace_2700_-with-regular-expressions-in-Visual-Studio.aspx
http://blogs.msdn.com/vseditor/archive/2004/06/18/159515.aspx
http://msdn.microsoft.com/en-us/library/2k3te2cs%28VS.80%29.aspx

Tags: ,

Dec 7 2009

Invoke Google from withing VS 2008

Category: .Net | .Net Framework | C# | CodeProject | VS2008 ashish sheth @ 11:25

As programmers we need to search for many tasks that we want to accomplish. And the F1 key in visual studio does not help because it always launches the local MSDN search, even if MSDN is not installed on the local computer.

Brian Schmitt has provided the code to write a macro to search variouse sites. Here I am describing steps to how you can configure your Visual studio 2008 to invoke google search from within the IDE based on his post.

  • In the VS 2008 IDE, click Alt + F8 to launch the Macro explorer.  It should show you a tree like below at the right hand side of the IDE.

 

 

  • Right Click on theMyMacros project and create a new module named Search. (Alternately, you can goto Tools menu-> Macros -> New Macro command). This will launch the macro editor.
  • Copy and paste the below code in the macro editor. (Code taken from Brian Schmitt's article on Better Visual Studio F1)

 

Imports EnvDTE
Imports System.Web

Public Module Search

#Region "Search Internet Sites"
  Public Const GOOGLE_FORMAT As String = "www.google.com/search?q={0}"
  Public Const STACKOVERFLOW_FORMAT As String = "http://www.stackoverflow.com/search?q={0}"
  Public Const SEARCHDOTNET_FORMAT As String = "http://searchdotnet.com/results.aspx?cx=002213837942349435108:jki1okx03jq&q={0}&sa=Search&cof=FORID:9#1144"
  Public Const MSDN_FORMAT As String = "http://social.msdn.microsoft.com/Search/en-US/?query={0}&ac=8"
   
  Public Sub SearchStackOverflowForSelectedText()
      SearchWebPage(STACKOVERFLOW_FORMAT)
  End Sub
  Public Sub SearchGoogleForSelectedText()
      SearchWebPage(GOOGLE_FORMAT)
  End Sub
  Public Sub SearchSearchDotNetForSelectedText()
      SearchWebPage(SEARCHDOTNET_FORMAT)
  End Sub
      Public Sub SearchMSDNForSelectedText()
      SearchWebPage(MSDN_FORMAT)
  End Sub
  Private Sub SearchWebPage(ByVal SearchURLFormat As String)
      Dim sel As EnvDTE.TextSelection = DTE.ActiveWindow.Selection
      Dim srchTxt As String = sel.Text.Trim
      If srchTxt.Length > 0 Then
          DTE.ItemOperations.Navigate(String.Format(SearchURLFormat, HttpUtility.UrlEncode(srchTxt)))
      End If
  End Sub
#End Region

End Module

 

  • Now the macro is ready (there are four macros created one each for google, stackoverflow, searchdotnet and MSDN). Now we will assign short cut for all the four macros.
  • Go to Tools -> Options -> keyboard. In the “Show command containing” type macro. Or simply scroll through the list box to find the macro we just created.

 

 

  • In the “Press shortcut key” type in the short cut you want (for e.g. Alt + F1, Alt + Shift + F1). Note that if you press just F1, it will replace the existing binding for the F1 key to the MSDN help.
  • In the similar way type in the short cut for other macros.

Tags: ,

Aug 27 2009

Using CultureInfo for Globalization/Localization of an Asp.Net Applictation

Category: .Net | asp.net | CodeProject ashish sheth @ 11:22

Globalization is the process of making the application able to handle different culture and regions, while localization is the process of customization of the application for a specific culture and region.

You use resource files (.resx) to localize the resources in your application. You use classes in System.Globalization namespace to make your application culture aware.

The main class in Systme.Globalization namespace is the CultureInfo class. It contains many methods and properties to identify different cultures and configure your application to use a specific culture.

You use System.Threading.Thread.CurrentCulture and System.Threading.Thread.CurrentUICulture to configure your application to use a specific culture setting.

So how do you set which culture to use with your application?

The System.Threading.Thread.CurrentCulture property is used to set a specific culture for the application. This property mainly defines how the application will format the datetime string and currency. So if you are manipulating datetime and currency in your application and want you application to correctly format them based on the use's culture then you need to set the System.Threading.Thread.CurrentCulture property.

The System.Threading.Thread.CurrentUICulture property is used to set a neutral culture for the application. This property mainly defines what resource files to use for your application. Say for example, for English user you want display content in your site in English and for French users you want to display your sites in French. So you create different resource files for different languages and set this property and your application will automatically select correct resource file to used based on the culture setting.

There are three types of Culture your application can use. One is InvariantCulture, second is NeutralCulture and the last one is SpecificCulture.

InvariantCulture actually means culture agnostic. You use InvariantCulture when you want to compare strings, display or compare dates in culture agnostic way. By default it uses the en-US culture.

NeutralCulture is actually a language specific culture without regard to the country specific datetime and currency formats. You use this culture to determine which language specific resource file your application will use. You can specify NeutralCulture with two lower case characters identifying the language. For example, 'en' for English, 'fr' for French, 'es' for Spanish.

SpecificCulture is the language and country specific culture which determines the language to use with your application and also the datetime and currency format to use with your application. You specify the specific culture with two lower case characters identifying the language and two upper case characters identifying the country separated by hyphen. For example, 'en-US' for English (US), 'en-GB' for English (UK), 'fr-FR' for French(France) etc.

So while setting the culture to use with you application, you set the CurrentCulture property to a SpecificCulture and the CurrentUICulture property to a NeutralCulture.

Let's see an example to set the culture for an application.

CultureInfo ci = new CultureInfo("en-US);
CultureInfo ciUI = new CultureInfo("en");
System.Threading.Thread.CurrentCulture = ci;
System.Threading.Thread.CurrentUICulture = ciUI;

In the above two lines, you are telling your application to use English as the culture. As said before, CurrentCulture property will determines which format to use for displaying datetimes and currency while the CurrentUICulture will determine which resource files to use while displaying strings in your application. You can see that the CurrentCulture property is set to "en-US" which a specific culture for English for United Status, while the CurrentUICulture property is set to "en" which is a neutral culture.

Tags: , ,

Aug 8 2009

Changing the default name of indexer

Category: .Net | .Net Framework | C# ashish sheth @ 12:05

.NET framework contains many hidden gems, which we rarely need and use, in the Base class libraries.

You probably know that when you write an indexer in C#, it will get compiled into two methods called get_Item and set_Item.

So when you declare an indexer like this:

public string this[int number]

it actually compiles into this:

public string get_Item(int number)

Now, did you know that you can have any other name for your indexer if you don't want the name of your indexer to be get_Item? Yes, you can use System.Runtime.CompilerServices.IndexerNameAttribute to change the name into which your indexer will be compiled. Here is the example.

[System.Runtime.CompnailerServices.IndexerName("BinaryFormatOf")]
    public string this[int number]

The above lines will generate a method like below:

public string get_BinaryFormatOf(int number)

I am not sure in what scenario this can be useful but it will certainely usefull if you have indexers which does fit into the getItem-setItem pattern.

Tags: , , ,

Jul 25 2009

What is vshost.exe and vshost.exe.config?

Category: .Net | VS2008 ashish sheth @ 12:20

When we compile a windows application(forms or sevice) in VS 2005 or VS 2008 then we see that there is a *.vshost.exe and *.vshost.exe.config file generated in the bin folder. And we wonder what are these files and why are they generated. Here (http://blogs.msdn.com/dtemp/archive/2004/08/17/215764.aspx) is the anser. In short they are there to provide support for improved F5 performance, partial trust debugging, and design time expression evaluation. These files are there just for developent environment. It sould not be deployed to production environment.

Tags: ,