Creating Required Literal for MVC with Razor rendering engine

In web applications, It is became a standard to have a symbol indicating if the field is required or not. This symbol maight be a star, icon or any verbiage that a client ma requested to have. It is a good practice to have the logic that render this symbol in one place and have all of your views using it. You can do that easily in standard ASPX pages, and it is the same on MVC using Razer rendering engine (cshtml/vbhtml). For MVC you need to create a custom HTML helper that do the job for you, and using it in your views cross the board. Below is a sample HTML helper method

 

public static MvcHtmlString RequiredFieldIcon(this HtmlHelper helper)
{
TagBuilder tag = new TagBuilder(“span”);
tag.AddCssClass(“color-color-text”);
tag.Attributes.Add(“title”, “Field is required”);
tag.SetInnerText(“>> “);
return MvcHtmlString.Create(tag.ToString(TagRenderMode.Normal));
}

In above method, the symbol is as simple as ‘>>’ in red color; using CSS class for that. it might be more complicated UI control and you can customize it based on your requirement. You can use this method just as if it is one of the out of the box HTML helpers that shipped with MVC; you just need to make sure you are including the namespace of the class that hosting this HTML helper method.

@Html.RequiredFieldIcon()

Using Google Calculator for Money Exchange

While working in one of the projects, one of the main requirements was to do money exchange from a specific currency to another. When I was looking into this functionality, I thought that is going to be a hard thing to be implemented as it is touching a critical area related to money. in fact, Thanks to Google calculator.. implementing such a functionality was a very easy job and it took from me like 1 hour to be done… Google Calculator has a very easy to be consumed APIs. below code explaining how could I consume Google Calculators to get the up to date exchange rate between 2 different currencies.

   /// <summary>
/// Currency Exchange Service that is responsible
/// </summary>
public class CurrencyExchangeService
{private static string GoogleCalculatorApiUrl
{
get
{
return “http://www.google.com/ig/calculator?hl=en&q={0} {1} to {2}”;
}
}

/// <summary>
/// Do currency Exchange between currencies.
/// </summary>
/// <param name=”fromCurrencyCode”>Source Currency Code</param>
/// <param name=”toCurrencyCode”></param>
/// <param name=”amountToConvert”></param>
/// <param name=”roundedDecimalPoints”></param>
/// <returns></returns>
public static decimal ConvertCurrency(string fromCurrencyCode, string toCurrencyCode, decimal amountToConvert = 1, int roundedDecimalPoints = 4)
{
if (fromCurrencyCode == null)
throw new ArgumentNullException(“fromCurrencyCode”);
else if (toCurrencyCode == null)
throw new ArgumentNullException(“toCurrencyCode”);
else if (amountToConvert < 0)
throw new ArgumentOutOfRangeException(“amountToConvert”);

if (string.Compare(fromCurrencyCode, toCurrencyCode, true) == 0)
return amountToConvert;
else if (amountToConvert == 0)
return 0;

var request = HttpWebRequest.Create(string.Format(GoogleCalculatorApiUrl, amountToConvert, fromCurrencyCode, toCurrencyCode));
request.Timeout = 5000;
using (var response = request.GetResponse())
{
using (var stream = new StreamReader(response.GetResponseStream(), Encoding.GetEncoding(“iso-8859-1”)))
{
Match match;
if ((match = Regex.Match(
stream.ReadLine(),
@”{lhs: “”(?<From>[0-9.\s]+)(.*?)””,rhs: “”(?<To>[0-9.\s]+)(.*?)””,error: “”(?<Error>(.*?))””,icc: (true|false)}”,
RegexOptions.Singleline | RegexOptions.IgnoreCase)
).Success)
{
//Parse response from Google Calculator.
var result = new
{
From = Regex.Replace(match.Groups[“From”].Value, “[^0-9.]”, string.Empty),
To = Regex.Replace(match.Groups[“To”].Value, “[^0-9.]”, string.Empty),
Error = match.Groups[“Error”].Value
};

if (string.IsNullOrEmpty(result.Error))
{
return Math.Round(Convert.ToDecimal(result.To, CultureInfo.InvariantCulture), roundedDecimalPoints);
}

throw new Exception(string.Format(“Converter error: {0}.”, result.Error));
}

throw new Exception(“Response format error.”);
}
}
}
}

How to Create Pivot Tables with MS Excel

Usually when you have a large list of data; you will need to have summary and statistics out from this list to take decisions. I mean by summary things like:

1. How many records do we have under certain category?

2. What is the best time that my product is being sold?

3. How my salespersons performing during the course of certain period?

The easiest way to get the answers of the above questions is to create a pivot table on Microsoft Excel. Pivot tables are interactive tables where it extract data and summaries the data in a more meaningful format. It will make it easy to analyze and make comparisons detect what kind of decisions you need to do.

Let’s assume that we have the following list and we need to extract summary data from it.

datasource snapshot image

 

to create pivot table do the followings:

1. highlight your data table.

2. from insert tab; Click on Pivot table

3. make sure the Table/Range is selecting the correct range of data that you need to create your report against.

4. Click OK

5. Configure your items as showing on the below snapshot

 

pivot table snapshot table

 

I would recommend to play with the columns and rows to let you understand the concept in a solid way. using Pivot table will save time and effort when you are create reports to take decision up on. I’m attaching sample data here if you would like to download and play with it.

Google Chrome Frame Plugin!

There is many of technologies that are not supported in IE 6,7,8 and even 9; such as rich text editing and faster Java script execution. some of these features supported on the new versions of IE but not supported in the older versions, like the curve edges for tables, buttons..etc (supported on IE 9 but not on IE 6)

Usually the end users would like to see the same UI over any browsers and the bad news is, there are some people working on the very old version of IE; IE 6 – I have no idea why they still using such browser.

on the other hand; the GOOD NEWS; There is plugin form Google Chrome, that you can install it on the old IE version and let Chrome handle rendering the websites just like if it is running under chrome. it will be look very good and execute the client side script in very efficient way. that would make the developer life much easier and get rid of having the headache of supporting multiple browsers with very old technologies like IE 6!

Installing this plugin will be very easy, it will be a matter of single click, to install this plugin, please use the below link to get into the downloadable area from Google Chrome!http://www.google.com/chromeframe?quickenable=true

Basically, this plugin will create a frame inside the IE and let Chrome rendering engine render the web page instead of the IE browser; that means whatever is supported on the LATEST chrome version will be there as well. it is like do a perfect union between IE and chrome to get the best of chrome inside the IE!

How to Install OneNote Printer to Simulate Printing Process

One of the components that I worked on recently is printing components and I got into a need to test how things going when I print out to the printer. It was a costly thing to keep printing out into a hard copy papers. one of the ultimate solutions for this is to simulate the printing process. so I start using OneNote printer (which is installed automatically once you install MS OneNote product). it was brilliant idea to use it and it worked just perfectly.

For some reasons the OneNote printer got deleted from my machine, and I got into a need to use it again; I look up for help and I found this article that helped me on reinstalling the printer again http://speedstug.com/node/85… This solved the issue that I faced.

Locate the Position of website user by IP Address

How can sites knows the country of users? a friend of mine asked me that question and that question drive us into long conversation about “Locating Positions of website’s user”. the idea is very simple behind how the sites locate users’ location. it is by IP address. these days there are many sites that can let you determine in which country a certain IP address, more over, it may give you a very accurate address. I’m usually using ip2location site but there are many websites that do the same job like geobytes and hostip.

Also there are some sites which selling database of IP addresses and locations but you need to keep updating your database every once awhile incase you decided to go with that

Go for Wireless Internet Connections

I had a discussion with a friend of mine about why to go with Wireless Internet connections rather than using the standard way for it; meaning over land phone lines. I have been using wireless internet connectivity for like 2 years by and I am super happy with it. the first concern that I have about it; is the stability for the connection over bad weather conditions. that was my only one concern that I have when I switch to the wireless internet connectivity. but after trying it; I found the wireless connections work very good in the bad weather condition (off course depending on your ISP)

After 2 years of using the wireless internet connection, I found it is more efficient than using land phone lines to connect to internet for many reasons. One of the main reason is I can go anywhere in my country and connect to internet easily as long as there is coverage in the area that I’m on it. This made my life much easier and I could do my work in more effective way.

Some companies having some sort of flexibility in their environment; I know couple of them for sure that implementing the flex-work-environment very effectively like integrant.com and O2; for me to be able to utilize this flexibility of work environment, I need to have flexible internet connection which will let me choose wireless internet connection over land-phone-internet to be able to get full benefits from the flexibility that I have in place.

While technologies emerging, the wireless internet speed are become very fast and competing the land-phone-internet’s speed of internet which is making this is the best choice to go with.

One of the good things that late emerge is Wireless Routers with USB Dongle; which will let you to get a USB dongle as an internet modem and connect this dongle into your wireless router to get a wireless network that is connected to internet thus you will not fin yourself in a situation where you need to pay good amount of money just to get a wireless router that is connecting to wireless internet.

at the end; I strongly recommending going with wireless internet connections over land-phone-internet and believe me you will touch the different in the first week. I would recommend also checking this link

Read and Write BLOB objects on SQL Server

I had faced couple of cases where I need to store files inside the SQL Server rather than storing these files on the file system. for the cases I faced, I compared the value of storing the files inside SQL server versus storing those files on the file system and start interact with the file system and I found going with storing these files in SQL server is much valuable for me which may be the same case for you as well.

To store the files on sql server do the followings:

SELECT TOP 1 *

FROM OPENROWSET (BULK N’<FilePath>’, SINGLE_BLOB) TblName

the above statement will read the file contents and convert it into Binary format (which is the format of BLOB on DB). Make sure to replace <FilePath> with the correct path at your DB Server. meaning this path should be a valid path on DB Server.

after reading the file contents; you can push this content into your DB Tables using ordinary Insert Statement.

Insert into Tbl (FileContent)

SELECT TOP 1 *

FROM OPENROWSET (BULK N’<FilePath>’, SINGLE_BLOB) TblName

To Read file Contents from DB follow the following steps:
1. Open Command Prompt on SQL Server

2. Type the following Command:

 

C:>bcp “<SQL STATMENT>” queryout <OutputFilePath> -T –d <DBNAME>

make sure to replace the following placeholders:

  • <SQL STATEMENT> by your SQL Statement that retrieving the file contents
  • <OutputFilePath> the destination file path including filename
  • <DBNAME> your DB Name

3. There will be couple of questions , answer them as below
     Enter the file storage type of field Media [image]: <Enter>
        Enter prefix-length of field Media [4]: 0
        Enter length of field Media [0]: <Enter>
        Enter field terminator [none]: <Enter>
    Do you want to save this format information in a file? [Y/n] y

 

 

I hope you will find this article helpful… Please let me know what do you think by posting your comments

Motivational Video

A very wonderful video that I wanted to share with you.. It is a very true thing… It is a great motivator for me

 

Conditional Page Break in SRSS Reports

one of the cases that I faced recently is having conditional page break in SRSS report. this is not an out of the box feature in SRSS and I had to do a workaround in order to accomplish this feature. To do so, I followed these steps:

  1. Add a rectangle to your report
  2. Right click on the rectangle and select “rectangle properties “
  3. Check the checkbox related to “Add a page break after” or “Add a page break before”; depending on the location of the rectangle and where the page break is intended to be.
  4. The tricky point is to set a visibility condition that control when the rectangle. The point is if the rectangle is invisible; then there will be no page break.