Round up a number to highest 10s place

0

Download Source Code

Recently we faced a problem that we need to round-up a number to greatest 10s place.
For ex: we needed to round-up a number as follows
1023 -> 2000
37911 -> 40000
912345 –> 1000000

First we checked Math.Round(). But it didn’t solve our problem.  Math.Round() supports only rounds a value to the nearest integer or to the specified number of fractional digits. Further checking we come up a solution by using Math.Ceiling() method.

Math.Ceiling()returns the smallest integral value that is greater than or equal to the specified double-precision floating-point number.
For ex:
Math.Ceiling(7.3)     -> 8
Math.Ceiling(7.64)     -> 8
Math.Ceiling(0.12)     -> 1

Below is the solution we came up

decimal[] values = { 1023, 37911, 23000, 1234, 912345 };
foreach (var value in values) {
//// get the lenght of the 10s places;
var length = (int)Math.Log10((double)value);
//// using Math.Pow() calculate the power of 10s
var power = Math.Pow(10, length);
//// var roundadValue = Math.Ceiling(1023 / 1000) * 1000;
var roundadValue = Math.Ceiling(value / (decimal)power) * (decimal)power;

Console.WriteLine("Value:{0} Rounded Value:{1}", value, roundadValue); 

}

Math.Ceiling() Results

The Logic


Math.Ceiling(value / (decimal)power) * (decimal)power;
var roundadValue = Math.Ceiling(1023 / 1000) * 1000;

so, for any number, fist compute power of 10s and then it use for above calculation to get the results.

Counting Consecutive Dates Using SQL

1

Download demo query

Recently I have answered one of the SQL based question in the CodeProject. Thanks for the participant that question wake up me to write this blog post.

Question:

He has a table (tblLeave) with the data like below.

PAYCODE		LV_TYPE	FROM_DATE		TO_DATE	        	LVALUE
5023		SL    	14/12/2012 0:00		14/12/2012 0:00		1
5023		SL    	15/12/2012 0:00		15/12/2012 0:00		1
5023		COF   	16/12/2012 0:00		16/12/2012 0:00		1
5023		SL    	19/12/2012 0:00		19/12/2012 0:00		1
5023		SL    	22/12/2012 0:00		22/12/2012 0:00		1
5023		SL    	23/12/2012 0:00		23/12/2012 0:00		1
5023		SL    	24/12/2012 0:00		24/12/2012 0:00		1
5023		PL    	28/12/2012 0:00		28/12/2012 0:00		1
5023		PL    	29/12/2012 0:00		29/12/2012 0:00		1
5023		PL    	30/12/2012 0:00		30/12/2012 0:00		1
5023		PL    	31/12/2012 0:00		31/12/2012 0:00		1

And he wants to output the data as below

PAYCODE LV_TYPE FROM_DATE       TO_DATE         LVALUE
5023    SL      14/12/2012 0:00 15/12/2012 0:00 2
5023    COF     16/12/2012 0:00 16/12/2012 0:00 1
5023    SL      19/12/2012 0:00 19/12/2012 0:00 1
5023    SL      22/12/2012 0:00 24/12/2012 0:00 3
5023    PL      28/12/2012 0:00 31/12/2012 0:00 4

Condition: If same type of leave taken continuously, it should be merged in one row mentioning from_date to to_date.

Answer:

When I saw that question first time, I didn’t go through in details and just thought that was an easy grouping query. And I just gave following answer.

SELECT LV_TYPE,LV_TYPE,MIN(FROM_DATE) AS FROM_DATE ,MAX(TO_DATE) AS TO_DATE, COUNT(LVALUEP) AS LVALUE
FROM tblLeave
GROUP BY PAYCODE,LV_TYPE

But that’s wrong, he made comments saying it doesn’t make sense and highlighted the condition he wants. (Thanks for him; he didn’t down vote my answer). Again I read the question… Oh… That was a tricky question. He needs to group the leave by consecutive date. Isn’t that tricky?

To answer that, I use the DATEDIFF SQL function

DATEDIFF ( datepart , startdate , enddate )

http://msdn.microsoft.com/en-us/library/ms189794.aspx

Following is my answer and the output

SELECT PAYCODE,LV_TYPE, MIN(FROM_DATE) AS FROM_DATE,
       MAX(FROM_DATE) AS TO_DATE, COUNT('A') AS LVALUE
FROM (
SELECT PAYCODE,LV_TYPE,FROM_DATE,
    DATEDIFF(D, ROW_NUMBER() OVER(ORDER BY FROM_DATE), FROM_DATE) AS Diff
FROM tblLeave) AS dt
GROUP BY PAYCODE,LV_TYPE, Diff
ORDER BY FROM_DATE
PAYCODE     LV_TYPE FROM_DATE               TO_DATE                 LVALUE
----------- ------- ----------------------- ----------------------- -----------
5023        SL      2012-12-14 00:00:00.000 2012-12-15 00:00:00.000 2
5023        COF     2012-12-16 00:00:00.000 2012-12-16 00:00:00.000 1
5023        SL      2012-12-19 00:00:00.000 2012-12-19 00:00:00.000 1
5023        SL      2012-12-22 00:00:00.000 2012-12-24 00:00:00.000 3
5023        PL      2012-12-28 00:00:00.000 2012-12-31 00:00:00.000 4

Query Explanation:

Before explain the logic see the following query and the output.

SELECT PAYCODE,LV_TYPE,FROM_DATE,
	ROW_NUMBER() OVER(ORDER BY FROM_DATE) AS ROW_NUMBER,
    DATEDIFF(D, ROW_NUMBER() OVER(ORDER BY FROM_DATE), FROM_DATE) AS Diff
FROM tblLeave
PAYCODE     LV_TYPE FROM_DATE               ROW_NUMBER           Diff
----------- ------- ----------------------- -------------------- -----------
5023        SL      2012-12-14 00:00:00.000 1                    41254
5023        SL      2012-12-15 00:00:00.000 2                    41254
5023        COF     2012-12-16 00:00:00.000 3                    41254
5023        SL      2012-12-19 00:00:00.000 4                    41256
5023        SL      2012-12-22 00:00:00.000 5                    41258
5023        SL      2012-12-23 00:00:00.000 6                    41258
5023        SL      2012-12-24 00:00:00.000 7                    41258
5023        PL      2012-12-28 00:00:00.000 8                    41261
5023        PL      2012-12-29 00:00:00.000 9                    41261
5023        PL      2012-12-30 00:00:00.000 10                   41261
5023        PL      2012-12-31 00:00:00.000 11                   41261

By seen this, you will realize that above query generate the same Diff  value for all the consecutive dates. Now you can easily group this and get the counts as you like.

Adding styles dynamically to ASP.NET page header

2

Recently when I was working on the ASP.NET web site I wanted to modify the page styles dynamically. I googled and found that there are various technique out there for this. In this Article, I wish to share those techniques with.

Following are some of the techniques out there to accomplish this.

1. By using Page.header.Controls.Add()

Page.Header property gets the document header of the page if the head element is defend with “runat=server”  tag in the page declaration.The Header property gets a reference to an HtmlHead object that you can use to set document header information for the page. The HtmlHeadallows you to add information such as style sheets, style rules, a title, and metadata to the head element.

http://msdn.microsoft.com/en-us/library/system.web.ui.page.header.aspx

By using a literal control you can include the CSS file or even a style set.

Literal cssFile = new Literal()
{
    Text = @"<link href=""" + Page.ResolveUrl(styleFilePath) + @""" type=""text/css"" rel=""stylesheet""/>"
};
Page.Header.Controls.Add(cssFile);
Page.Header.Controls.Add(
new LiteralControl(
@"<style type='text/css'>
        .myCssClass
        {
background: black;
border: 1px solid;
        }
</style>
    "
));

Or HtmlGenericControl can use to add the styles file

//// Insert css file to header
HtmlGenericControl oCSS = oCSS = newHtmlGenericControl();
oCSS.TagName = "link";
oCSS.Attributes.Add("href", "css/mystyle.css");
oCSS.Attributes.Add("rel", "stylesheet");
oCSS.Attributes.Add("type", "text/css");
this.Page.Header.Controls.Add(oCSS);

2.  Page.Header.Stylesheet

More elegant technique is use of the Page.Header.Stylesheet Instead of using the string to defend styles (like above with Literal) you can use the style properties to create this.

//// Create dynamic style rule which applies to the css class selector (“.MyCssClass”)
Style dynamicClassStyle = new Style();
dynamicClassStyle.BorderStyle = BorderStyle.Solid;
dynamicClassStyle.BorderColor = System.Drawing.Color.Black;
dynamicClassStyle.BorderWidth = new Unit(1);
dynamicClassStyle.BackColor = System.Drawing.Color.White;
Page.Header.StyleSheet.CreateStyleRule(dynamicClassStyle, null, ".MyCssClass");
//// Create dynamic style rule which applies to type selector ("DIV")
Style dynamicTypeStyle = new Style();
dynamicTypeStyle.BorderStyle = BorderStyle.Solid;
dynamicTypeStyle.BorderColor = System.Drawing.Color.Black;
dynamicTypeStyle.BorderWidth = new Unit(1);
dynamicTypeStyle.BackColor = System.Drawing.Color.White;
Page.Header.StyleSheet.CreateStyleRule(dynamicTypeStyle, null, "DIV");

For more information please refer
http://msdn.microsoft.com/en-us/library/system.web.ui.istylesheet.createstylerule.aspx

With whatever the technique you follow please remember the following hints also,

Adding styles programmatically using the methods of the IStyleSheet interface during asynchronous postbacks is not supported. When you add AJAX capabilities to a Web page, asynchronous postbacks update regions of the page without updating the whole page.

Web service and Script service

0

Most of you are familiar about writing a web service using c#. Visual Studio provides the project template which easily creates a web service for you.

Visual Studio Project Template

Hello world web service

I’m sure you may know how to call this web service using c#. But do you know how to call the web service using client side scripts such as JavaScript? There are various ways to do this. I will demonstrate this using jQuery$.ajax() function.

        function callSvc() {
            $.ajax({
                type: "POST",
                url: "Service1.asmx/HelloWorld",
                data: "",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function(data, status) { alert(data); },
                error: function(request, status, error) { alert(request); alert(status); alert(error); }
            });
        }
    

When you call the HelloWorld() service, by default you will get “500 – Internal server error” error message.

JavaScript debug mode

This error raised because you haven’t configured this service to access using client side scripts. When you Check the responseText, you will notice that it says “Only Web services with a [ScriptService] attribute on the class definition can be called from script.

To resolve this you have to configure your web service with [ScriptService] attribute.

[System.Web.Script.Services.ScriptService]
public class Service1 : System.Web.Services.WebService

When adding [ScriptService] attribute to the web service, it gets automatically handled by the ScriptHandlerFactory and creates a JavaScript proxy class for the web service. That means, you will be able to call the web service from the client side script same way as you call it from the code behind. You can view the generated proxy class by using the following command.

http://<URL>/SimpleWebService.asmx/js
http://<URL>/SimpleWebService.asmx/jsdebug

Compare the generated proxy class with the service description (http://<URL>/Service1.asmx?WSDL) and let me know what you noticed.

Download Demo Project

How to validate a credit card number?

2

All you know what information contains in your NIC number. But do you know what information contains in the Credit Card Number? Here are some useful details.

Card Length

Typically, credit card numbers are all numeric and the length of the credit card number is between 12 digits to 19 digits.

  • 14, 15, 16 digits – Diners Club
  • 15 digits – American Express
  • 13, 16 digits – Visa
  • 16 digits – MasterCard

For more information refer: http://en.wikipedia.org/wiki/Bank_card_number

Containing Information

Sample Credit Card

1 – Major Industry Identifier (MII)

The first digit of the credit card number is the Major Industry Identifier (MII). It designates the category of the entry which issued the card.

  • 1 and 2 – Airlines
  • 3 – Travel
  • 4 and 5 – Banking and Financial
  • 6 – Merchandising and Banking/Financial
  • 7 – Petroleum
  • 8 – Healthcare, Telecommunications
  • 9 – National Assignment

2 – Issuer Identification Number

The first 6 digits are the Issuer Identification Number. It will identify the institution that issued the card. Following are some of the major IINs.

  • Amex – 34xxxx, 37xxxx
  • Visa – 4xxxxxx
  • MasterCard – 51xxxx – 55xxxx
  • Discover – 6011xx, 644xxx, 65xxxx

3 – Account Number

Taking away the 6 identifier digits and the last digits, remaining digits are the person’s account number (7th and following excluding last digits)

4 – Check digits

Last digit is known as check digits or checksum. It is used to validate the credit card number using Luhn algorithm (Mod 10 algorithm).

For more information please refer.
http://en.wikipedia.org/wiki/Bank_card_number
http://en.wikipedia.org/wiki/List_of_Issuer_Identification_Numbers

Luhn algorithm (Mod 10)

The Luhn algorithm or Luhn formula, also known as the “modulus 10″ or “mod 10″ algorithm, is a simple checksum formula used to validate a variety of identification numbers, such as credit card numbers, IMEI numbers, National Provider Identifier numbers in US and Canadian Social Insurance Numbers. It was created by IBM scientist Hans Peter Luhn. (http://en.wikipedia.org/wiki/Luhn_algorithm)

When you implementing the ecommerce application, it is good practice to validate credit card number before send it to the bank validation. This saves a lot of time and money by avoiding a trip to the bank.

Here are the Luhn steps which can used to validate the credit card number.

4 0 1 2 8 8 8 8 8 8 8 8 1 8 8 1

1. Starting with the check digit double the value of every other digit (right to left every 2nd digit)

Mod 10 Step 1

2. If doubling of a number results in a two digits number, add up the digits to get a single digit number. This will results in eight single digit numbers

Mod 10 Step 2

3. Now add the un-doubled digits to the odd places

Mod 10 Step 3

4. Add up all the digits in this number

Mod 10 Step 4

If the final sum is divisible by 10, then the credit card number is valid. If it is not divisible by 10, the number is invalid.

Here is the code sample that I used to do the mod10 validation

public static bool Mod10Check(string creditCardNumber)
{
 //// check whether input string is null or empty
 if (string.IsNullOrEmpty(creditCardNumber))
 {
 return false;
 }

//// 1. Starting with the check digit double the value of every other digit
 //// 2. If doubling of a number results in a two digits number, add up the digits to get a single digit number. This will results in eight single digit numbers
 //// 3. Get the sum of the digits
 int sumOfDigits = creditCardNumber.Where((e) => e >= '0' && e <= '9')
 .Reverse()
 .Select((e, i) => ((int)e - 48) * (i % 2 == 0 ? 1 : 2))
 .Sum((e) => e / 10 + e % 10);
 //// If the final sum is divisible by 10, then the credit card number is valid. If it is not divisible by 10, the number is invalid.
 return sumOfDigits % 10 == 0;
}

The original article was modified according to the comments made by Code Project super users.

Download Demo Project

Exclude crystal report embedding when building the ASP.Net web site

0

If you have worked with ASP.Net web applications which include number of crystal reports as part of that, you might have experienced it takes a long time to build the web site. This happens, because by default crystal reports are set to be embedded as a resource.In default your “web.config” displays as follows.

Web config default configuration for crystal report

To resolve this, you can simply modify the embedRptInResource=”false” as follows.

<businessObjects>
    <crystalReports>
        <rptBuildProvider>
            <add embedRptInResource="false"/>
        </rptBuildProvider>
    </crystalReports>
</businessObjects>