Friday, August 28, 2015

Recompile the store procedure to improve the performance

One of our report runs under 2min in TEST environment, but over 10 min when deployed in production.  After days of research, it turns out all we need to do is to recompile the stored procedure.

Below is from MSDN:

When a procedure is compiled for the first time or recompiled, the procedure’s query plan is optimized for the current state of the database and its objects. If a database undergoes significant changes to its data or structure, recompiling a procedure updates and optimizes the procedure’s query plan for those changes. This can improve the procedure’s processing performance.

example:
USE AdventureWorks2012;
GO
EXEC sp_recompile N'Sales.Customer';
GO

https://msdn.microsoft.com/en-us/library/ms190439.aspx

Monday, August 17, 2015

Use camelCasing JSON

Add the following code in the WebApiConfig.cs file in the App_Start folder:

In the Register static method, add:

// Web API configuration and services
config.Formatters.JsonFormatter.SerializerSettings.ContractResolver =
                new CamelCasePropertyNamesContractResolver();

reference:
http://odetocode.com/blogs/scott/archive/2013/03/25/asp-net-webapi-tip-3-camelcasing-json.aspx

Wednesday, June 17, 2015

Bootstrap Themes

http://bootswatch.com/

https://wrapbootstrap.com

http://fontawesome.io/

Tuesday, June 09, 2015

MVC bootstrap Modal Dialog

starts with:  http://www.codeproject.com/Tips/826002/Bootstrap-Modal-Dialog-Loading-Content-from-MVC-Pa

Replacing Html.BeginForm with Ajax.BeginForm:  http://blogs.msmvps.com/craigber/?p=41

Fix the cache issue with Ajax.BeginForm:  http://www.leniel.net/2013/09/detecting-fixing-ajax-beginform-partial-view-stale-data.html

Monday, June 01, 2015

MVC data annotation on Password field

Below is the cheat sheet for the password field:


       
[Required]
[StringLength(255, MinimumLength=8)]
[DataType(DataType.Password)]
[RegularExpression(@"^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[^\da-zA-Z])(.{8,15})$", ErrorMessage = "Password must contain at least 1 number, 1 uppercase letter, and 1 special character.")]
public string Password { get; set; }

 

^                   #Beginning of expression
(?=.*\d)            #At least one digit
(?=.*[a-z])         #At least one lower case
(?=.*[A-Z])         #At least one upper case
(?=.*[^\da-zA-Z])   #A non-alphanumeric character
(.{8,15})           #Allow between 8 and 15 characters
$                   #End of expression

Good website to find a starting point for Regular Expression:  http://regexlib.com/

Friday, March 23, 2012

Increase performance by adding NONCLUSTERED INDEX

Got a call from a client reporting an issue that is randomly occurred. after looking into the log file, I found one method took over a min to complete. The code shows only a simple select statement with where clause on "sentby" column. This column is a "nvarchar" and the table itself has over 1 million records.

Here is what I learned when I trying to fix this issue:

1. use "varchar" instead of "nvarchar". only use "nvarchar" when you have different languages in the same column! if you look at the sql execution plan ( sql -> display estimated ececution plan), search "nvarchar" does an index scan and "varchar" does index seek. index seek is orders of magnitude faster than a scan!

2. no index is set on "sentby" column. It won't be an issue in the small table (sql does index scan on small table), but it will impact performance when data grows. I used the script below to add a NONCLUSTERED INDEX on this column.

CREATE NONCLUSTERED INDEX IDX_MyMessageTable ON dbo.MyMessageTable
(
SentBy
)

after the index is created, the 1 min search time is down to under a second.

Tuesday, February 28, 2012

XOOM stuck on dual core logo screen (how to fix)

My XOOM was stuck on the Moto dual core logo screen last night. Soft reset (Volumn up + Power) did not work. It reboot, then still stuck on the logo screen. I searched on the web and the popular solution is to reinstall the ROM (requires android SDK and ROM at moto dev site).

This is how I fixed my issue without installing the ROM (XOOM wifi only US edition):
0. take out the microSD card if you installed one in your XOOM!!!
1. reboot (Vol up + Power)
2. On start-up when you see the Motorola logo, press and hold the Volume Down key.
3. When you see the Android recovery text, press the Volume Up key to put XOOM tablet in recovery mode. After a few min, you should see a Green Android laying down with the triangle and an exclamation (Android recovery screen).
4. On the Android recovery screen, press and keep holding the Power button then press and release the Volume Up key. This will take you to the recovery screen with list of menus.
5. Using Volume Down key navigate to Wipe data / factory reset option and press Power button to select it.
6. Select Yes, delete all user data option using Power button
7. My XOOM is fixed this way. time to set up the account again.

Wednesday, September 21, 2011

Prevent asp.net button double click

http://www.codeproject.com/KB/ajax/disable_btn_on_click.aspx

Tuesday, August 16, 2011

New Object Oriented Features in C# 3.0

Implicitly Typed Local Variables
var age = 30;

Implicitly Typed Arrays
var numbers = new[] { 1, 2, 3, 4, 5};
var names = new[] { "Dave", Doug, "Jim" };


Auto Implemented Properties
old:
public int ID
{
get{return _id;}
set{_id = value;}
}

new:
public int ID { get; set; }

Object Initializers
old:
Person obj = new Person();
obj.ID = 1;
obj.FirstName = "Thiru";
obj.LastName = "Thangarathinam";
new:
Person obj = new Person { ID = 1, FirstName = "Thiru", LastName = "Thangarathinam" };

Collection Initializers
old:
List names = new List();
names.Add("David");
names.Add("Tim");
names.Add("Doug");
new:
List names = new List {"David", "Tim", "Doug"};

Anonymous Types

As the name suggests, anonymous types allow you to create a type on-the-fly at compile time. The newly created type has public properties and backing fields defined for the members you initialize during construction. For example, consider the following line of code:

var obj=new{ID=1,FirstName="Thiru",LastName="Thangarathinam"};

In the above line, you just specify the various attributes you want to have in the anonymous class and assign the instantiated object to a variable of type "var". The actual type assigned to obj is determined by the compiler. Since the compiler assigns the name of the type only at compile time, you can't pass an anonymous type to another method and it can only be used within the method they were declared.

When the compiler sees the above code, it automatically declares a class as follows:

class __Anonymous1
{
private int _id = 1;
private string _firstName = "Thiru";
private string _lastName = "Thangarathinam";

public int ID
{
get{return _id;}
set{_id = value;}
}
public string FirstName
{
get{return _firstName;}
set{_firstName = value;}
}
public string LastName
{
get{return _lastName;}
set{_lastName = value;}
}
}

Anonymous Types use the Object Initializer to specify what properties the new type will be declare. This allows us to reduce code looking similar to this:

Note that the anonymous types are just meant to be placeholders for quickly defining entity types and you can't add methods or customize the behavior of an anonymous type.


Extension Methods

Another important feature introduced with C# is the ability to add new static methods to existing classes, known as extension methods. Using this new feature, you can extend the built-in classes (such as the String class) to support your custom requirements. For example, you can add a new method named "IsValidZipCode" to the string class that validates the zip code format. Let us discuss the code required to accomplish this:

namespace StringExtensions
{
public static class CustomStringExtension
{
public static bool IsValidZipCode(this string input)
{
Regex regEx = new Regex(@"^\d{5}$");
return regEx.IsMatch(input);
}
}
}

As part of the declaring the arguments for the IsValidZipCode, you specify the name of the type to which the extension method should be added as the first parameter. In this case, since we want the IsValidZipCode method to be added to the string class, you specify string as the first parameter. Once you are inside the IsValidZipCode() method, you can access all of the public properties/methods/events of the actual string instance that the method is being called on. In this example, you return true or false depending on whether it is a valid zip code or not.

Now that you have implemented the extension method, the next step is to invoke it from the client application. To be able to do that, you first need to import the namespace in which the CustomStringExtension is located.

using StringExtensions;

Once you have imported the namespace, the next step is to declare a variable of type string and invoke the IsValidZipCode() method.

private void btnTestExtensionMethod_Click(object sender, EventArgs e)
{
string zip = "85226";
if (zip.IsValidZipCode())
MessageBox.Show("Valid Zipcode format");
else
MessageBox.Show("Invalid Zipcode format");
}

As you can see from the preceding lines of code, the extension methods allow you to write cleaner and easy-to-maintain code.

Here are some of the key characteristics of extension methods:

  • The extension method as well as the class that contains the extension method should be static.
  • Although extension methods are static methods, they are invoked as if they are instance methods.
  • The first parameter passed to the extension method specifies the type on which they operate and it is preceded by the "this" keyword.
  • From within the extension method, you can't access the private variables of the type you are extending.
  • Instance methods take precedence over extension methods in situations where they have same signature.

Lambda Expressions


Anonymous methods is a new feature introduced with C# 2.0 that enables you to declare your method code inline instead of with a delegate function. Let us take a look at a simple anonymous method:

public Forms()
{
check = new CheckBox(...);
text = new TextBox(...);
checkBox.CheckedChanged += delegate
{
text.Text = "...";
};
}

As you can see in the above code, you don't have to explicitly declare a new method to link it with an event. C# 3.0 introduces an even simpler syntax, lambda expressions, which you write as a parameter list followed by the "=>" token, followed by an expression or a statement block.

Lambda expressions are simply functions and they are declared in the context of expressions than as a member of a class. It is an inline expression or a statement block which can be used to pass arguments to a method or assign value to delegate. All lambda expressions use the lambda operator => and the left side of the operator denotes the results and the right side contains the expression to be evaluated. For instance, consider the following lambda expression:

age => age + 1

The above function takes one argument named age, and returns age + 1 as the result. As you can see, Lambda expressions follow the below syntax:

(parameter-list) => expression;

where expression can be any C# expression or a block of code. Just like anonymous methods you can use a lambda expression in place of a delegate. Here are some sample lambda expressions and their corresponding delegates.

//Explicitly typed parameter
(Person obj) => MessageBox.Show(obj.FirstName.ToUpper());

//Implicitly typed parameter
(obj) => obj.FirstName == "Thiru";

//Explicitly typed parameter
(int a, int b) => a + b

//Implicitly typed parameter
(x, y) => { return x + y; }

As you see from the preceding lines of code, lambda expressions can be written in such a way that it can infer the parameter type from the signature of the delegate it is assigned to.


Type Inference

To understand type inference, let us look at couple of lines of code.

var count = 1;
var output = "This is a string";
var employees = new EmployeesCollection();

In the above lines of code, the compiler sees the var keyword, looks at the assignment to count, and determines that it should be an Int32, then assigns 1 to it. When it sees that you assign a string to the output variable, it determines that output should be of type System.String. Same goes for employees collection object. As you would have guessed by now, var is a new keyword introduced in C# 3.0 that has a special meaning. var is used to signal the compiler that you are using the new Local Variable Type Inference feature in C# 3.0.

As an example, let us modify our string query example to use the var keyword.




string[] names = {"John", "Peter", "Joe", "Patrick", "Donald", "Eric"};
var namesWithFiveCharacters =
from name in names
where name.Length < 5
select name'
var lstResults = new List();
foreach(var name in namesWithFiveCharacters)
lstResults.Add(name);



As the above code shows, the variable namesWithFiveCharacters now uses the type "var" instead of IEnumerable. Using "var" is much more extensible since it tells the compiler to infer the type from the assignment. In this case, based on the results of the query, which is IEnumerable, the compiler will automatically assume that it is a variable of type IEnumerable.

If you run the code, it still produces the same output.
(http://www.15seconds.com/issue/060713.htm)

Thursday, August 04, 2011

Tethering & Wi-Fi Sharing - Samsung Vibrant

Tethering & Wi-Fi Sharing

With Tethering, your phone can share its mobile data connection with a single computer using a USB cable. With Wi-Fi Sharing, your phone can share its mobile data connection with up to five devices wirelessly.

Tether Your Device

** Device tethering is only available on Devices running 2.2 or higher OS**

To tether your device with a computer or other device and use it as a modem, follow these steps:

  1. Connect your device to a computer using a USB cable.
  2. Tap the Menu key.
  3. Tap Settings.
  4. Tap Wireless & network.
  5. Tap Tethering.
  6. Tap USB tethering.

Your device starts sharing its mobile network data connection with your computer or other device via the USB connection.

Turn On Wi-Fi Portable HotSpot

To turn on Mobile AP, follow these steps:

  1. From any Home screen, tap the Menu key.
  2. Tap Settings.
  3. Tap Wireless & network.
  4. Tap Mobile AP.
  5. If prompted, tap Yes.

Set up Wi-Fi Portable HotSpot

When you turn on Mobile AP, your device starts broadcasting its Wi-Fi network name (Service Set Identifier) so you can connect to it with up to five computers or other devices. The SSID is a unique key that identifies a wireless Local Area Network (LAN). The purpose of the SSID is to stop other wireless equipment from accessing your LAN — whether accidentally or intentionally. To communicate, wireless devices must be configured with the same SSID. To configure devices with your device’s SSID, follow these steps:

  1. From any Home screen, tap the Menu key.
  2. Tap Settings.
  3. Tap Wireless & network.
  4. Tap Mobile AP. 
  5. If desired, tap to edit the Network SSID.
  6. Tap the Security drop-down menu.
  7. Select one of the following options:
    • Open
    • WPA2 PSK
  8. Tap Save.

Wednesday, August 03, 2011

Cons of Response.Redirect(url, false)

Took me a while to find this redirect issue. Glad I can across this blog from Jon B. Gallant.

Quote from Jon B. Gallant http://blogs.msdn.com/b/jongallant/archive/2006/06/20/640484.aspx

The second parameter overload of Response.Redirect is nice because it doesn't call Response.End, which is responsible for throwing the ThreadAbortException. BUT...

The drawback to using this is that the page will continue to process on the server and be sent to the client. If you are doing a redirect in Page_Init (or like) and call Response.Redirect(url, false) the page will only redirect once the current page is done executing. This means that any server side processing you are performing on that page WILL get executed. In most cases, I will take the exception perf hit over the rendering perf hit, esp since the page won't be rendered anyway and that page could potentially have a ton of data. Using Fiddler I was also able monitor my http traffic and see that when using this redirect method the page is actually being sent to the client as well.

I don't usually do redirects in try/catch blocks, but if you do the ThreadAbortException will be handled by your catch and potentially cause a transaction Abort (depending on what you are doing of course). If you do put the redirect in the try block, then you'll need to explicitly catch the ThreadAbortException or create a wrapper method that does that for you.

Something like this would work.

///


/// Provides functionality for redirecting http requests.
///

public static class RedirectUtility
{
///
/// Redirects to the given url and swallows ThreadAbortException that is raised by the Redirect call.
///

/// The url to redirect to.
public static void Redirect(string url)
{
try
{
HttpContext.Current.Response.Redirect(url, true);
}
catch (ThreadAbortException)
{
}
}
}

Tuesday, May 05, 2009

Can't use SCOPE_IDENTITY() to return uniqueidentifier id

SCOPE_IDENTITY() returns the last generated *identity* value in the current scope (function, stored proc., trigger, etc.). Identity columns need to be of type bigint, int or smallint and are not compatible with type uniqueidentifier (i.e. you can't assign an integer to a variable defined as a uniqueidentifier).

So, if you're asking SQL Server to give you last identity inserted and then assigning that to a variable previously declared as a uniqueidentifier, you'll end up with the compatibility error that you're receiving.

Wednesday, April 08, 2009

Overloading methods in WCF

Service oriented development is different than the Object oriented programming. Overloading methods is possible in WCF, but not recommended.

To make it work in WCF, you'll need to add Name property

[ServiceContract]
public interface ICalendarService
{
[OperationContract(Name = "GetScheduledEventsByDate")]
ScheduledEvent[] GetScheduledEvents(DateTime date);

[OperationContract(Name = "GetScheduledEventsByDateRange")]
ScheduledEvent[] GetScheduledEvents(DateTime start, DateTime end);
}

For more info: here

SQL: Return limit Rows

In the asp.net application, i found the good way to return limit rows from data table is to use the ROWCOUNT

CREATE PROCEDURE GetContacts
(
 @ModuleID int,
 @maxrows int = 0
)
AS
 SET ROWCOUNT @maxrows

 SELECT
   ItemID,
   CreatedDate,
   CreatedByUser,
   Name,
   Role,
   Email,
   Contact1,
   Contact2
 FROM
   Contacts
 WHERE
   ModuleID = @ModuleID
For more info: http://authors.aspalliance.com/stevesmith/articles/sprowcount.asp

Wednesday, April 01, 2009

Change the author initial when review comments

  1. On the Review tab, in the Tracking group, click the arrow next to Track Changes, and then click Change User Name.
  2. Click Popular.
  3. Under Personalize your copy of Office, change the name or initials that you want to use in your own comments.

Thursday, March 12, 2009

FxCop: exclude the naming rule for some words

I used the Iframe identifier in my project and FxCop did not like it.

The way to get around this without rename everywhere is to include a custom dictionary named CustomDictionary.xml in the project directory.


for more info: http://msdn.microsoft.com/en-us/bb264492.aspx

Friday, March 06, 2009

FxCop to Excluded in Source

There are 2 ways to make the rule exceptions in FxCop. One way is to update the .fxcop file. Another way is to update your source code.


For Excluded in Source, add add the following line on top of the method/function/data members.

[SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly", Justification = "Need to set Specialties collection")]

Also, need to declare System.Diagnostics.CodeAnalysis in your source file.

using System.Diagnostics.CodeAnalysis;

Wednesday, January 28, 2009

StringComparison

Here is a great article on when to use the StringComparison.

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

DO: Use StringComparison.Ordinal or OrdinalIgnoreCase for comparisons as your safe default for culture-agnostic string matching.

DO: Use StringComparison.Ordinal and OrdinalIgnoreCase comparisons for increased speed.

DO: Use StringComparison.CurrentCulture-based string operations when displaying the output to the user.

DO: Switch current use of string operations based on the invariant culture to use the non-linguistic StringComparison.Ordinal or StringComparison.OrdinalIgnoreCase when the comparison is linguistically irrelevant (symbolic, for example).

DO: Use ToUpperInvariant rather than ToLowerInvariant when normalizing strings for comparison.

DON'T: Use overloads for string operations that don't explicitly or implicitly specify the string comparison mechanism.

DON'T: Use StringComparison.InvariantCulture-based string operations in most cases; one of the few exceptions would be persisting linguistically meaningful but culturally-agnostic data.

Thursday, January 22, 2009

Use delegate to sort the generic list (collection)

Here is an example of how to use the delegate to sort the list:

returnList.Sort(delegate(IMyClass x, IMyClass y)
{
return String.Compare(x.Name, y.Name);
});

So, instead of override the ICompare, you can use this short-cut to return a sorted list.

Here is how to just make your Thing class implement IComparable, implementing the CompareTo method like this:

public int CompareTo(Thing other)
{
return Name.CompareTo(other.Name);
}