Custom configuration section

четверг, 31 июля 2008 г. · 0 коммент.

Have you ever saw such situation? You open web.config or app.config file trying to find some setting and get to huge list of AppSettings values? You may say that this is ok. I can't agree with you.

AppSettings section is good for small amount of settings. When number of settings begins to grow you should think about grouping settings into custom sections. You have already seen custom sections: ConnectionStrings, AppSettings, Complitation and etc.

It's easy to create custom configuration section. First of all i would like to say that i'm not going to pay attention to all details of section creation. I'm going to show you how you can create simple section and use it. More information can be found in MSDN.

Let's start!

We are going to create section which stores list of pages which require HTTPS protocol. Here is what I would like to have:
I will need three objects to read this information from configuration file:

  • Configuration section element. This element is container of settings. In my sample it corresponds to tag httpsSection
  • Configuration element collection. This is going to be a list of page urls. This collection uses patterns tag.
  • Configuration element. This element stores information about pattern. It's tag is add because it's a part of collection.
I think we should start from the simplies element of this list. This is pattern collection item. Here is a source code of this class:

using System.Configuration;

namespace Business.HttpsRedirect.Configuration
{
public class PatternElement : ConfigurationElement
{
[ConfigurationProperty("pattern", IsRequired = false)]
public string Pattern
{
get { return this["pattern"] as string; }
}
}
}
As you can see it's very simple. You should page attention to base class. It's ConfigurationElement. Also you should no forget about ConfigurationProperyAttribute.
This attribute contains other properties so you may get more information in MSDN.

Next we going to create configuration element collection:

using System.Configuration;

namespace Business.HttpsRedirect.Configuration
{
/// <summary>
/// List of configuration elements
/// </summary>
public class PatternElementCollection : ConfigurationElementCollection
{
/// <summary>
/// Creates the configuration element programmatically.
/// </summary>
/// <returns>The configuration element.</returns>
protected override ConfigurationElement CreateNewElement()
{
return new PatternElement();
}

/// <summary>
/// Gets the configuration element identifier.
/// </summary>
/// <param name="element">The configuration element.</param>
/// <returns>The configuration element identifier.</returns>
protected override object GetElementKey(ConfigurationElement element)
{
return ((PatternElement)element).Pattern;
}

/// <summary>
/// Matches the HTTPS pattern.
/// </summary>
/// <param name="url">The URL.</param>
public bool MatchesHttpsPattern(string url)
{
foreach (PatternElement pattern in this)
{
if (url.IndexOf(pattern.Pattern.ToLower().Trim()) >= 0)
return true;
}
return false;
}
}
}

You should pay attention to overridden methods. One method create instance of collection item (CreateNewElement) here we may put name of desired class. In our case we going to put PatternElement. The second method (GetElementKey) should return key for specified object. We are going to use pattern as a key. Last method (MatchesHttpsPattern) is simple check for url it maches some pattern. This method may be removed.

Last thing we need to do is to create configuration section. Here is a code for this section:



using System.Configuration;

namespace Business.HttpsRedirect.Configuration
{
/// <summary>
/// Provides information on https redirection.
/// </summary>
public class HttpsRedirectSection : ConfigurationSection
{
#region Properties

/// <summary>
/// Gets the patterns.
/// </summary>
/// <value>The patterns.</value>
[ConfigurationProperty("patterns")]
private PatternElementCollection Patterns
{
get { return this["patterns"] as PatternElementCollection; }
}

/// <summary>
/// Gets the configuration section.
/// </summary>
/// <returns>The configuration section.</returns>
private static HttpsRedirectSection GetConfig()
{
return ConfigurationManager.GetSection("httpsSection") as HttpsRedirectSection;
}

#endregion

#region Public Methods

/// <summary>
/// Matches the HTTPS pattern.
/// </summary>
/// <param name="url">The URL.</param>
public static bool MatchesHttpsPattern(string url)
{
return GetConfig().Patterns.MatchesHttpsPattern(url);
}

#endregion
}
}

All what is necessary for this class is Patterns property and attribute applied to this property. All other methods were created to simplify section usage.

Ok. What's next? We have code for configuration section but how can we let application know about this section? It should be registered in configuration file. Here is how it look like:



<configuration>
<configSections>
<section name="httpsSection" type="Business.HttpsRedirect.Configuration.HttpsRedirectSection, Business"/>
</configSections>

<httpsSection>
<patterns>
<add pattern="/UserArea/"/>
<add pattern="/AdminArea/"/>
<add pattern="/Newsletters/"/>
<add pattern="/Basket.aspx"/>
<add pattern="/Checkout.aspx"/>
<add pattern="/Track-Order.aspx"/>
<add pattern="/LogIn.aspx"/>
<add pattern="/Phone-Me.aspx"/>
<add pattern="/Request-For-Quote.aspx"/>
</patterns>
</httpsSection>

I have to register section in configurationSection of config file. Section name should match section tag name (httpsSection).

Conclusion: Here is description of steps which allow you to create simple and light-weight section to store related settings. Use custom section instead of making AppSettings to big

Dont' use RAR archives for files

· 0 коммент.

I see that some developers send their files using RAR archive. It's convenient to send files in archives. It's ok. But RAR archivator is paid software. File receiver may not be able to extract files. There is a simple solution for this problem. You should use ZIP achive for packed files. There is a lot of free tools which allow unpack files.

Conclusion: ZIP file should be used for files sent to client. You may use other formats if you are 100% sure that receiver will be able to unpack files.

What is the difference between Server.Transfer and Response.Redirect?

вторник, 29 июля 2008 г. · 0 коммент.

Response redirect causes client-side redirect. Visitor browser receives response from server. This response force browser to load page requested by server.

Server.Transfer terminates execution of current handler a executes other page (specified as param). From the visitor point of view this looks like no redirect takes place. The limitation of this redirect is that you can only redirect to page of your Web Application. Response.Redirect allows you redirect to any valid Url.

Notify your team when yor are going to leave the office

· 2 коммент.

What a strange situation? I want to discuss developer activity and can't find him! I'm not a manager, but i'm a team lead and i'm planing activity of this developer. So if developer is leaving office without any notification he should be punished. He should notify manager and his team. It's everything clear about boss. By why all team? Because team members may have questions to leaving person. So it's better to answer these questions before leaving the office. Otherive will have problems for sure!

Conclusion: If you don't want to have problems with your boss so don't leave the office without notifying him and your team.

Use "Is" prefix for methods with boolean return value

суббота, 26 июля 2008 г. · 0 коммент.

I'm sure that everyone uses methods which return boolean value. First of all you should make sure that these methods can't be moved to properties. If this is impossible you should give a good name to this method. I think that all methods which return bool value should start with Is prefix. Yes, I know that sometime it's difficult to give good name but you should try to do this at least.

Here is a sample how this may look like:


private static bool IsValidAgencyUser(AccountUserEntity user)
{
if (!user.AccountID.HasValue)
return false;
AccountEntity account = ControllerManager.AccountController.GetAccount(user.AccountID.Value);
if (account == null)
return false;
return account.IsLoginAllowed;
}

Use Path class instead of string manipulations

пятница, 25 июля 2008 г. · 0 коммент.

Today i've found such a code in my project. This code was added by other developer. The interesting thing about this code is bold line:


private static string GetFullPath(string directoryPath, string fileName)
{
if (string.IsNullOrEmpty(directoryPath))
throw new ArgumentOutOfRangeException("directoryPath");
if (string.IsNullOrEmpty(fileName))
throw new ArgumentOutOfRangeException("fileName");

return string.Format("{0}\\{1}", directoryPath.Trim('\\'), fileName);
}

What is wrong? If you want to be sure that path will be constructed properly use Path class and it static methods. Here is how this code should look like:

      private static string GetFullPath(string directoryPath, string fileName)
{
if (string.IsNullOrEmpty(directoryPath))
throw new ArgumentOutOfRangeException("directoryPath");
if (string.IsNullOrEmpty(fileName))
throw new ArgumentOutOfRangeException("fileName");

return Path.Combine(directoryPath, fileName);
}

Conclusion: Use Path class for file path manipulations instead of string manipulations

Remove old unused code

четверг, 24 июля 2008 г. · 0 коммент.

There is nothing more permanent the temporary things. Don't be lazy! Remove old unused code. It doesn't do anything but requires support. You may say that it may be required in future. Heh... I sure that everyone uses version control software. There should be no problem to find desired odler version of code and get removed code piece.

Conclusion: Current system version should contain minimal required amount of code. There is not place for old and unused code.

What should you do to become good prorammer?

· 0 коммент.

If you want to become good programmer you have to kill 10 bad programmers =)

IE 7.0 cookie problem

· 1 коммент.

I have site written in ASP.NET 2.0. Yesterday I've got complains about login problems from my customers. First of all i've checked if site works properly. I was able to login into test account. So problem was not in login implementation.

I've asked customers about web browser they using. It was Internet Explorer 7.0. I was using Fire Fox 3.0. So i've decided to use IE 7.0. I was really surprised when i was not able to login using it.

First idea was that it's security settings proble. I've played around with these settings. Nothing helps. Second idea was cookie settings. This didn't help too.

I've dicided to use havy artilery. I've used tool to see traffic. After some minuts I've found the source of problem. Server has been sending me expired cookie. This cookie was not send by browser during next request.

The source of problem was found. I've to find out why my site sends out of date cookie. The answer was simple. Clock settings were wrong. After system time of server was set to correct time probem has disappeared.

Conclusion: Check client time settings or server time settings to make sure that cookie expiration date is processed by browser properly.

Обо мне

Моя фотография
Кто к нам с чем и зачем, тот от того и того!