ASP.NET MVC Extensions Methods

These are my extensions.

  1. Not display dropdownlist if the Select list is null
    public static MvcHtmlString DropDownListNull(this HtmlHelper html, string Name, SelectList select, object htmlAttributes)
    if (select == null)
    return MvcHtmlString.Empty;
     return html.DropDownList(Name, select, htmlAttributes);
  2. Transform Enum to SelectList
    #region enum to list
            private static List<KeyValuePair<long, string>> FromEnum(this Type e)
                List<KeyValuePair<long, string>> kvp = new List<KeyValuePair<long, string>>();
                foreach (var s in Enum.GetValues(e))
                    kvp.Add(new KeyValuePair<long, string>((int)s, s.ToString()));
                return kvp;
            public static SelectList ToSelectList(this Type enumObj)
                return new SelectList(enumObj.FromEnum(), "Key", "Value");
  3. Transform Generic list into a SelectList
                  #region Generic List to SelectItem
            public static SelectList SelectFromList<TItem>(this List<TItem> values,
                Expression<Func<TItem, string>> key, Expression<Func<TItem, string>> value)
                var Key = key.Compile();
                var Value = value.Compile();
                List<KeyValuePair<string, string>> kvp = new List<KeyValuePair<string, string>>(values.Count);
                values.ForEach(item =>
                    kvp.Add(new KeyValuePair<string, string>(Key.Invoke(item), Value.Invoke(item))));
                return new SelectList(kvp, "Key", "Value");
  4. Display pager control
    #region paged list control
            /// <summary>
            /// Shows a pager control - Creates a list of links that jump to each page
            /// </summary>
            /// <param name="page">The ViewPage instance this method executes on.</param>
            /// <param name="pagedList">A PagedList instance containing the data for the paged control</param>
            /// <param name="controllerName">Name of the controller.</param>
            /// <param name="actionName">Name of the action on the controller.</param>
            public static void ShowPagerControl(this ViewPage page, BasePagedListImplementation pagedList, string formatUrl)
                HtmlTextWriter writer = new HtmlTextWriter(page.Response.Output);
                if (writer != null)
                    for (int pageNum = 1; pageNum <= pagedList.PageCount; pageNum++)
                        bool samepage=(pageNum == pagedList.PageNumber);
                        if (!samepage)
                            writer.AddAttribute(HtmlTextWriterAttribute.Href,string.Format(formatUrl, pageNum));
                            writer.AddAttribute(HtmlTextWriterAttribute.Alt, "Page " + pageNum);
                                            pageNum == pagedList.PageNumber ?
                                                                "pageLinkCurrent" :
                        if (!samepage)
                    writer.Write(" items in all)");

Other extensions available that are good :


If you know more, please tell me

My programmer tools in 2009

you can download the PDF from




SharpZipLib Zip files programatically
nunit test
svn source control
hudson continous integration
EntityFramework sql server database to .NET code
filehelpers parse csv and other files
log4net logging
lumisoft parsing email messages
moq mocking in unit test
automapper transferring data between dal and bll
pagedlist use for paging in ASP.NET MVC
log4postsharp logging every method with easy
postsharp see log4postsharp, version 1.5 still free
webdeployment project to deploy web projects;displaylang=en&displaylang=en
IIS SEO Toolkit verify my sites
nbehave testing with words
reflector analyze code, others and mine
fiddler analyze ajax requests
build utilities from apache svn commit if different
selenium testing web interfaces
HtmAgilityPack saving web pages




notepad++ no notepad
paint graphic editor graphic editor
7zip free archiver-un-archiver
sysinternals bunch of windows utilities
windows live writer blog
psr.exe new method to create help
logparser parse fast files
foxitreader pdf reader
yahoo instant messaging
skype instant messaging
dosbox old games redivivus
vlc movie player
dvddecrypter and dvdshrink backup my movies
magicdisk load iso files
freecommander norton commander
winmerge compare files / folders

Firefox addons

yahoo slow

As I was saying, you can download the PDF from

Saving Setting for Windows Forms

Saving and retrieving application settings

Every application that I have made needs at minimum two things, that we will put on the generic term “ settings “:

1. “remember” their state – information that are read at the beginning, write at the end of the program . We will name those “local settings” because there are different by each user that uses the application.

2. Connect with other applications (databases, web services, other programs ) and remember the “connection” settings – information that is read and does not change often ( number of writes is minimized). We will name this “global settings”.Most of the time the writing is realized by setup and/or a new application dedicated to application administration.

Usually the settings are saved in a file persisted on local hard disk. From the programmer perspective, there are four questions that arise:

1. when to save

2. where to save

3. how to save

4. how to make the information confidential.

When to save

The saving can be done in two separate moments: on installing the application and in running the application. Usually, the global settings(information that does not change often such as database connection) is persisted on application setup and read when the application starts. The local settings information (such as last action of the user) is read when the application starts and it is write at the application end.

Where to save

For a desktop application there are two places to save the data for a application : the folder where the applications is installed by the user (usually %programfiles% , can be obtained in .NET with Path.GetDirectoryName( Assembly.GetEntryAssembly().GetName().CodeBase)) and the local folder for application data for this user (%USERPROFILE%\AppData\Local – obtained in .NET with
). The first one is for global settings, the other one for local user settings.

How to save

We will enumerate here several methods, remaining for you the task to choose between the best. We will deliberately skip the method in which you use a file and you wrote information there in a proprietary format.
In the next examples we will save/retrieve two named properties : DatabaseConnection and LastAction
Save method 1 : from Settings within Visual Studio
You can create settings for your project very easy. Load your project in Visual Studio, click on toolbar Project=>Properties, select the tab “Settings” and create the settings. In the picture you will see two settings, one with user scope and one with application scope:
By default Visual Studio creates a class named “Settings” and puts code for retrieving/storing the settings that you create. More – the application settings does not have a “set” by default – it is normal since it is stored in application config file – an ordinary user cannot write this setting.
The code for retrieving/saving the settings is the following:
Properties.Settings.Default.LastAction = “difference”;
//you can reset the values by
For more details please refer to the following links :

· Application Settings Architecture ,

· Application Settings Overview ,

Video tutorial :

Save method 2 : from application configuration file

You can read/save directly from application configuration file. Add an application configuration file to the project and a reference to System.Configuration . In the app.config file add
<add key=”DatabaseConnection” value=”name=Stargate”/>
<add key=”LastAction” value=”add”/>
And the code is the following:
var app=ConfigurationManager.AppSettings;
foreach (var key in app.AllKeys)
Observation 1 : Please ensure you put in the app.config file file just global settings. Otherwise the application must have administrative rights to modify the app.config file.
Observation 2 : For applications , the modifying of Web.config will result in restarting the application – that is NOT a good behaviour.

Video Tutorial :

Save method 3 , create a new configuration :

This method is a combinations between method 2 and 3 : we have an intermediate class to save and we save in the config file . It is somewhat more to write about, but it is more safe – and can be modified and/or tested easily.
First we create the class :
public class MyConfig : ConfigurationSection
public string DatabaseConnection
return base[“DatabaseConnection”].ToString();
base[“DatabaseConnection”] = value;
public string LastAction
return base[“LastAction”].ToString();
base[“LastAction”] = value;
Next , we put in the application configuration file the settings :
<sectionGroup name=”MyApplicationSettings”>
<section name=”MyConfig” type=”AppSettingsConsole.MyConfig, AppSettingsConsole” restartOnExternalChanges=”false” allowDefinition=”Everywhere” />
<MyConfig DatabaseConnection=”name=Stargate” LastAction=”add”>
And third we wrote code to retrieve :
MyConfig m = (MyConfig)System.Configuration.ConfigurationManager.GetSection(“MyApplicationSettings/MyConfig”);

Video Tutorial :

Save method 4, XML file :
This is the method with the more liberty. We can define any class we want to preserve properties – we just need to serialize the class.
public class MySettings
static XmlSerializer xs;
static MySettings()
xs = new XmlSerializer(typeof(MySettings));
public string DatabaseConnection { get; set; }
public string LastAction { get; set; }
public void SaveToFile(string NameFile)
using (StreamWriter sw = new StreamWriter(NameFile))
xs.Serialize(sw, this);
public static MySettings RetrieveFromFile(string NameFile)
using (StreamReader sw = new StreamReader(NameFile))
return xs.Deserialize(sw) as MySettings;
And the code to save is easier :
string folderPath = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);
string FileName = Path.Combine(folderPath, “mysettings.txt”);
MySettings ms = new MySettings();
ms.DatabaseConnection = “name=Stargate”;
ms.LastAction = “add”;
MySettings msRetrieve = MySettings.RetrieveFromFile(FileName);
Console.WriteLine(ms.LastAction + ” — ” + ms.DatabaseConnection);
Video Tutorial :
Save method 5, Ini Files
Save method 6, Database
It’s obvious that you can have a table with 3 columns :Object, Name and Value. Access this column with EF, L2S , NHibernate or any other framework
Save method 7, Registry

Just the code
using (RegistryKey r = Registry.CurrentUser.CreateSubKey(@”Software\App”))
r.SetValue(“myvalue”, “1”, RegistryValueKind.String);
using (RegistryKey r = Registry.CurrentUser.CreateSubKey(@”Software\App”))
Video Tutorial :


In this chapter we have shown different ways to store application settings in various file formats. A final recommendation is to store application global data in config file (either web.config, either app.config) and local user in XML file ( in
folder). More, for each desktop application please provide a way to edit the config file – and make sure you request elevated privileges.

How To … Create a new site similar with regular internet site in Windows 7


Step 1 : Make a Web site with Visual Studio

Step 2 : In IIS Manager create the new site

Step 3: edit the hosts file (administrative rights)

Step 4: Create the Web application, modify his Project=>properties=>Web =>Use local IIS Web Server

Step 5: Edit bindings for new site to point to the folder of application

Step 6: Run Visual Studio

Andrei Ignat weekly software news(mostly .NET)

* indicates required

Please select all the ways you would like to hear from me:

You can unsubscribe at any time by clicking the link in the footer of our emails. For information about our privacy practices, please visit our website.

We use Mailchimp as our marketing platform. By clicking below to subscribe, you acknowledge that your information will be transferred to Mailchimp for processing. Learn more about Mailchimp's privacy practices here.