Saturday, February 16, 2008

Securing Configurations

Have you ever wanted to provide a level of protection to your values in the configuration files? aspnet_regiis will help you in encrypting the configuration section(s) in your config files. The executable resides in: "<windows_root>\Microsoft.NET\Framework\<framework_version>" and it was common to be used in installing ASP.NET on IIS. However, you can use it as well in encrypting/decrypting the configuration files.

Here is the command line used for encrypting a section in the web.config of SecureWebProj application:

aspnet_regiis.exe -pe connectionStrings -app /SecureWebProj

-pe attribute is used to tell the executable to encrypt the specified section. You can also use -pd attribute instead of -pe if you want to restore or decrypt the section to its original values. -app attribute is for specifying the application virtual path.

After encrypting the connectionStrings section, the web.config will look like that:

<connectionStrings configProtectionProvider="RsaProtectedConfigurationProvider">
<EncryptedData Type="http://www.w3.org/2001/04/xmlenc#Element" xmlns="http://www.w3.org/2001/04/xmlenc#">
<EncryptionMethod Algorithm="http://www.w3.org/2001/04/xmlenc#tripledes-cbc" />
<KeyInfo xmlns="http://www.w3.org/2000/09/xmldsig#">
<EncryptedKey xmlns="http://www.w3.org/2001/04/xmlenc#">
<EncryptionMethod Algorithm="http://www.w3.org/2001/04/xmlenc#rsa-1_5" />
<KeyInfo xmlns="http://www.w3.org/2000/09/xmldsig#">
<KeyName>Rsa Key</KeyName>
</KeyInfo>
<CipherData>
<CipherValue>j2E3lO/bMp8ljiDFKhRJu33zVD0mrXD7k5WV4nQ5uNJEav7cKcjhtO1ztCfxJw7ZE5uNdj+THVwJroZBoPEhtPAISPH75Zq
5C1G+5WOLcBwBBzbcp7C6i6U7+/IWmThTNFRAEdQp/lHryDkapep4MNUCGNZlcVLlmX0n/bqZEoE=</CipherValue>
</CipherData>
</EncryptedKey>
</KeyInfo>
<CipherData>
<CipherValue>D/Z9ZyH7P+9e3kDi5gLevpdqbjwia0uQ/cOB0gHVXc8=</CipherValue>
</CipherData>
</EncryptedData>
</connectionStrings>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20


Sometimes you just need to map the operation direct to the application physical path. This would be useful if you are using ASP.NET Development Server instead of IIS.
aspnet_regiis.exe -pef connectionStrings E:\Projects\SecureWebProj

Encrypting the configuration sections won't prevent you to access the configuration values from your code. If you have already completed the project and you need to encrypt some sections inside the configuration files, you don't have to modify your application code anymore. The code will still run properly and won't be affected by the encryption changes.

The nice part is that you can encrypt the web.config sections even within your code. The following sample encrypts the connectionStrings section in the web.config of SecureWebProj:

Configuration cfg = WebConfigurationManager.OpenWebConfiguration("/SecureWebProj");
ConnectionStringsSection section = (ConnectionStringsSection)(cfg.GetSection("connectionStrings"));
section.SectionInformation.ProtectSection("RsaProtectedConfigurationProvider");
cfg.Save();
1
2
3
4


You may ask: This is an encryption operation, so where the encryption keys? Actually, each .NET installation will create by default a new key container in your machine formally called: NetFrameworkConfiguarationKey. This will contains the needed keys for the providers to work. However, you can create a new key container using aspnet_regiis as well.
aspnet_regiis.exe -pc SecureKeyContainerName -exp

You may find more about securing your key containers in this MSDN entry: Securing ASP.NET Configuration. In the later command line, -exp attribute means that the key container is exportable. You can export this container to XML file and use it in any other machine. This would be useful if your application is running in a web farm and you want to share the encrypted configurations across the farm machines.

DZone


Thursday, February 14, 2008

Mohammed Hossam @ Microsoft

Great news! My dear friend, Mohammed Hossam, will join Microsoft Live Team in the next May. Mohammed is one of the best techinical professionals I have ever met. You can find that from his blog posts, sessions, initiatives and technical side talks. Mohammed is so effective in his work and his knowledge is always spread among the team. You can feel his innovation, spirit and knowledge when you work with him. He is one of the few guys who is always up-to-date with the new technologies and not always that he tries to use it in real projects if it really fit the needs.

We will miss you Mohammed. We wish you all the best of luck in Microsoft. Keep in touch!


Sunday, February 03, 2008

Survey Results

In December 29th, a survey were published for public to answer - for more details check this post. Here is the results of the survey:

Download the Survey Results: 2008_Survey_Results.zip

[Update] The attempt should be considered as a start to confirm the benefits of these kind of surveys. The results may appear to have some illogical information. Unfortunately, we have only 150 participants. Needless to say that the more you get participations, the more you get accurate results. But still I promised to publish the results even with this small number of participation. I hope to find more similar and effective attempts in the future from authorized and independent organizations in Egypt.


Saturday, December 29, 2007

Survey - The Software Industry Inside Egypt

This survey is one of the first initiatives aims to formulate accurate indicators about the software development industry inside Egypt. The survey will give important information about the current professional level of the software companies. It will try to measure different aspects in the industry like the companies technical level, management, process, salaries and the work environments. The target is to give informative details for the IT stuff to get a clear and transparent information regarding their career.

Please be accurate in your answers as much as you can. Your answer is definitely affect the overall results and the others attitude. The final results will be published here in this blog.

* We don't collect any identity information in this survey.

ANSWER THE SURVEY NOW!

[Update]

[03/2/2008] The survey results have been published. Click here
[31/1/2008] The survey results will be published on Sunday, 3rd February, 2008
[12/1/2008] The survey participation period is extended to 19th Jaunary, 2007


Thursday, December 27, 2007

Vote Results: Do you apply design patterns in your software projects?

This is the result of a vote I made later: Do you apply design patterns in your software projects? The question is to illustrate if the developers really care about learning solutions for already predefined problems. Do you really care about using the best solution to solve a problem?

37 people contributed in the vote. The following is a chart representing people votes.





Design Patterns are a collection of patterns documenting successful solutions for specific problems. The term introduced from a long time. Most of the developers uses the patterns in there daily work, but don't really know that it's a predefined design pattern until they read about it. For more information about the topic, I highly recommend this book: "Design Patterns - Elements of Reusable Object-Oriented Software" by "Erich Gamma, Richard Helm, Ralph Johnson, John Vlissides". For a brief summary about the book, check the Wikipedia Version


Saturday, December 22, 2007

Image Resizing

Sometimes you need to process the users' uploaded images in your web application so that it doesn't take too much space. This can be done either by resizing the uploaded image, saving it in a specific format or may be both.

The following is a code snippet for resizing images and saving it in *.jpeg format. The method take the image file to be resized as a stream, the destination path, the file name to save the image as and the maximum side size of the image (i.e the output image should fit a square of this maximum side size).


public static void ResizeImage(Stream originalImageStream, string destinationFilePath,
string destinationFileName, ImageEncoding saveEncoding, int maxSideSize)
{
int intNewWidth;
int intNewHeight;

Bitmap original = new Bitmap(originalImageStream); // your original image

//Set the image format
ImageFormat fmtImageFormat = original.RawFormat;

//Get the image original width and height
int intOldWidth = original.Width;
int intOldHeight = original.Height;

//Determine if Landscape or Portrait
int intMaxSide;

if (intOldWidth >= intOldHeight)
{
intMaxSide = intOldWidth;
}
else
{
intMaxSide = intOldHeight;
}


if (intMaxSide > maxSideSize)
{
//set new width and height
double dblCoef = maxSideSize / (double)intMaxSide;

intNewWidth = Convert.ToInt32(dblCoef * intOldWidth);
intNewHeight = Convert.ToInt32(dblCoef * intOldHeight);
}
else
{
intNewWidth = intOldWidth;
intNewHeight = intOldHeight;
}


Size resolution = new Size(intNewWidth, intNewHeight); // size of your thumbnail

Image thumbnail = new Bitmap(original, resolution);

Graphics g = Graphics.FromImage(thumbnail);

// The InterpolationMode was the catalyst to eliminate pixelation.
g.InterpolationMode = InterpolationMode.HighQualityBicubic;
g.CompositingQuality = CompositingQuality.HighQuality;
g.SmoothingMode = SmoothingMode.HighQuality;

g.DrawImage(original, new Rectangle(0, 0, thumbnail.Size.Width, thumbnail.Size.Height));


// Prepare for a controlled-quality JPEG export
ImageCodecInfo jpegCodec = GetEncoderInfo("image/jpeg");
Encoder jpegEncoder = Encoder.Quality;
EncoderParameters jpegEncoderParameters = new EncoderParameters(1);
EncoderParameter jpegEncoderQuality = new EncoderParameter(jpegEncoder, 100L /*jpegQuality*/);

jpegEncoderParameters.Param[0] = jpegEncoderQuality;

thumbnail.Save(destinationFilePath + destinationFileName + ".jpg", jpegCodec, jpegEncoderParameters);
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67

You will have to get the appropriate codec information to save the image.

ImageCodecInfo jpegCodec = GetEncoderInfo("image/jpeg");
1

The following is the implementation of GetEncoderInfo.
private static ImageCodecInfo GetEncoderInfo(string encoderString)
{
foreach (ImageCodecInfo info in ImageCodecInfo.GetImageEncoders())
{
if (info.MimeType == encoderString)
return info;
}

return null;
}
1
2
3
4
5
6
7
8
9
10


Simply you loop through all the encoders in ImageCodecInfo to find JPEG codec info. Other codecs info can also be retrieved for other image types like PNG, JIF and BMP.

The interesting point is in specifying the quality of your output image so that you avoid the pixelation problem and make your output image looks smooth. You declare a new Encoder Parameter with the required quality of your output image. Then you pass the encoding parameters when saving the final resized image.

// Prepare for a controlled-quality JPEG export
ImageCodecInfo jpegCodec = GetEncoderInfo("image/jpeg");
Encoder jpegEncoder = Encoder.Quality;
EncoderParameters jpegEncoderParameters = new EncoderParameters(1);
EncoderParameter jpegEncoderQuality = new EncoderParameter(jpegEncoder, 100L /*jpegQuality*/);

jpegEncoderParameters.Param[0] = jpegEncoderQuality;
1
2
3
4
5
6
7

The quality encoder parameter may have varying values (i.e. 25L, 50L, 75L and 100L). You will have to tune it to balance the quality with the output image size.

Another point to mention that there are many other interesting encoders you can make use of like Encoder.Transformation - which allowing you to rotate or swap your images. You can find more information here.


Thursday, December 20, 2007

Language-specific Code Compilation in App_Code

App_Code folder is the default location to add your code files for your ASP.NET project. You may have the situation when you want to add mixed code files written in different languages i.e C# or VB.Net and you need to include these mixed files in the project compilation. The question: Can I have mixed files some written in C# and others in VB.NET in the App_Code folder? Yes, you can but in limitation. First, you will have to add different folders for each language-specific code. Then, in web.config add an entry for each folder inside CodeSubDirectories tag.

<?xml version="1.0"?>
<configuration>
<system.web>
<compilation debug="true">
<codeSubDirectories>
<add directoryName="CSharpFolder"/>
<add directoryName="VBFolder"/>
</codeSubDirectories>
</compilation>
</system.web>
</configuration>
If the folder you added to codeSubDirectories tag doesn't physically exist, you will have a compilation error.
The code subdirectory '/MyProject/App_Code/CSharpFolder/' does not exist. E:\Projects\MyProject\web.config 


Monday, December 10, 2007

ASP.NET MVC Framework CTP is Finally Released.

ASP.NET MVC CTP is finally released. The framework is released as a part of new ASP.NET 3.5 Extensions package. The extensions includes some new stuff beside the MVC framewok like: The Entity Framework, new additions for ASP.NET AJAX and others.

Download ASP.NET 3.5 Extensions

Scott Guthrie published a series of articles about MVC. Here is the full list:

ASP.NET MVC Framework: Introduction
ASP.NET MVC Framework (Part2): URL Routing
ASP.NET MVC Framework (Part3): Passing ViewData From Controllers to Views
ASP.NET MVC Framework (Part4): Handling Form Edit and Post Scenarios


Saturday, October 20, 2007

Scrum in Action

We are now working in a project which have taken more than 6+ months and still in progress. 159078+ lines of code, 80+ page, 120+ user controls, 100+ tables and counting. In projects with such scale, you need to manage and control your development life cycle. You want to decrease all risks and possibilities of failure. Working with Scrum methodology helps a lot in making developers time management more efficient.

I'll try to state some points which helps us during the development of the project. My recommendation points maybe a part of the scrum definition and maybe not. But sometimes practice is more trivial than science. The following are the concluded results.

Design meetings: In each project you have to design. But as a fact, the design will change. So all what you need is to put the outlines. You don't have to state all the details. Try to make the design meetings for things which is really need a heavy mind storming and architecture. This includes frameworks, libraries and infrastructures. Discussing the design of each part in the project is a time consuming and won't help you that much.

Time Estimation: When estimating the time of the tasks, it should be in the presence of your team members as it's a part of the sprint planning. The sprint planning is usually a long boring meeting. For each task, each member will make an estimate. Then the average will be the final estimate of the task. If some member give an estimation which isn't reasonable or far away of the others estimations average, you start to ask him why? He may know something in the task which is mysterious, may take more time or may need more resources. Depending on all these discussions you will get a better estimation and better time management.

Another point, if a task will take more than 2 days, you should start to think about dividing it. Most of the uncompleted and bottlenecks in the projects are the long estimated tasks. The estimation of the long tasks are usually not accurate. Even the scrum master won't be able to know your progress each day if you just telling him "I am still working on it". Try to divide your task to smaller parts so that you can give it a better estimation.

Daily meetings: The essence of the scrum is the daily scrum meetings. If you didn't do it daily you will lose process monitoring. The team activity will be degraded. You won't be able to finish the work on the estimated time. Try to keep on this 15 min. meeting every day. Try to keep these meetings physical as much as you can. I mean here to avoid instant messaging meetings or such stuff. Instant messaging meetings takes much time than the physical ones. People don't take care about the time while messaging and the scrum master won't be able to control it. Try to determine a fixed time for the meeting each day - ideally - 15-30 min. maximum - and make sure it doesn't exceed the time limit.

Code Review: Usually you will need to refactor some parts of your code with your teammates. Code Review Meeting is your way to do that. Problems exists when you try to make "code reviews" as a rule in each sprint. It doesn't work like that. From my experience don't do any code review if you don't have a predefined list of your targets and you really have a problem you want to solve. If you have nothing to review in these meetings, then it will be a hassle and it will be something other than a technical meeting! It will be time consuming and the meeting will end up with nothing. Specify the targets of the meeting before scheduling it. Team members may inform the scrum master if they think there is a part in their code should be refactored in attendance of the other team members.

Design Changes Reporting: Keep all design documents on your source control or repository folder. Make sure that any updates on the designs, flow, sequence diagrams or even requirements modifications are accessible for all the team members. Problems occurred if one of the team members changes something in the design or the flow and didn't inform the others about it. The best practice is to update your documents with any modifications and commit it in your repository. Not only that but you should inform the others about your modifications and the member you think his work will be affected with your changes.

Bug Fixing: During the sprint, testers may start to test your work of the previous ones. Bugs will be accumulated and it's not considered as a part of the sprint estimation. You have 2 choices, either allocate a member in your team to fix all these stuff or assign the bugs to their owners. The later option - if not well controlled - will contradict with the scrum rules. The developers will have an increasing bug list and will feel that they don't make any progress. The solution is to postpone any generated bugs through the sprint to the next one. Testing the work during the development is really a mess . Testers may report some bugs which are features to be implemented on the sprint. Still the bugs should be reported but not assigned to the developers during the sprint. It should be postponed. In the next sprint meeting it will be considered in the developers estimation.

Injecting Members to the Team: You have time constraints and you want your developers to take care of the new features. But in the same time, you have a list of bugs to be fixed. Don't inject external developers to fix these bugs. Especially if they don't have enough idea about the project and the requirements. You will end up with a longer bug list!

This is my review about the best practice which makes the scrum process more efficient. Still it's not that perfect on all the time. Try to modify the process to fit your needs. Although learning and reading is so important to improve your process, but still nothing better than practice.

Dzone - Vote for for this article!
Stumbleupon - Add Your Review


Tuesday, October 09, 2007

Finally MVC Model For ASP.NET

Finally we will have MVC model for ASP.NET. This was announced on Alt.Net Conference last day. In my opinion, this will be one of the most interesting feature added to ASP.NET. MVC is one of the old design patterns which introduced in many object-oriented languages. In MVC pattern, controllers just handle application flow, models represent the data, and the view is just concerned about presentation logic. The model was first introduced in SmallTalk. It is widely used on many other web frameworks like Zend Framework for PHP and MoneRail.

I was reading about Zend Framework from a while and I liked the way which they separate their pages and controllers classes. The model itself has a great trust from many web developers especially when building large scale projects where updatability is a critical issue.

Using MVC model, you will be able to define you application URLs like:
http://domain_name/Controller/Action/Parameter1/Parameter2/...

Where you map a URL to a certain Controller and action.

Read more about this topic here.
For more about MVC Model, check out this post