Wednesday, November 11, 2015

Best way to secure password using Cryptographic algorithms in C# .NET

Let me explain with some of the common ways of storing passwords in the database with its demerits. By reading this full article you will understand the best way to secure your password  using Cryptographic algorithms in C# .NET.


1. Plain text

Storing password in plain text is the worst way of password management. If the database is compromised by the hacker, with no effort he can reveal all the passwords.

2. Symmetric Key Encryption

One usual way to storing password is using encryption. it's a two-way process. That means the password is encrypted using the secret key when storing and decrypt using the same key for the password authentication.

It's better than storing the password as plain text. But key management is the challenge. Where do you save that key? If it is a database, It won't be difficult for the hacker who got the encrypted password by hacking the database and decrypt it using the same key.

3. Asymmetric Key Encryption

So instead of using symmetric key encryption algorithm. we can use asymmetric key encryption algorithm like RSA where client uses public key to encrypt the password and sends it to the server for storage. When authenticate a private key is used to decrypt the password. That private key should be kept secret. This is also not a great solution as the key management is difficult like the previous way.

4. Hashing

If we use Hashing there won't be any over head of key management. Also no need to decrypt the password back to plain text. As we discussed in my previous article Cryptographic Hashing Algorithm in .NET C#, Hashing is one way operation. Once a data is hashed we cannot reverse and get the original message, It has four important properties,
  • Easy to compute the hash value for any given message
  • Not possible to generate a message from the given hash
  • Not possible to modify a message without changing the hash
  • Not possible to find two different messages with the same hash

Two types of attack is possible on the hashed password. They are,
  1. Brute force attack
  2. Rainbow table attack
Brute force attack

The attacker would try the different combination of passwords hash that is equivalent to the password hash you have stored. Using the latest high performance graphic processor system it is possible to generate billions of random password hash. It only the matter of time to  generate the correct password.

Rainbow table attack

A rainbow table is a listing of all possible plain text permutations of hashed passwords specific to a given hash algorithm. Which is often used for crack the password from the hashed values that we stored in the application database. It can be Giga bytes of size. Once an attacker gains access to a system’s password database, the password cracker compares the rainbow table’s precompiled list of hashes to hashed passwords in the database. The rainbow table relate plaintext possibilities with each of those hashes. Thus attacker could crack the password.

5. Salted Hash

It is common for a web application to store in a database the hash value of a user's password. Without a salt, a successful SQL injection attack may yield easily crackable passwords. Because many users re-use passwords for multiple sites, the use of a salt is an important component of overall web application security


If we append a random value with a hashed password, Which is difficult for the attacker to hack using brute force or rainbow table attack. The random value is called Salt. The Salted hash and the Salt will be stored in the database as the Salt is required when the password authentication.

Salted Hash Sample Code :
using System;
using System.Security.Cryptography;
using System.Text;
static void Main()
{
    const string password = "SampleP455w0rd";
    byte[] salt = GenerateSalt();

    Console.WriteLine("Sample Password : " + password);
    Console.WriteLine("Generated Salt : " + Convert.ToBase64String(salt));
    Console.WriteLine();

    var hashedPassword = HashPasswordWithSalt(Encoding.UTF8.GetBytes(password), salt);

    Console.WriteLine("Salted Hash Password : " + Convert.ToBase64String(hashedPassword));
    Console.WriteLine();
   
    Console.ReadLine();
}
public static byte[] GenerateSalt()
{
    const int saltLength = 32;

    using (var randomNumberGenerator = new RNGCryptoServiceProvider())
    {
        var randomNumber = new byte[saltLength];
        randomNumberGenerator.GetBytes(randomNumber);

        return randomNumber;
    }
}
private static byte[] Combine(byte[] first, byte[] second)
{
    var ret = new byte[first.Length + second.Length];

    Buffer.BlockCopy(first, 0, ret, 0, first.Length);
    Buffer.BlockCopy(second, 0, ret, first.Length, second.Length);

    return ret;
}
public static byte[] HashPasswordWithSalt(byte[] toBeHashed, byte[] salt)
{
    using (var sha256 = SHA256.Create())
    {
        var combinedHash = Combine(toBeHashed, salt);

        return sha256.ComputeHash(combinedHash);
    }
}
Console Output



6. Password Based Key Derivation Function (PBKDF2)

Attackers can use super computers for the brute force attack as it could generate large number of random passwords within a sort period of time. To solve this PBKDF2 is used.


The PBKDF2 expect password input with salt also additionally the number of iteration the password should be hashed. It  makes password cracking much more difficult also increase the time taken to generate the hash value. You can see the delay in below sample code based on the number of iteration value u have passed.

When the standard was written in 2000, the recommended minimum number of iterations was 1000, but the parameter is intended to be increased over time as CPU speeds increase. As of 2005 a Kerberos standard recommended 4096 iterations, Apple iOS 3 used 2000, iOS 4 used 10000, while in 2011 LastPass used 5000 iterations for JavaScript clients and 100000 iterations for server-side hashing.

PBKDF2 Sample Code
using System;
using System.Diagnostics;
using System.Security.Cryptography;
using System.Text;
static void Main()
{
    const string passwordToHash = "SamplePassword";

    HashPassword(passwordToHash, 100);

    HashPassword(passwordToHash, 50000);

    HashPassword(passwordToHash, 500000);

    Console.ReadLine();
}
private static void HashPassword(string passwordToHash, int numberOfRounds)
{
    var sw = new Stopwatch();

    sw.Start();
    var hashedPassword = HashPassword(Encoding.UTF8.GetBytes(passwordToHash), GenerateSalt(), numberOfRounds);
    sw.Stop();

    Console.WriteLine("Password to hash : " + passwordToHash);
    Console.WriteLine("PBKDF2 Hashed Password : " + Convert.ToBase64String(hashedPassword));
    Console.WriteLine("Iterations : " + numberOfRounds);
    Console.WriteLine("Elapsed Time : " + sw.ElapsedMilliseconds + "ms");
    Console.WriteLine();
}
public static byte[] GenerateSalt()
{
    using (var randomNumberGenerator = new RNGCryptoServiceProvider())
    {
        var randomNumber = new byte[32];
        randomNumberGenerator.GetBytes(randomNumber);

    return randomNumber;
    }
}
public static byte[] HashPassword(byte[] toBeHashed, byte[] salt, int numberOfRounds)
{
    using (var rfc2898DeriveBytes = new Rfc2898DeriveBytes(toBeHashed, salt, numberOfRounds))
    {
        return rfc2898DeriveBytes.GetBytes(32);
    }
}
Console Output



Tuesday, October 27, 2015

Steve Jobs explains what Object Oriented Programming is in Rolling Stone interview 1994

Interviewer: Would you explain, in simple terms, exactly what object-oriented software is?


Steve Jobs: Objects are like people. They're living, breathing things that have knowledge inside them about how to do things and have memory inside them so they can remember things. And rather than interacting with them at a very low level, you interact with them at a very high level of abstraction, like we're doing right here.

Here's an example: If I'm your laundry object, you can give me your dirty clothes and send me a message that says, "Can you get my clothes laundered, please." I happen to know where the best laundry place in San Francisco is. And I speak English, and I have dollars in my pockets. So I go out and hail a taxicab and tell the driver to take me to this place in San Francisco. I go get your clothes laundered, I jump back in the cab, I get back here. I give you your clean clothes and say, "Here are your clean clothes."

You have no idea how I did that. You have no knowledge of the laundry place. Maybe you speak French, and you can't even hail a taxi. You can't pay for one, you don't have dollars in your pocket. Yet I knew how to do all of that. And you didn't have to know any of it. All that complexity was hidden inside of me, and we were able to interact at a very high level of abstraction. That's what objects are. They encapsulate complexity, and the interfaces to that complexity are high level.

Monday, October 26, 2015

Project Euler Solution using C#: Problem 29 : Distinct powers

Problem:

Consider all integer combinations of a^b for 2 ≤ a ≤ 5 and 2 ≤ b ≤ 5:

2^2=4, 2^3=8, 2^4=16, 2^5=32
3^2=9, 3^3=27, 3^4=81, 3^5=243
4^2=16, 4^3=64, 4^4=256, 4^5=1024
5^2=25, 5^3=125, 5^4=625, 5^5=3125
If they are then placed in numerical order, with any repeats removed, we get the following sequence of 15 distinct terms:

4, 8, 9, 16, 25, 27, 32, 64, 81, 125, 243, 256, 625, 1024, 3125

How many distinct terms are in the sequence generated by a^b for 2 ≤ a ≤ 100 and 2 ≤ b ≤ 100?

Solution:
static void Main(string[] args)
{
    var aMin = 2;
    var aMax = 100;

    var bMin = 2;
    var bMax = 100;

    List lst = new List();

    for (int a = aMin; a <= aMax; a++)
    {
        for (int b = bMin; b <= bMax; b++)
        {
            lst.Add(Math.Pow(a, b));
        }
    }

    var distinctRslt = lst.Distinct().ToList();
    distinctRslt.Sort();

    Console.WriteLine("Result : " + distinctRslt.Count());
    Console.ReadLine();
}

Output :

Wednesday, October 21, 2015

(Solved) Error: Unable to make the session state request to the session state server

Error:

Unable to make the session state request to the session state server. Please ensure that the ASP.NET State service is started and that the client and server ports are the same.  If the server is on a remote machine, please ensure that it accepts remote requests by checking the value of HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\aspnet_state\Parameters\AllowRemoteConnection.  If the server is on the local machine, and if the before mentioned registry value does not exist or is set to 0, then the state server connection string must use either 'localhost' or '127.0.0.1' as the server name.

Solution:

1. Go to Run command, type services.msc



2. Right click over the ASP.NET State Service and click Start or Restart if it is already Started.




Note:
You could set the service to automatic so that it will work after a reboot.

Thursday, October 15, 2015

Cryptographic Hash-based Message Authentication Code (HMAC) Algorithm in .NET C#

If we combine one way hash functions with secret cryptographic key that's called HMAC. like hash code the HMAC is used to verify the integrity of the code. It is also allow us to verify the authentication of the message. Only the person who has the key can calculate the hash. This HMAC can be used with different hashing methods like MD5 and SHA family.

So the HMAC is used to check both the integrity and authenticity. For example, assume that you are sending a message and hash. Receiver can verify it by comparing with hash he received. However we are not sure weather the message will be delivered to the person to whom you need to send. So using a private key we can secure the message. Using the same key he can recompute the HMAC and compare it with the HMAC you sent. That ensures the authenticity.

The code implementation is same as what we did in MD5 and SHA family samples in my previous post except only one change that we have to pass a private key to the hashing method. The primary key can be generated using another cryptocraphic method called RNGCryptoServiceProvider. That I have explained in my another post Generate Random numbers using RNGCryptoServiceProvider in C#.

HMAC SHA-512 Sample
using System;
using System.Security.Cryptography;
using System.Text;
static void Main()
{
    var key = GenerateKey();

    const string message1 = "The quick brown fox jumps over the lazy dog";
    const string message2 = "The quick brown fox jumps over the lazy dog.";

    Console.WriteLine("Original Message 1 : " + message1);
    Console.WriteLine("Original Message 2 : " + message2);
    Console.WriteLine();

    var hmacMessage = ComputeHmacHash(Encoding.UTF8.GetBytes(message1), key);
    var hmacMessage2 = ComputeHmacHash(Encoding.UTF8.GetBytes(message2), key);

    Console.WriteLine();
    Console.WriteLine("HMAC SHA-512 Hash");
    Console.WriteLine();
    Console.WriteLine("Message 1 hash = " + Convert.ToBase64String(hmacMessage));
    Console.WriteLine("Message 2 hash = " + Convert.ToBase64String(hmacMessage2));
    Console.ReadLine();
}
public static byte[] ComputeHmacHash(byte[] toBeHashed, byte[] key)
{
    using (var hmac = new HMACSHA512(key))
    {
        return hmac.ComputeHash(toBeHashed);
    }
}
public static byte[] GenerateKey()
{
    const int KeySize = 32;

    using (var randomNumberGenerator = new RNGCryptoServiceProvider())
    {
        var randomNumber = new byte[KeySize];
        randomNumberGenerator.GetBytes(randomNumber);

        return randomNumber;
    }
}
Output 

The same way we can implement the HMAC for HMAC MD5, HMAC SHA1, HMAC SHA-256 and HMAC SHA-512 using its corresponding class HMACMD5(key),  HMACSHA1(key) and HMACSHA256(key).

Cryptographic Hashing Algorithm in .NET C#

The idea of hashing is to generate a fixed size string from the give input data. That will be encoded ie, It can not be read. .Net has various hashing algorithms MD5, SHA1, SHA2 and SHA3 are derived from a single class called HashAlgorithm.

Hashing can be used in two different ways. With and without using Secret key. Hashing without secret key is called HMAC (Hash-based Message Authentication Code).

Hashing is one way operation. Once a data is hashed we cannot reverse and get the original message. But encryption is two way. Once a messages is encrypted using a key we can reverese it using the same key. This hashing technique is widely used to check the data integrity. Usefull to check the transfered data is corrupted or not.



From the above image, Person 1 sends a message and its hash to Person 2. Person 2 receives both and compute the hash for the received message and compare with the received hash. If both are equal means the file is not corrupted or not attacked by the viruses. So we can confirm that we got the complete file bytes.

Even a small change in the message will result in a mostly different hash, due to the avalanche effect. For example, adding a period to the end of the sentence changes some bits in the hash.

In the forthcoming samples I have used two messages to hash. Both having just slight difference that one doesn't have full stop (dot) at the end. But still the generated hash will be completely new one.

Two types of hashing method is used mostly. They are,
  1. MD5
  2. SHA (Secure Hash Algorithm)
MD5

MD5 was designed by Ronald Rivest in 1991. It produces a 160-bit hash value. First flaw found in 1996. So the recommendation was to move over to the Secure Hash Family (SHA).

SHA

Secure Hash Algorithm is published by National Institute of Standards and Technology (NIST) in USA. It has three different varients.
  1. SHA1
  2. SHA2
  3. SHA3
SHA-1

A 160-bit hash function which resembles the earlier MD5 algorithm. This was designed by the National Security Agency (NSA) to be part of the Digital Signature Algorithm. Cryptographic weaknesses were discovered in SHA-1, and the standard was no longer approved for most cryptographic uses after 2010.

SHA-2

It has two different varients.
  1. SHA 256
  2. SHA 512
SHA 256 produces a 256-bit hash computed with 32-bit words and the SHA 512 produces a 512-bit hash computed with 64-bit words. This is also designed by NSA. Both are works the same way than SHA1 but are stronger and generate a longer hash based on its bits.

SHA-3

It was designed after a public competition among non-NSA designers and released by NIST on 2015. SHA-3 is not meant to replace SHA-2, as no significant attack on SHA-2 has been demonstrated. SHA-3 is not commonly supported in .NET directly but 3rd party implementations are available. Implementation of SHA 256 and SHA 512 is straight forward in .NET as the SHA class is identical to MD5.

SHA-512 Sample
using System;
using System.Security.Cryptography;
static void Main()
{
    const string message1 = "The quick brown fox jumps over the lazy dog";
    const string message2 = "The quick brown fox jumps over the lazy dog.";

    Console.WriteLine("Original Message 1 : " + message1);
    Console.WriteLine("Original Message 2 : " + message2);
    Console.WriteLine();

    var md5HashedMessage = ComputeHashCode(Encoding.UTF8.GetBytes(message1));
    var md5HashedMessage2 = ComputeHashCode(Encoding.UTF8.GetBytes(message2));

    Console.WriteLine();
    Console.WriteLine("SHA-512 Hash");
    Console.WriteLine();
    Console.WriteLine("Hashed Message 1 :  " + Convert.ToBase64String(md5HashedMessage));
    Console.WriteLine("Hashed Message 2 :  " + Convert.ToBase64String(md5HashedMessage2));
    Console.ReadLine();
}
public static byte[] ComputeHashCode(byte[] toBeHashed)
{
    using (var md5 = SHA512.Create())
    {
        return md5.ComputeHash(toBeHashed);
    }
}
Output

The same way we can generate the hash of MD5, SHA1 and SHA-256 just by replacing its corresponding methods MD5.Create()SHA1.Create() and SHA256.Create() in the above code sample.

HMAC

Combining one way Hash function with secret Cryptographic key is called HMAC. I have explained it with sample code in my another post Cryptographic Hash-based Message Authentication Code (HMAC) in .NET

Hashing Advantages
  • Easy to compute the hash value for any given message
  • Not possible to generate a message from the given hash
  • Not possible to modify a message without changing the hash
  • Not possible to find two different messages with the same hash
Ref: Wikipedia, Pluralsight

Thursday, October 8, 2015

(Solved) Error: Memory gates checking failed because the free memory (201310208 bytes) is less than 5% of total memory

Error:
Memory gates checking failed because the free memory (201310208 bytes) is less than 5% of total memory. As a result, the service will not be available for incoming requests. To resolve this, either reduce the load on the machine or adjust the value of minFreeMemoryPercentageToActivateService on the serviceHostingEnvironment config element.

Solution:
To solve the above error, Add or update the below line in the Web.Config file.
<system.serviceModel>
    <serviceHostingEnvironment minFreeMemoryPercentageToActivateService="0"/>
</system.serviceModel>
Read more about serviceHostingEnvironment
https://msdn.microsoft.com/en-us/library/ms731336(v=vs.110).aspx

Friday, September 18, 2015

Build Where Clause Dynamically Using Linq PredicateBuilder to filter data from DataTable C#

To filter some data from a DataTable based on two or more condition is not possible using the below code. As the Linq where condition not allowed more than one condition.
var filtered = dataTable.Where(x => x["Name"].Equals("Venkat") && x => x["Age"].Equals("26")).ToList()

So using the PredicateBuilder we can build where clause dynamically. Check the below code.,

As you can see, the below code is constructing the where clause dynamically. You can pass multiple column name and value as filter condition dynamically.
var predicate = PredicateBuilder.True();
predicate = predicate.And(x => x["Name"].Equals("Venkat"));
predicate = predicate.And(x => x["Age"].Equals("26"));
predicate.Compile();
var filtered = dataTable.Where(predicate).ToList();

public static class PredicateBuilder
{
    public static Expression<Func<T, bool>> True<T>() 
    { 
        return f => true; 
    }

    public static Expression<Func<T, bool>> False<T>() 
    { 
        return f => false; 
    }

    public static Expression<Func<T, bool>> Or<T>(this Expression<Func<T, bool>> expr1, Expression<Func<T, bool>> expr2)
    {
        var invokedExpr = Expression.Invoke(expr2, expr1.Parameters.Cast<Expression>());
        return Expression.Lambda<Func<T, bool>> (Expression.OrElse(expr1.Body, invokedExpr), expr1.Parameters);
    }

    public static Expression<Func<T, bool>> And<T>(this Expression<Func<T, bool>> expr1, Expression<Func<T, bool>> expr2)
    {
        var invokedExpr = Expression.Invoke(expr2, expr1.Parameters.Cast<Expression>());
        return Expression.Lambda<Func<T, bool>> (Expression.AndAlso(expr1.Body, invokedExpr), expr1.Parameters);
    }
}

Friday, September 11, 2015

How to convert CSV to EXCEL using C#

It is possible using the EPPLUS .net library. It is free and available in epplus.codeplex.com. You have to pass both CSV and the EXCEL file path where it should be saved. The ExcelTextFormat class has more conditions, based on that it reads the CSV file. Check the below console application sample code that accomplish that task.
static void Main(string[] args)
{
 string csvFilePath = @"D:\sample.csv";
 string excelFilePath = @"D:\sample.xls";

 string worksheetsName = "TEST";
 bool firstRowIsHeader = false;

 var excelTextFormat = new ExcelTextFormat();
 excelTextFormat.Delimiter = ',';
 excelTextFormat.EOL = "\r";

 var excelFileInfo = new FileInfo(excelFilePath);
 var csvFileInfo = new FileInfo(csvFilePath);

 using (ExcelPackage package = new ExcelPackage(excelFileInfo))
 {
  ExcelWorksheet worksheet = package.Workbook.Worksheets.Add(worksheetsName);
  worksheet.Cells["A1"].LoadFromText(csvFileInfo, excelTextFormat, OfficeOpenXml.Table.TableStyles.Medium25, firstRowIsHeader);
  package.Save();
 }

 Console.WriteLine("Converted!");
 Console.ReadLine();
}
EPPLUS Setup

The EPPLUS can be installed through Visual Studio Nuget package also. Follow the below steps to install it.

  • Right click the Visual Studio solution and select "Manage NuGet Packages for Solution".
  • And in the window search for EPPlus. 
  • From the searched list select EPPlus and click install.

Wednesday, September 9, 2015

How to use Sass/Scss in Visual Studio

Visual Studio update 2 has the native Scss support. So we can write Scss code but, to compile it, we need Sass compilers. Those are available as Visual Studio extensions.

There are many extensions available in the internet. You can use Web Workbench extension as it is very simple to use. Using Web Workbench extension in visual studio, files are compiled automatically to CSS with the same name whenever you save it.

So you should refer the compiled CSS files to the project to make the CSS work.

Folow the below steps to install the Web Workbench extension in Visual Studio,
  • Download the extension from here
  • Double click to Install it
  • Restart the Visual Studio
  • You will see a new MINDSCAPE menu in Visual Studio.
Reference: http://www.mindscapehq.com/products/web-workbench

Sass - CSS Stylesheet Language

Sass (Syntactically Awesome Style Sheets) is an extension of CSS that adds power and elegance to the basic language. It is an open source project that is coded in Ruby. It was created in order to simplify CSS development. It adds a feature set to your stylesheet markup that makes writing styles more organized way.



When I work with Sass the file extensions were scss. So what is Scss in Sass?. Well, when Sass first came out, the main syntax was different from CSS. It looked a lot like Haml. So in version 3 Sass changed it’s main syntax to .scss to make it look like CSS.

What is the use of Sass?

It is important to follow the coding standard in our application. Not only in server side code and also in client side code. So Scss makes writing maintainable CSS easier. You can get more done, in less code, more readable, in less time.

1. Variables

Variables in Sass are preceded with the $ symbol.

Types of variables:
  • numbers - 1.2, 13, 10px
  • strings - "foo", 'bar', baz
  • colors - blue, #04a3f9, rgba(255, 0, 0, 0.5)
  • booleans - true, false
  • null - null,
  • lists - 20px 5px 0 10px, Helvetica, Arial
  • maps - (key1: value1, key2: value2)
$baseColor: #eeffcc;

body {
    background: $baseColor;
}
Variable has scope. If it is declared within the braces it can not be accessed outside. But using !global flag we can make the variable globally accessible.
$baseColor: #ccc !global;
Variable might be used in multiple places. In any place if values is not assaigned to it, We can set a default value for a variable using !default flag.

2. Math

It's supports mathematical expressions.

Types of math operators:
  • + Addition
  • – Subtraction
  • / Division
  • * Multiplication
  • % Modulo
  • == Equality
  • != Inequality
$container-width: 100%;

.container {
    width: $container-width / 4;
}
3. Functions

It has some built in functions. Click here

4. Nesting

Using this feature we can write single class by nesting the common class together instead of writing multiple classes separately.
.container {
    width: 100%;
}

.container h1 {
    color: red;
}

.container {
    width: 100%;
    h1 {
        color: red;
    }
}
In some situation we have to refer the parent. For example we cannot just write :hover inside the parent a class. We have to refer the parent with the & symbol.
a {
    color: blue;
        &:hover {
        text-decoration: underline;
    }

    &:visited {
    color: purple;
    } }
5. Imports

Imports allow you to break your styles into separate files and use them into one another. @import directive used to import a scss files.
@import "grids.scss";
@import "grids";
Sass compilers also include a concept called “partials”. If you prefix a .sass or .scss file with an underscore, it will not get compiled to CSS. This is helpful if your file only exists to get imported into a master style.scss and not explicitly compiled.

6. Extends & Placeholders

Using @extend keyword we can inherit already existing styles.
.input {
    border-radius: 3px;
    border: 4px solid #ddd;
    color: #555;
    font-size: 17px;
    padding: 10px 20px;
    display: inline-block;
    outline: 0;
}

.error-input {
    @extend .input;
    border:4px solid #e74c3c;
}
7. Mixin

Mixins allow you to define styles that can be re-used throughout the stylesheet. Can be re-used using @include directive.
@mixin large-text {
    font: {
        family: Arial;
        size: 20px;
        weight: bold;
    }
    color: #ff0000;
}

.page-title {
    @include large-text;
    padding: 4px;
    margin-top: 10px;
}
Its also accept parameters.
@mixin style-border($color, $width) {
    border: {
        color: $color;
        width: $width;
    }
}

p { @include style-border(blue, 1in); }
8. Function Directives

It is possible to define your own functions in sass and use them in any value or script context.
$grid-width: 40px;
$gutter-width: 10px;

@function grid-width($n) {
    @return $n * $grid-width + ($n - 1) * $gutter-width;
}

#sidebar { width: grid-width(5); }
We can also pass named parameters like below,
#sidebar { width: grid-width($n: 5); }
How to use Sass in Visual Studio

Check out my another post to know How to use Sass in Visual Studio. Click here.

Monday, September 7, 2015

Sample ExtJs Column Chart

In this column chart, I have used the same model, store and require section that I used in my previous sample Sample ExtJS Line Chart. So check it out before continue this sample.

Chart Component
 
Ext.create('Ext.chart.Chart', {
   renderTo: Ext.getBody(),
   width: 400,
   height: 300,
   theme: 'Green',
   store: store,
   animate: true
    axes: [
        {
            title: 'Score',
            type: 'Numeric',
            position: 'left',
            fields: ['score'],
            minimum: 0,
            maximum: 400
        },
        {
            title: 'Over',
            type: 'Numeric',
            position: 'bottom',
            fields: ['over']
        }
    ],
    
      series: [
        {
            type: 'column',
            axis: 'left',
            xField: 'over',
            yField: 'score'
        }
    ]
});
Result
Demo Click here to view in Jsfiddle

Sample ExtJS Line Chart

In this line chart sample I have used two fields 'over' and 'score' in the model named 'CricketScore'. Added some default scores in the store. Both values are numeric. The store has been assigned to the chart store property. The two fields are pointed to the position left and bottom in the axes array section in the chart. In the series array section I have mentioned the chart type and the x, y fields.

In the fiddle demo, I have included ExtJS 4.2.0 in the Frameworks and Extension section and in the External resources section added the following CSS Url,
http://cdn.sencha.com/ext/gpl/4.2.0/resources/css/ext-all.css
Namespace
 
Ext.require([
    'Ext.chart.Chart'
]);
Model
Ext.define('CricketScore', {
    extend: 'Ext.data.Model',
    fields: ['over', 'score']
});
Store
var store = Ext.create('Ext.data.Store', {
    model: 'CricketScore',
    data: [
        { over: 5, score: 35 },
        { over: 10, score: 75 },
        { over: 15, score: 110 },
        { over: 20, score: 135 },
        { over: 25, score: 171 },
        { over: 30, score: 200 },
        { over: 35, score: 225 },
        { over: 40, score: 240 },
        { over: 45, score: 285 },
        { over: 50, score: 345 },
    ]
});
Chart Component
Ext.create('Ext.chart.Chart', {
   renderTo: Ext.getBody(),
   width: 400,
   height: 300,
   theme: 'Red',
   store: store,
   axes: [
        {
            title: 'Over',
            type: 'Numeric',
            position: 'left',
            fields: ['over'],
            minimum: 1,
            maximum: 50
        },
        {
            title: 'Score',
            type: 'Numeric',
            position: 'bottom',
            fields: ['score']
        }
    ],
    
      series: [
        {
            type: 'line',
            xField: 'score',
            yField: 'over'
        }
    ]
});
Result
Demo Click here to view in Jsfiddle

Friday, September 4, 2015

How to find a control in ASP.NET page recursively

Here is a sample code to find a asp.net control. You have to pass the parent control within which you need to search and the id of control to be searched as params.
public static Control FindControlRecursive(Control parent, string id)
{
    // If the control we're looking for is parent, return it
    if (parent.ID == id) return parent;

    // Else search through children
    foreach (Control control in parent.Controls)
    {
        Control found = FindControlRecursive(control, id);
        if (found != null) return found;
    }

    // No control with id is found
    return null;
}

JSLint - JavaScript code quality tool

JSLint is a static code analysis tool used in software development for checking JavaScript source code complies with coding rules. It is provided primarily as an online tool http://www.jslint.com/. It is also available as a Visual Studio extension JSLint.NET for the .Net developers. It can also check HTML and CSS code qualities.

I found very useful as I am using it in my current ExtJS project. Follow the below simple steps to make it available in your Visual Studio
1. Download the Visual Studio extension by clicking here,
2. Double click and Install the downloaded extension
3. Restart the Visual Studio

It will find your JavaScript coding standard errors and display it as Warnings whenever building your .net web application. You can also manually run it by just right click a JavaScript file and clikck JS Lint. Some additional settings can be configured in the menu Tools -> JS Lint Optons

Check the below attached image to see how it actually displays errors in Visual Studio.


Thursday, September 3, 2015

15 Cool New Features in C# 6.0

The first release of the C# language was in 2002 and then in 2005 version 2 released. It gave us Generics. In 2007, the C# language gave us Linq features, including lambda expressions, implicit typing, a query syntax and var keyword. In 2010, the release of version 4 introduced the dynamic keyword and the dynamic language runtime. And then 2012 brought us version 5 of the language. It gave us the async and await keywords, which make async code much easier to read and write, and in today's world where the async programming model is used nearly everywhere from the server to the client. Compared to the previous release, the language features introduced in this version might seem underwhelming. And partly that's because C# is now over 13 years old; it's a somewhat mature language has major features that have been added over the years. They give us the ability to write less code than we had to write before.



Here is the 15 cool new features in C# 6.0 According to Roslyn some features are planned and might be available in the future.

1. Auto-Property Initializers

In early version of c# if we want to set a default value for a property in a class, we do this in the constructor. In C# 6.0 using Auto-property initializers we can assign a default value for a property as part of the property declaration itself.

// Old way
class Program
{
    public Program()
    {
        MyProperty = 10;
    }

    public int MyProperty { get; set; }
}

// New way
class Program
{
    public int MyProperty { get; set; } = 10
}

2. Using static

With static members you don't need an instance of an object to invoke a method, you just use the typename, a dot, a static method name, and apply parentheses and parameters. This feature allows us to access the static methods inside a class directly without speifying its class name. Usually we use Convert.ToInt32 to convert a value to integer. But using this feature we can just use ToInt32 to convert.

// Old way
namespace TestApp
{
    class Program
    {
        static void Main(string[] args)
        {
            var value = Convert.ToInt32("2015");
        }
    }
}

// New way
using static Convert;

namespace TestApp
{
    class Program
    {
        static void Main(string[] args)
        {
            var value = ToInt32("2015");
        }
    }
}

// Some more samples,
using static System.Console; 
using static System.Math;

class Program 
{ 
    static void Main() 
    { 
        WriteLine(Sqrt(25)); 
    } 
}

3. Dictionary Initializers

Ever since C# version 3 came around, we've had the ability to initialize collections like lists and dictionaries using the key value pairs are surrounded with curly braces. With C# 6.0 we can achieve the same result, using key value inside of square brackets and a sign of value using an equal sign.

// Old way
Dictionary dict = new Dictionary<int, string>
{
    {1, "Apple" },
    {2, "Microsoft" },
    {3, "IBM" }
};

// New way
Dictionary dict = new Dictionary<int, string>
{
    [1] = "Apple",
    [2] = "Microsoft",
    [3] = "IBM" 
};

4. Getter-only auto-properties
When we use auto implemented properties in old vesion of c#, we must provide both get and set. If you want the property value should not be set, you can use the private accessor on the setter, With C# 6.0, you can now omit the set accessor to achieve true readonly auto implemented properties:

// Old way
public int MyProperty { get; private set; }

// New way
public int MyProperty { get; }

5. Null-conditional operators (?.)

This is one of the cool feature in c# 6.0. Usually we use if condition before using it to execution. But using this feature we can check the value is null or not in a single line and proceed the execution if it is not null. It help us to avoid the NullReferenceException.

// Old way
public string Truncate(string value, int length)
{
    string result = value;
    if (value != null)
    {
        result = value.Substring(0, value.Length - 1);
    }

    return result;
}

// New way
public string Truncate(string value, int length)
{          
    return value?.Substring(0, value.Length - 1);
}

Some more samples,
int? length = customers?.Length; // null if customers is null
Customer first = customers?[0]; // null if customers is null 
int length = customers?.Length ?? 0; // 0 if customers is null

6. await in catch and finally block

In c# 6.0 the await keyword can be used inside catch or finally block. Usually we would write log when any exception occured inside catch block itself. In those times we no need to wait for that execution to be completed before going to next line of execution. So using the await keyword those execution will be asynchronous.

try
{

}
catch (Exception)
{
    await LogManager.Write(ex);
}
finally
{
    await LogManager.Write("Done");
}

7. Declaration expressions

Using this feature we can declare local variable in an expression itself instead of declaring globally. But the scope of that variable will be inside the loop.

// Old way
int parsed;
if (!int.TryParse("12345", out parsed))
{ 
}

// New way
if (!int.TryParse("12345", out int parsed))
{
}

8. Primary Constructor

Using this feature the property values can be initialized directly with the help of another new feature Auto-Property Initializers that we have seen in this post, without using default constructor and writing much of code to it. When using a primary constructor all other constructors must call the primary constructor using :this().

// Old way
public class StoredProcedureInfo
{

    private StoredProcedureInfo(string connectionName, string schema, string procedureName)
    {
        this.ConnectionName = connectionName;
        this.Schema = schema;
        this.ProcedureName = procedureName;
    }

    public string ConnectionName { get; set; };
    public string Schema { get; set; };
    public string ProcedureName { get; set; };
}

// New way
private class StoredProcedureInfo(string connectionName, string schema, string procedureName)
{
    public string ConnectionName { get; set; } = connectionName;
    public string Schema { get; set; } = schema;
    public string ProcedureName { get; set; } = procedureName;
}

9. Exception filters

This feature allow us to specify a condition on a catch block. Based on that condition the catch block will be executed.

try
{
}
catch (Exception ex) if (UserPermission == Permission.Administrator)
{
}
catch (Exception ex) if (UserPermission == Permission.Requester)
{
} 

10. Expression-bodied function

Expression-bodied function members allow methods, properties, operators and other function members to have bodies as lambda like expressions instead of statement blocks. It helps reducing lines of codes.

// Old way
public int Multiply(int a, int b)
{
    return a * b;
}

// New way
public int Multiply(int a, int b) = > a * b;

// Old way
public int WriteLog(string log)
{
    LogManager.Write(log);
}

// New way
public int WriteLog(string log) => LogManager.Write(log);

// Some more samples,
public double Distance => Math.Sqrt(X + Y); // property
public void Execute() => Math.Sqrt(25); // method

11. String Interpolation

This feature is one of an addition to the string format technique in c#. So far we used + sign or string.format to format a string. But in this feature we can directly use the value to be concatinate inside the string itself using \{} symbol. Any condition can be used inside the braces.

// Old way
public string FormatString(int value)
{
    return "Total # of tickets: "+ value + " tickets";
}

public string FormatString(int value)
{
    return string.Format("Total # of tickets: {0} tickets", value);
}

// New way
public string FormatString(int value)
{
    return "Total # of tickets: \{(value <= 1 ? "ticket" : "tickts")}";
}

// Some more samples,
var s = "\{person.Name} is \{person .Age} year\{(person.Age == 1 ? "" : "s")} old"; 

12. nameof

Used to obtain the simple (unqualified) string name of a variable, type, or member. When reporting errors in code instead of hard code it.

// Old way
public void SaveData()
{
    try
    {
    }
    catch (Exception ex)
    {
        this.WriteLog("SaveData", ex);
    }
}

// New way
public void SaveData()
{
    try
    {
    }
    catch (Exception ex)
    {
        this.WriteLog(nameof(SaveData), ex);
    }
}

13. Literals and Separators

When initializing fields and properties and variables with numerical values, we have a new binary literal syntax we can use, 0b. We can write binary values with a 0b prefix and then use just ones and zeros to specify which bits are on and off. This can lead to more readable code.
public byte code = 0b01011011010;
Another feature we have for numeric literals will be the ability to use an underscore as a separator. It's much easier to look at a value and see it as in the billions or the millions when we have an underscore separating the digits instead of just a long string of numbers. The C# compiler doesn't actually care where you use the separator, the separator can appear anywhere after the first leading digit.

public long value = 1_000_000_000;

14. Event Initializer

C# 6.0 will now allow us to wire up event handlers as part of an object initialization syntax. Before a version 6 of the language, this event wire up syntax would be illegal. I just always have to remember to use the += operator to wire up an event. Trying to assign directly to an event using an equal sign is still illegal. Events need to encapsulate the delegates that they hold inside, so from the outside we can only use += and -= to add and remove delegates respectively. In an initializer you'd want to be using += to add delegates and listen for an event to fire.

public class Person
{
    private int _age;
    public int Age
    {
        get
        {
            return _age;
        }
        set
        {
            _age = value;
             OnAgeChanged(EventArgs.Empty);
        }
    }

    public string Name { get; set; }

    public event EventHandler AgeChanged;

    protected virtual void OnAgeChanged(EventArgs e)
    {
        if (AgeChanged != null)
        {
            AgeChanged(this, e);
        }
    }
}

// Old way
class Program
{
    static void Main(string[] args)
    {
        var pers = new Person()
        {
            Name = "Venkat"
        };
        pers.AgeChanged += pers_AgeChanged;
 }

    static void pers_AgeChanged(object sender, EventArgs e)
    {
        Console.WriteLine("Changed");
    }
}

// New way
class Program
{
    static void Main(string[] args)
    {
        var pers = new Person()
        {
            Name = "Venkat",
             AgeChanged += pers_AgeChanged
        };
    }

    static void pers_AgeChanged(object sender, EventArgs e)
    {
        Console.WriteLine("Changed");
    }
}
15. params and Ienumerable

In C# version 6.0 we can use the params keyword with IEnumerable instead of using an array.

// Old way
void Foo(params int[] a) 
{
}

Foo(10,2,4,22);

// New way
void Foo(params IEnumerable<int> a) 
{
}

Foo(10,2,4,22);

Happy Coding!

Trello - Free Project Management Tool

Trello


Trello is a free web-based lighter-weight project management tool. It makes the project well organized. You can crate separate boards for your each project. A Trello board is a list of lists, filled with cards, used by you and your team. Its UI looks so cool, It makes project collaboration simple and kind of enjoyable. It has everything you need to organize projects of any size and any kind. You can create as many boards, cards, and organizations as you like and add as many people as you want. You can choose to make any number of boards or organizations private or public. Bellow image shows how a board look like. You can drag and drop cards from one list to another based on the task completion.



You can invite as many people to your board as you need, all for free. Drag and drop people to cards to divvy up tasks. Everyone sees the same board and the whole picture all at once. You can start a discussion with comments and attachments. Mention any member in a comment using @ symbol like what we using in facebook, to make sure they get notified.

You can create cards and comment via email. Trello uploads the attachments you send along, too. Also, when you get notifications via email, you can reply via email without opening Trello.

Open a card and you can add comments, upload file attachments, create checklists, add labels and due dates, and more. Add files by uploading them from your computer, Google Drive, Dropbox, Box, and OneDrive.

Whenever something important happens, you know instantly with Trello’s notification system. You’ll get notifications wherever you are: inside the app, via email, desktop notifications via the browser, or via mobile push notifications. Notifications stay in sync across all your devices. Notifications stay in sync across all your devices.

Your project may have hundreds of cards. You can easily search any card with the search and filter functionality. Search is incredible fast and powerful, with sophisticated operators that help you narrow your search. It will list out all the card related to your search with the link to the particular card. You can click there to access the card directly. Search operators refine your search to help you find specific cards and create highly tailored lists. Trello will suggest operators for you as you type, but here’s a full list to keep in mind.
  • @name - Returns cards assigned to a member
  • #label - Returns labeled cards
  • board:id - Returns cards within a specific board
  • list:name - Returns cards within the list named “name”
  • has:attachments - Returns cards with attachments. has:description, has:cover, has:members, and has:stickers also work
  • due:day -Returns cards due within 24 hours. due:week, due:month, and due:overdue also work
  • created:day -Returns cards created in the last 24 hours. created:week and created:month also work
  • edited:day - Returns cards edited in the last 24 hours. edited:week and edited:month also work
  • description:, checklist:, comment:, and name: - Returns cards matching the text of card descriptions, checklists, comments, or names
  • is:open - returns open cards. is: archived returns archived cards
  • is:starred - Only include cards on starred boards.

Trello has apps for iPhone, iPad, Android phones, tablets, and watches, Kindle Fire Tablets, and Windows 8. Useful to keep track of and get notified anything Important using the apps. Also you can create cards in the app itself no matter wherever you are. You no need to always use pc or laptop to manage your projects.

The data is private and secure. You have full control over who sees our boards. All data is sent over a secure, SSL/HTTPS connection, the same encryption technology used by banks. Trello keep encrypted, off-site backups of your data in case of disasters

Trello provides a simple RESTful web API to use Trello in your own app, plug-in, or extension where each type of resource (e.g. a card, a board, or a member) has a URI that you can interact with.
For example, if you’d like to use the API to get information about the Trello Development Board you’d use the following URI:

https://api.trello.com/1/boards/4d5ea62fd76aa1136000000c
All API requests go to https://api.trello.com
The /1 part of the URI is the API version
The /boards part means that we’re addressing Trello’s collection of boards
The /4d5ea62fd76aa1136000000c part is the id of the board that we want to interact with
to know more https://trello.com/docs/index.html

Here is a collection of boards can be used in both your personal and work life management. All of these boards can be copied and used as a jumping off point for projects of your own.

Link to access those board : https://trello.com/inspiringboards

Reference: https://trello.com

Wednesday, September 2, 2015

Sample ExtJS Grid

In the fiddle demo, I have included ExtJS 5.1.0 in the Frameworks and Extension section and in the External resources section added the following CSS Url,
http://cdn.sencha.com/ext/gpl/4.2.0/resources/css/ext-all.css 
Model
    Ext.define('User', {
    extend: 'Ext.data.Model',
    fields: [
        { name: 'name', type: 'string' },
        { name: 'email', type: 'string' },
        { name: 'phone', type: 'string' },
        { name: 'Married', type: 'boolean', defaultValue: false }
    ]
});
Store
var userStore = Ext.create('Ext.data.Store', {
 model: 'User',
 data: [
    { name: 'Lisa', email: 'lisa@simpsons.com',
        phone: '555-111-1224', Married: true },
    { name: 'Bart', email: 'bart@simpsons.com',
        phone: '555-222-1234', Married: true },
    { name: 'Homer', email: 'homer@simpsons.com',
        phone: '555-222-1244', Married: false },
    { name: 'Marge', email: 'marge@simpsons.com',
        phone: '555-222-1254', Married: false }
 ]
});
Grid Component
Ext.create('Ext.grid.Panel', {
 renderTo: document.body,
 store: userStore,
 width: 400,
 height: 200,
 title: 'Application Users',
 columns: [
        {
         text: 'Name',
         width: 100,
         sortable: false,
         hideable: false,
         dataIndex: 'name'
        },
        {
         text: 'Email Address',
         width: 150,
         dataIndex: 'email',
         hidden: true
        },
        {
         text: 'Phone Number',
         flex: 1,
         dataIndex: 'phone'
        },
        {
         xtype: 'booleancolumn',
         text: 'Boolean Field',
         flex: 1,
         dataIndex: 'Married'
        }
 ]
});
Result
Demo Click here to view in Jsfiddle

Wednesday, August 19, 2015

(Solved) Error: 500 - Internal server error

Error: 500 - Internal server error. There is a problem with the resource you are looking for, and it cannot be displayed.

Of course the above line makes no sense. We should return the detailed error to fix it.

To display the detailed error follow the below steps,
  • In Internet Information Services (IIS) Manager select your published site
  • In the right side windows double click the "Error Pages" icon
  • A list of errors will be displayed.
  • Right click and choose the "Edit Feature Setting" on the error status code "500"
  • Select the "Detailed Error" radio button
  • Click Ok
  • Run the application again. You will get the detailed error.


Monday, August 17, 2015

(Solved) Error: HTTP Error 401.3 - Unauthorized

HTTP Error 401.3 - Unauthorized
You do not have permission to view this directory or page because of the access control list (ACL) configuration or encryption settings for this resource on the Web server.
Solution:

In IIS,

  • Right Click the  published site -> Edit Permission
  • A dialog will open
  • In the security tab, "Group or user names" section check IUSER is there.
  • If not, click edit button below that section
  • Click the Add button in the dialog
  • Click Advanced button in the dialog
  • Click Find Now button in the dialog
  • In the Search results section select IUSER and click ok.
  • Now choose IUSER and give all the permission by clicking the check box's.

Monday, July 6, 2015

Generate Random numbers using RNGCryptoServiceProvider in C#

Random numbers used for creating encryption keys and for hashing. Good random numbers are important in Cryptography as it deals with security. The .NET Framework has two ways to generating random values.
  1. System.Random 
  2. System.Security.Cryptography.RNGCryptoServiceProvider
System.Random:
System.Random is not good enough for cryptographic purposes. Microsoft recommends creating one instance of System.Random to generate numbers for your application. Also it's not thread safe.

System.Security.Cryptography.RNGCryptoServiceProvider:
The RNGCryptoServiceProvider is used as cryptographic random number generators as it can not be predict. It is a more secure way to generate random numbers.

The following Console application sample generates 10 random values.
using System;
using System.Security.Cryptography;
static void Main()
{
    for (var i = 0; i < 10; i++)
    {
        int keySize = 32;
        var randomValueByte = GenerateRandomValue(keySize);
        Console.WriteLine(Convert.ToBase64String(randomValueByte));
    }

    Console.ReadLine();
}

public static byte[] GenerateRandomValue(int keySize )
{
    var randomValue = new byte[keySize];
    using (var randomValueGenerator = new RNGCryptoServiceProvider())
    {
        randomValueGenerator.GetBytes(randomValue);
    }
    return randomValue;
}
Output:
Check my another article to learn Cryptographic Hashing Algorithm in .Net.

Wednesday, July 1, 2015

Get invalid fileds/components list from ExtJS form when the form.isValid() returns false

To list the invalid fileds/components from ExtJS form when the form is inValid (form.isValid() == false), use the below script,
var formPanel = this.down('form');
var form = formPanel.getForm();
var invalidFields = form.query("field{isValid()==false}");
So the variable invalidFields will hold the invalid fileds/components list.

(Solved) SQL Server Error: The subscription(s) have been marked inactive and must be reinitialized. NoSync subscriptions will need to be dropped and recreated.

Solution:

1. Run the below query to check the status of the subscription
use distribution
go
select * From distribution..MSsubscriptions
2. Note down the publisher_id, publisher_db, publication_id, subscriber_id, subscriber_db if the status is 0

3. Then update the status by runing the below query, apply the where condition value properly that you have noted in the previous step.
use distribution
go
if exists (select * from distribution..MSsubscriptions where status = 0)
begin
    UPDATE distribution..MSsubscriptions
    SET STATUS = 2
    WHERE publisher_id = 0
    AND publisher_db = 'Publisher_Db'
    AND publication_id = 16
    AND subscriber_id = 0
    AND subscriber_db ='Subscriber_Db'
end
 else
begin
 print 'All the subscription is Active'
end
4. Check the replication monitor for any issues.

Monday, June 29, 2015

Adding 'meta' tag in ASP.NET to ensure browser compatibility

Meta tag is very useful to solve most of the browser compatibility issues. If its is html, we need to add it in each page. But in ASP.NET we can straight away add it in Web.config file that will be applied to all the pages. Here is how,

Just add the below config in ASP.NET Web.config file.
<system.webServer>
 <httpProtocol>
  <customHeaders>
   <clear/>
   <add name="X-UA-Compatible" value="IE=9; IE=8; IE=7; IE=EDGE"/>
  </customHeaders>
 </httpProtocol>
</system.webServer>

Below is some of the rendering modes we can use,

ValueRendering mode
IE=9Use the Windows Internet Explorer 9 standards rendering mode
IE=8Use the Internet Explorer 8 standards rendering mode
IE=7Use the Windows Internet Explorer 7 standards rendering mode
IE=5Use the Microsoft Internet Explorer 5 standards rendering mode

Thursday, June 25, 2015

(Solved) SQL Server Error: This database is not enabled for publication.

To enable a database for replication,
  1. On the Publication Databases page of the Publisher Properties [Publisher] - dialog box, select the Transactional and/or Merge check box for each database you want to replicate. 
  2. Select Transactional to enable the database for snapshot replication. 
  3. Click OK.

(Solved) SQL Server Error: Cannot drop the database because it is being used for replication.

Solution:

Drop the replication in the corresponding database using the below Stored Procedure query. Then delete the Database.
sp_removedbreplication 'YOUR_DATABASE_NAME'

Wednesday, May 13, 2015

Sample C# code to Generate linear Y axis value for a chart from the given amount.

Below is a sample C# code to Generate linear Y axis value for a chart from the given amount. You wil get the lower bound of the y axis value when you call the CalculateLowerBound method. That will be added itself based on the barCount in a loop to get the linear y axis values.
public List GenerateAxis()
{
 int barCount = 5;
 double amount = 10000;
 double money = CalculateLowerBound(amount, barCount);

 var axisVal = new List();

 double valX = 0;
 for (int i = 1; i <= barCount; i++)
 {
  valX += money;
  axisVal.Add(valX);
 }

 return axisVal;
}

public double CalculateLowerBound(double range, int barCount)
{
 double unroundedTickSize = range / (barCount);
 double x = Math.Ceiling(Math.Log10(unroundedTickSize) - 1);
 double pow10x = Math.Pow(10, x);
 return Math.Ceiling(unroundedTickSize / pow10x) * pow10x;
}

Sample C# code to shorten amount from 1 Trillion to 1T, 1 Billion to 1 B, 1 Million to 1M and 1 Thousand to 1K.

The following code can be used to shorten a amount from 1 Trillion to 1T, 1 Billion to 1 B, 1 Million to 1M and 1 Thousand to 1K. You can customize it to accept more number of scales amount like Quadrillion, Quintillion, Sextillion, Septillion etc.
public static string GetFormattedAmountText(double amount)
{
 var formattedAmount = string.Empty;

 var x = amount;  //the number to be evaluated
 var e = 0;    //to accumulate the scale
 var i = x;    //a working variable

 while (i > 1)
 {
  i = i / 10;
  e++;
 }

 if (e >= 12)
 {
  formattedAmount = x / 1E9 + "T";
 }
 else if (e >= 9)
 {
  formattedAmount = x / 1E9 + "B";
 }
 else if (e >= 6)
 {
  formattedAmount = x / 1E6 + "M";
 }
 else if (e >= 3)
 {
  formattedAmount = x / 1E3 + "K";
 }

 return formattedAmount;
}

Tuesday, February 10, 2015

Clean way to maintain Session in a single class in ASP.Net application

We can use a wrapper class around the ASP.NET session to maintain session in a single class in ASP.Net application. This class stores one instance of itself in the ASP.NET session and allows you to access your session properties in a type-safe way from any class. Check the below code,
public sealed class Sessions : System.Web.UI.Page
{
     private const string SESSION_MANAGER = "PROJECTNAME_SESSION_OBJECT";

     private Sessions()
     {
          //You can initialize any variables here.
     }

     public static Sessions Current
     {
          get
          {
               Sessions session = (Sessions)HttpContext.Current.Session[SESSION_MANAGER];
               if (session == null)
               {
                     session = new Sessions();
                     HttpContext.Current.Session[SESSION_MANAGER] = session;
               }

               return session;
          }
     }

     // properties
     public string Username{ get; set; }
     public DateTime LoggedinDtae { get; set; }
     public int UserId { get; set; }
}
And you can access those session properties like below,
     //to get UserId
     int userId= Sessions.Current.UserId;
     //to set UserId
     Sessions.Current.UserId = 101;

     //to get Username
     string username= Sessions.Current.Username;
     //to set Username
     Sessions.Current.Username = "test name";

     //to get LoggedinDate
     DateTime loggedinDate = Sessions.Current.LoggedinDate;
     //to set LoggedinDate
     Sessions.Current.LoggedinDate= DateTime.Now;