Friday, November 16, 2012

Observer Design Pattern using Delegates/events

Today I want to discuss with you how to implement Observer design pattern using delegate and event in asp.net /c#.

Observer Pattern

The observer pattern is a software design pattern in which an object, called the subject, maintains a list of its dependents, called observers, and notifies them automatically of any state changes, usually by calling one of their methods. It is mainly used to implement distributed event handling systems. The Observer pattern is also a key part in the familiar Model View Controller (MVC) architectural pattern.(wikipedia).

UML class diagram of Observer pattern(wikipedia)





The Observer Pattern describes the dependence relationship between one object (observable) to many objects (observers). It's also called Model/View, Dependents, or Distributor/Listener pattern.This article introduces an implementation when we can use the Observer pattern to keep all observer objects updated after things have changed.

Case project

In this case, patient is an ObservableObject that needs to send out the notification when the hospital updates his/her physical status. The hospital will determine who will be notified when the patient status is updated.

Thursday, November 15, 2012

A Custom Attribute based approach to write summary on business object

Last day, I have got a mail from a junior developer he needs some help about custom attributes. He has no previous experience about it. I have delivered his some speech or send some link for study. Today I have made an example for him, so that he can understand its usage very easily. Now this also share with you it may also help other friends.


using System;
using

Tuesday, October 9, 2012

MSSQL SERVER 2008 – IntelliSense Does Not Work

Last few months ago I have upgraded Visual Studio 2010 ultimate with service pack 1. But unfortunately my SQL Server Management Studio(SSMS) 2008 intellisense not working. After searching I got that it is a common problem. Please have visit here.

To fix it just install SQL Server 2008 r2 SP1. You can download it from here.

If it is not working please check the following issues it may solve your problem.

  • Verify that the T-SQL Editor does not launch in SQLCMD mode Under Tools->Options->Query Execution->SQL Server->General, make sure “By default, open new queries in SQLCMD mode” is unchecked.

Thursday, September 27, 2012

“The ‘VSTS for Database Professionals Sql Server Data-tier Application’ package did not load correctly”

After long time, I have got some relax from work pressures. I have got lots of mail about several issues. I had tried to give them hot fix with in a very short time. Sorry to everyone for my late response.

Today, when I am setting my new laptop I have faced a problem in VS 2010. Just run the VS2010 and got the error,
The ‘VSTS for Database Professionals Sql Server Data-tier Application’ package did not load correctly.
I don't understand why this is happening?

Potential cause:
This problem may occur due to install SQL Server Express 2008 with Visual Studio 2010 installation. When install SQL Server 2008 r2 on the same machine I had got an exception. So that I have uninstalled SQL Server Express 2008 from machine and then install SQL Server 2008 r2 but installation not completed successfully.

Solution 1:
I have got the solution from this link.
To fixed my problem I did the following tasks

Step-1: Run the Visual Studio 2010 Ultimate  disc
Step-2: Explore  \WCU\DAC folder from disc
Step-3: Now installed the three packages from the Visual Studio 2010 Ultimate disc and it fixed the problem right away for me.

Microsoft SQL Server 2008 R2 Data-Tier Application Framework with this command:
\WCU\DAC\DACFramework_enu.msi

Microsoft SQL Server 2008 R2 Data-Tier Application Project:
\WCU\DAC\DACProjectSystemSetup_enu.msi

Microsoft SQL Server 2008 R2 Transact-SQL Language Service:
\WCU\DAC\TSqlLanguageService_enu.msi

If required you can re-install the Visual Studio 2010 Service pack 1.

Thursday, August 16, 2012

KeyValue pair/Dictionary with duplicate keys

Very recently for my development purpose I need to use Dictionary. And it works very nicely. But problem occurred when requirement changes and face a scenario that duplicate key's are needed to handle in Dictionary which is not possible. So I had written a custom class to handle this problem,please suggests me if there is any better idea.

Examble:

public class KeyValuePair
{
public string Key { get; set; }
public int Value { get; set; }
public string HdValue { get; set; }

public KeyValuePair(string key, int value, string hdValue)
{
this.Key = key;
this.Value = value;
this.HdValue = hdValue;
}
}

Insert Data:
List<KeyValuePair> listKeyValuePair= new List<KeyValuePair>();
listKeyValuePair.Add(new KeyValuePair("TAX",2,"Income Tax"));
listKeyValuePair.Add(new KeyValuePair("TAX",4,"Vatlue added Tax"));
listKeyValuePair.Add(new KeyValuePair("PORT",9,"Vehicle Test"));


Sort Data:
List<KeyValuePair> listSorted = listKeyValuePair.OrderByDescending(x => x.key).ToList();


Filter Data:
var filteredData = listKeyValuePair.where(keyValue=> string.Compare(keyVaue.Key,"TAX")==0).ToList();
if(filteredData.Count > 0)
{
//Do something
}

Wednesday, August 15, 2012

Short circuit evaluations on && and || in JavaScript

Like many other languages Javascript’s && and || operators short-circuit evaluations,that is, for

&& if the first operand evaluates to false, the second operand is never evaluated because the result would always be false.
Similarly, for
|| if the result of the first operand is true, the second operand is never operated.

This means that in the following expression, x will never be compared to y.
true || x == y

This short-circuiting is great for performance, as it allows significant bits of calculations to be skipped. In addition to that, it lets you to write e.g. the following in one expression without getting an ‘object has no properties’ error:
oNode && oNode.firstChild

Be mindful though when using && with code that has side effects, e.g. say you have two objects with a hasError() method which return true or false depending on whether an error occurred and additionally output an error message:
x.hasError() && y.hasError()

Here, if x has an error, y will never be evaluated and thus the error message will never be shown.

For more details pls visits this and that.

Monday, July 2, 2012

Login failed for user 'NT AUTHORITY\NETWORK SERVICE'

Very recently I got a mail from a junior guy he faced a problem every time when he installed the SQL server database on his workstation. But he failed to understand what is the main reason behind this. The problem was that after installing SQL server database his working web sites were throws exception like this...

System.Data.SqlClient.SqlException: Login failed for user 'NT AUTHORITY\NETWORK SERVICE'

Reason
The main reason behind this error occurs when you configured your web site with IIS. When any one tries to browse the site, IIS send the request to the SQL server with credentials. But unfortunately the credential do not have proper permission. So that it throws exception.

Solution
We can solve this problem in several ways....
First solution that resolved my problem was:

  1. Login to SQL server database via SQL Server Management Studio
  2. Go to the "Security" directory of desired database
  3. Right-click the Users directory
  4. Select "New User..."
  5. Add 'NT AUTHORITY\NETWORK SERVICE' as a new user
  6. In the Data Role Membership area, select db_owner
  7. Click OK

Monday, May 28, 2012

Custom paging,sorting and filtering data with Dynamic query

Sometime it becomes very essential for us to write dynamic query for custom paging,sorting and filtering data. Today I want to share simple one which may help others to fulfill their requirements.


Sample stored procedure:


CREATE PROCEDURE [dbo].[spGetAllTag]
@SearchText varchar(50),
@PageIndex INT = 1,//page number like 1,2,3
@PageSize INT =10,
@SortCol varchar(100),
@TotalCount int output
As
Begin

;WITH PagingCTE (Row_ID,ID,Tags,Weight,CreatedBy)
     AS
      (
      SELECT
            ROW_NUMBER()
                  OVER(ORDER BY
                         CASE WHEN @SortCol='Name DESC' THEN [NAME] END DESC,
                         CASE WHEN @SortCol='Name ASC'  THEN [NAME] END ASC,
                         CASE WHEN @SortCol='CreatedBy DESC' THEN CreatedBy END DESC,
                         CASE WHEN @SortCol='CreatedBy ASC'  THEN CreatedBy END ASC,
                         CASE WHEN @SortCol='Weight ASC'   THEN Weight  END ASC,
                         CASE WHEN @SortCol='Weight DESC'  THEN Weight  END DESC

                        ) AS [Row_ID],
ID,
[NAME],
Weight,
CreatedBy

FROM TabularWeight
WHERE [Name] LIKE @SearchText + '%'
         )

       SELECT
            Row_ID,
            ID,
            [NAME],
            Weight,
            CreatedBy
         
      FROM PagingCTE
      WHERE Row_ID >= (@PageSize * @PageIndex) - (@PageSize -1) AND
            Row_ID <= @PageSize * @PageIndex

select @TotalCount = count(1) from dbo.TabularWeight where [Name] LIKE @SearchText + '%'  
   
End
GO

Friday, April 27, 2012

How can I get a value of a property from an anonymous type (C#)

Last day I have faced a problem when working with  "Anonymous Type". In development procedure I have got  result from a service which return object made of anonymous type. The problem arise when I need to access property of anonymous type. After made some r&d I have got the solution. Now share with you ....

Solution 1: (use reflection to retrieve the values of the following anonymous type)


var obj = new { ClientId = 7, ClientName = "Ahsan", Jobs = 12,City="Dhaka" };
System.Type type = obj.GetType();
int clientid = (int)type.GetProperty("ClientId").GetValue(obj, null);
string clientname = (string)type.GetProperty("ClientName").GetValue(obj, null);
// clientname  return the result Ahsan

More generic solution:

public static T GetValueFromAnonymousType( object dataitem, string itemkey ) 
{
    System.Type type = dataitem.GetType();
    T itemvalue = (T)type.GetProperty(itemkey).GetValue(dataitem, null);
    return itemvalue;
}

Example:
 var obj = new { ClientId = 7, ClientName = "Ahsan", Jobs = 12,City="Dhaka" };
 string clientname = GetValueFromAnonymousType(obj, "ClientName");



Solution 2:

var obj = new { ClientId = 7, ClientName = "ACME Inc.", Jobs = 5 };
string clientname = TypeUtils.GetValueFromAnonymousType(obj, "ClientName");

var obj = new { ClientId = 7, ClientName = "ACME Inc.", Jobs = 5 };
Type t = obj.GetType();

//Then from that you look up a property:
PropertyInfo p = t.GetProperty("ClientName");

//Then from that you can get a value:
object v = p.GetValue(obj, null);

//This answer is long overdue for an update for C# 4:
dynamic d = obj;
object v = d.ClientName;

Hope that it may helpful for others.
Thanks

Monday, April 2, 2012

2012 Microsoft® MVP Award

Last night I have got this mail from Microsoft MVP award program manager.

“Dear Ahsan Murshed,

Congratulations! We are pleased to present you with the 2012 Microsoft® MVP Award! This award is given to exceptional technical community leaders who actively share their high quality, real world expertise with others. We appreciate your outstanding contributions in ASP.NET/IIS technical communities during the past year.”


Alhamdulillah,I am pleased to say that Microsoft has re-awarded me Microsoft MVP status again for 2012! This is my second consecutive MVP award, this year for Microsoft ASP.NET/IIS. I am really proud about this. This reward obviously motivated me to give more effort for community.

Tuesday, March 13, 2012

The model backing the 'MyDBContext' context has changed since the database was created. Either manually delete/update the database, or call Database.SetInitializer with an IDatabaseInitializer instance. For example, the DropCreateDatabaseIfModelChanges strategy will automatically delete and recreate the database, and optionally seed it with new data.

Today I have faced a problem when working with a previous developed ASP.NET MVC application. Just copy the database(.sdf) from previous version to new version. I have changed some validation and business logic. But when run the application it shows me the following error:


The model backing the 'MyDBContext' context has changed since the database was created. Either manually delete/update the database, or call Database.SetInitializer with an IDatabaseInitializer instance. For example, the DropCreateDatabaseIfModelChanges strategy will automatically delete and recreate the database, and optionally seed it with new data.


It was a running application after searching on community I have got the solution.

Solution 1:
However, even if you manually update the database to follow the model, this exception will still occur. The reason is that EF does not check model schema completely: tables, columns, keys, indexes etc.

It calculates a hash of the model and compares with the hash of model which the database was built with. The hash is stored at EdmMetadata table.

Monday, March 12, 2012

ASP.NET Single Page Application (SPA)

My previous article wrote about new features of MVC 4.0 beta. Today I want to share with you another cool feature "ASP.NET Single Page Application (SPA)" known as ASP.NET SPA.
The ASP.NET Single Page Application (SPA) is a new feature in MVC 4 beta preview.

This project type is based on a stack of open source libraries and the MVVM pattern made popular by WPF and Silverlight. Single Page Application(SPA) Frameworks are growing popularity in the web community with lot of libraries such as JavaScriptMVC, Backbonejs and many other libraries.

(Img src: asp.net official site)


ASP.NET MVC 4 introduces experimental support for building single page application (SPA) through a template. Much of the plumbing work of wiring up the client side scripts, javascript modelviews and the controllers is automated, making it a quick start to develop SPAs relatively easier.

The ASP.NET Single Page Application (SPA)includes the following components:

1.A set of JavaScript libraries for richer local interactions with cached data
2.Additional Web API components for unit of work and DAL support
3.An MVC project template with scaffolding to get started quickly

For more info:http://www.asp.net/single-page-application

New cool features in MVC 4.0

Last few days I have worked on MVC3 and MVC4 beta. In MVC4 beta some cool features added like:

1.ASP.NET Web API
2.ASP.NET Single Page Application
3.Enhancements to Default Project Templates
4.Mobile Project Template


5.Display Modes

Friday, March 2, 2012

Error: Unable to Validate Data

Recently I have made some changes on my application after upload I have found this error:

Unable to validate data at
System.Web.Configuration.MachineKey.GetDecodedData(Byte[] buf, Byte[] modifier,
Int32 start, Int32 length, Int32& dataLength) at
System.Web.UI.LosFormatter.Deserialize(String input)

But I don't understand why this error was happening. Because I have changed on business logic not any architecture. After doing some r&d got the answer:)


Potential causes:

1.An application pool recycling between the time the viewstate was generated and the time that the user posts it back to the server (unlikely).
2.Modification of viewstate by firewalls/anti-virus software
3.A web farm where the machineKeys are not synchronized (not your issue).
4.Posting from one aspx page to another.

After studying various tutorial I have found that the problem is with the viewstate. The viewstate is actually decrypted in the server using a secret Machine key which resides on the server. The interesting thing is the key gets regenerated after a certain time. Therefore when the user returns the viewstate, if the machine identified key is changed, the decryption of viewstate fails and thus throws this nasty error.

Solution 1:

The solution is simple. First of all, to solve the issue, I disabled the ViewState for the current page by putting EnableViewState = false. I even disabled this for the entire viewstate for the website using Web.config. But still the error.

Finally I used "EnableViewStateMac =false" in pages section.this cause the problem.

<pages buffer="true" enableViewStateMac="flase"/>
</pages>


Just place the following between the system.web section and the site starts working.

Solution 2:

Second solution that we might use as well is to place the machine key directly on our web.config, so that it always decrypts and encrypts using the static key values. To do this, we need to use the following:

<machinekey validationkey="22E995276703B846C4AD0881EE3159FFCB376CD48B27F64
9A074815C83D5C925038938F6943555687582CBC186DB22E552FCDB4D46
124BAADEE85A857CC135BC"
decryptionkey="60588EB661A6483348C20F92659775872CB06427AF20733C"
validation="SHA1"></machinekey>


You can also try to use this site to generate validation key.

Viewstate & Machine config interaction:

When a request for a page in the server. After you place the request the server processes it, encrypts the viewstate that the server receives using the encryption mentioned. Basically it uses the key mentioned in the Machine.config to encrypt the viewstate data. Finally it converts to Base64 and embeds into some hidden fields.

We can mention the machine key in Web.config too so that it uses it for the current website. You might use the AutoGenerate option too to enable/disable autogeneration of key during runtime.
For more information visits.

For further study please visits: MS article

Orchard 1.4 Is released!!

Last day officially announced that the new Orchard release - version 1.4. It's a big step forward from the previous, 1.3.10 version, both in terms of performance and features.

Orchard 1.4 is here! The release is published on our Orchard CodePlex website and Microsoft Web Application Gallery.


What's new?

Orchard 1.4.0 fixes bugs, improves performance and introduces the following features:

Autoroute: Set-up token-based patterns for your URLs. David Hayden has a good post describing the feature: http://www.davidhayden.me/blog/autoroute-custom-patterns-and-route-regeneration-in-orchard-1.4

Projector: Create arbitrary queries on your site contents, then display the results in projection pages and widgets.

Fields: Orchard now comes with new field types for Boolean, Date/Time, Enumeration, HTML5 Input, Links, Media Picker and Numeric. The text field has a new setting for the flavor which adds html, markdown and textarea to the default text box.


Breaking Changes

Orchard 1.4 introduces a breaking change with the Autoroute and Alias features by removing the Route part that was previously handling URLs and titles for content items.

Migrating existing content items can be done with a special module (see next section), but it may also happen that some modules that were relying on the presence of Route may stop working.

We've asked all module developers to review their code with the new version, but there may still be incompatible ones out there. If a module misbehaves, please check whether a new version is available. If there isn't one, please contact its author through the contact form on the Orchard Gallery.

You may also attempt to fix the modules you need: we have a set of instructions on this thread.

Friday, February 10, 2012

How to convert List to DataTable

very recently I have published a new article based on "How to convert DataTable to generic List"

Now I have discussed about the vice verse -"convert List to DataTable"

Solution:

Here we use PropertyDescriptor ComponentModel class.

public static DataTable ToDataTable<T>(this IList<T> data)
{
PropertyDescriptorCollection properties =
TypeDescriptor.GetProperties(typeof(T));
DataTable table = new DataTable();
foreach (PropertyDescriptor prop in properties)
table.Columns.Add(
prop.Name,
(prop.PropertyType.IsGenericType && prop.PropertyType.GetGenericTypeDefinition() == typeof(Nullable<>))
? Nullable.GetUnderlyingType(prop.PropertyType)
: prop.PropertyType
);
foreach (T item in data)
{
DataRow row = table.NewRow();
foreach (PropertyDescriptor prop in properties)
row[prop.Name] = prop.GetValue(item) ?? DBNull.Value;
table.Rows.Add(row);
}
return table;
}

"The project type is not supported by this installation"

Today I have faced this problem when try to open a VS2010 project which is covert from VS2008 project. FYI:This project was built by another developer.

After conversion open the solution it gave me the following error,"The project type is not supported by this installation"

Possible Cause:It may possible that lack some advanced frameworks like newer versions of Windows Mobile SDK, but IIRC error message in such case is different.Or may be some updated packages required Or Visual studio version is not matched with your one(VS2008 Express, Standart, Pro or Team System/ VS2010 Professional, Premium or Ultimate)

After search on net I have found several solution, now these solutions are share with you.

Solution 1:(this is worked for me)

Open the Project.csproj file with any editor like notepad or notepad++,
Delete whatever you found between <ProjectTypeGuids></ProjectTypeGuids>

Solution 2:

Open a new cmd prompt with admin privilege.
Type “devenv / setup” and then run(takes a while without any visual activity).

Solution 3:

Open a new cmd prompt with admin privilege.
Type “devenv /ResetSkipPkgs” and then run(takes a while without any visual activity).


Useful Tips
This tips is not this error specific. But hope that helpful for others. Sometimes we can't open our web project using solution. One of the main reason is that this web project is configured for IISUSER only. So to open this type of project:

1.Open the web.config file
2.Find the <IISUSER></IISUSER>
3. Make it False=> <IISUSER>False</IISUSER>
Now hopefully you web project is open by solution.

How to convert DataTable to generic List

I have discussed about conversion of DataTable to Generic List<t>. We can do it in various way. I want to share with you some of them....

Solution 1:
DataTable dt = CreateDataTable();
List<datarow> list = new List<datarow>();
foreach (DataRow dr in dt.Rows)
{
list.Add(dr);
}

Solution 2:
DataTable table = new DataTable {
Columns = {
{"Foo", typeof(int)},
{"Bar", typeof(string)}
}
};
for (int i = 0; i < 5000; i++) {
table.Rows.Add(i, "Row " + i);
}

List<T> data = new List<t>(table.Rows.Count);
foreach (DataRow row in table.Rows) {
data.Add(new T((int)row[0], (string)row[1]));
}

Solution 3:
Using Linq/lamda expression. It return data in List<t>.
List<string> list =dataTable.Rows.OfType<datarow>().Select(dr => dr.Field<string>(0)).ToList();

Solution 4:
Using Linq/lamda expression.
List<employee> list= new List<employee>();
list= (from DataRow row in dt.Rows
select new Employee
{
FirstName = row["ColumnName"].ToString(),
LastName = row["ColumnName"].ToString()

}).ToList();


Solution 5:
Using Linq/lamda expression.
List<t> target = dt.AsEnumerable()
.Select(row => new T
{
// assuming column 0's type is Nullable<long>
ID = row.Field<long?>(0).GetValueOrDefault()
Name = String.IsNullOrEmpty(row.Field<string>(1))
? "not found"
: row.Field<string>(1)
})
.ToList();


Solution 6:
Using Linq/lamda expression. All are return array of datarow in List<t>.

List<datarow> list1= dataTable.Select().ToList();
List<datarow> list2= dataTable.Rows.Cast<datarow>().ToList();
List<datarow> list3 = dataTable.AsEnumerable().ToList();
List<datarow> list4 = new List<datarow>(dataTable.select());

Here result will return all rows of datatable, as an array of datarows, and the List constructor accepts that array of objects as an argument to initially fill our List<datarow> with.

Solution 7:
Using reflection PropertyInfo class.

sealed class Tuple<T1, T2>
{
public Tuple() {}
public Tuple(T1 value1, T2 value2) {Value1 = value1; Value2 = value2;}
public T1 Value1 {get;set;}
public T2 Value2 {get;set;}
}


public static List<T> Convert<T>(DataTable table)
where T : class, new()
{
List<Tuple<DataColumn, PropertyInfo>> map =
new List<Tuple<DataColumn,PropertyInfo>>();

foreach(PropertyInfo pi in typeof(T).GetProperties())
{
ColumnAttribute col = (ColumnAttribute)
Attribute.GetCustomAttribute(pi, typeof(ColumnAttribute));
if(col == null) continue;
if(table.Columns.Contains(col.FieldName))
{
map.Add(new Tuple<DataColumn,PropertyInfo>(
table.Columns[col.FieldName], pi));
}
}

List<T> list = new List<T>(table.Rows.Count);
foreach(DataRow row in table.Rows)
{
if(row == null)
{
list.Add(null);
continue;
}
T item = new T();
foreach(Tuple<DataColumn,PropertyInfo> pair in map) {
object value = row[pair.Value1];
if(value is DBNull) value = null;
pair.Value2.SetValue(item, value, null);
}
list.Add(item);
}
return list;
}

Solution 8:
Another class using reflection PropertyInfo class.

public List<T> ConvertTo<T>(DataTable datatable) where T : new()
    {
        List<T> Temp = new List<T>();
        try
        {
            List<string> columnsNames = new List<string>();
            foreach (DataColumn DataColumn in datatable.Columns)
                columnsNames.Add(DataColumn.ColumnName);
            Temp = datatable.AsEnumerable().ToList().ConvertAll<T>(row => getObject<T>(row, columnsNames));
            return Temp;
        }
        catch
        {
            return Temp;
        }

    }
    public T getObject<T>(DataRow row, List<string> columnsName) where T : new()
    {
        T obj = new T();
        try
        {
            string columnname = "";
            string value = "";
            PropertyInfo[] Properties;
            Properties = typeof(T).GetProperties();
            foreach (PropertyInfo objProperty in Properties)
            {
                columnname = columnsName.Find(name => name.ToLower() == objProperty.Name.ToLower());
                if (!string.IsNullOrEmpty(columnname))
                {
                    value = row[columnname].ToString();
                    if (!string.IsNullOrEmpty(value))
                    {
                        if (Nullable.GetUnderlyingType(objProperty.PropertyType) != null)
                        {
                            value = row[columnname].ToString().Replace("$", "").Replace(",", "");
                            objProperty.SetValue(obj, Convert.ChangeType(value, Type.GetType(Nullable.GetUnderlyingType(objProperty.PropertyType).ToString())), null);
                        }
                        else
                        {
                            value = row[columnname].ToString().Replace("%", "");
                            objProperty.SetValue(obj, Convert.ChangeType(value, Type.GetType(objProperty.PropertyType.ToString())), null);
                        }
                    }
                }
            }
            return obj;
        }
        catch
        {
            return obj;
        }
    }


Hopefully it will help other developers.

How to remove duplicate row from a DataTable

Today in my development procedure I want to remove duplicate rows from DataTable. There is a lot of solution in community. But I think that I need to make the solution for flexibility of use.
Now I want to shared this with you. Hope that it will helpful for others developers.

First Solution:

public DataTable RemoveDuplicateRows(DataTable dTable, string colName)
{
Hashtable hTable = new Hashtable();
ArrayList duplicateList = new ArrayList();

//Add list of all the unique item value to hashtable, which stores combination of key, value pair.
//And add duplicate item value in arraylist.
foreach (DataRow drow in dTable.Rows)
{
if (hTable.Contains(colName==""?drow[0]:drow[colName]))
duplicateList.Add(drow);
else
hTable.Add(colName==""?drow[0]:drow[colName], string.Empty);
}

//Removing a list of duplicate items from datatable.
foreach (DataRow dRow in duplicateList)
dTable.Rows.Remove(dRow);

//Datatable which contains unique records will be return as output.
return dTable;
}

we can call this method

RemoveDuplicateRows(dataTable,""); or
RemoveDuplicateRows(dataTable,"word");

Second Solution:

private void btnRemove_Click(object sender, EventArgs e)
{
List keyColumns = new List();
keyColumns.Add("ColumnName1");
keyColumns.Add("ColumnName2");
keyColumns.Add("ColumnName3");
RemoveDuplicates(ref dtAlarmData, keyColumns);
}

//Method to remove Duplicate value from DataTable

public static void RemoveDuplicatesFromDataTable(ref DataTable table, List keyColumns)
{
Dictionary uniquenessDict = new Dictionary(table.Rows.Count);
StringBuilder stringBuilder = null;
int rowIndex = 0;
DataRow row;
DataRowCollection rows = table.Rows;
while (rowIndex < rows.Count - 1) { row = rows[rowIndex]; stringBuilder = new StringBuilder(); foreach (string colname in keyColumns) { //If no column name found it will check the first column by default. stringBuilder.Append(colname==""?((string)row[0]):((string)row[colname]));
}

if (uniquenessDict.ContainsKey(stringBuilder.ToString()))
{
rows.Remove(row);
}
else
{
uniquenessDict.Add(stringBuilder.ToString(), string.Empty);
rowIndex++;
}
}
}

Tuesday, February 7, 2012

Compare to List using C# and LINQ

LINQ offers developers a lot of useful features by which developers can solve more complex solution in a easy way. Today our discussion about comparison of two lists or collections.

Sample code 1:

static void Main(string[] args)
{
List strList1 = new List{"Jack","And","Jill","Went","Up","The","Hill"};
List strList2 = new List{"Jack", "And", "Jill", "Went", "Down", "The", "Hill"};

Console.WriteLine("Except result ...........");
var lstExcept = strList2.Except(strList1);
foreach (var variable in lstExcept)
{
Console.WriteLine(variable);
}

Console.WriteLine("Insect result ...........");
var lstInsect = strList2.Intersect(strList1);
foreach (var variable in lstInsect)
{
Console.WriteLine(variable );
}

Console.WriteLine("Union result ...........");
var lstUnion = strList2.Union(strList1);
foreach (var variable in lstUnion)
{
Console.WriteLine(variable );
}
Console.ReadLine();
}

Output:



Note that if you want to, say, ignore case:

List except = listA.Except(listB, StringComparer.OrdinalIgnoreCase);
You can replace the last parameter with an IEqualityComparer of your choosing.

You can get more information from here.

Sample code 2:
In sample code 1 just showing simple implementation. Now showing some more complex implementation.

This solution produces a result list, that contains all differences from both input lists. You can compare your objects by any property, in my example it is ID. The only restriction is that the lists should be of the same type:

var DifferencesList = ListA.Where(x => !ListB.Any(x1 => x1.id == x.id))
.Union(ListB.Where(x => !ListA.Any(x1 => x1.id == x.id)));

Using RequiredField Validator with CKEditor in ASP.Net

Last day I have faced a problem with CKEDITOR and asp.net required field validator. Strange problem! When I left blank the textarea(CKEDITOR) required field validate it properly. But when I filled up textarea still now required field validator showed error message for entering data.

After some r&d I have found that the requiredfield validator control will not work properly when it is used with a textarea that is configured with CKEditor. This is due to the fact that, the CKEditor content will not be synched to the page element(textarea) properly when the validator control fire.

To overcome this difficulty, we need to call the method .updateElement() in order to sync or post the content back to the textarea.

Solution:


<head>
<title>CKEDITOR TEST</title>
<script src="_scripts/jquery-1.3.2.min.js" type="text/javascript"></script>
<script type="text/javascript" src="ckeditor/ckeditor.js"></script>
<script type="text/javascript" src="ckeditor/adapters/jquery.js"></script>

<script type="text/javascript" language="javascript">

$(document).ready(function() {
var textBoxId = $(".test").attr('id');
if (!CKEDITOR.instances[textBoxId]) {
$('#textBoxId').ckeditor();
});


function UpdateContent() {
var textBoxId = $(".test").attr('id');
if (textBoxId != null) {
var editor = CKEDITOR.instances[textBoxId];
editor.updateElement();
}
}

</script>

</head>

<body>
<form id="form1" runat="server">
<div>
<asp:TextBox ID="TextBox1" CssClass="test" MaxLength="3000" TextMode="MultiLine" Rows="3" runat="server"></asp:TextBox>

<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server"
ControlToValidate="TextBox1" ErrorMessage="No content in CKEditor!"></asp:RequiredFieldValidator>

</div>

<asp:Button ID="btnSave" OnClientClick="javascript:UpdateContent()" runat="server" Text="Save" onclick="btnSave_Click" />

<asp:Label ID="lblError" CssClass="error-msg" runat="server" Text=""></asp:Label>
</form>
</body>

Tuesday, January 31, 2012

Useful overloads for String.Split()

Most of C# developers are familiar with this String.split() method. I have found some useful overloads for split method of the string class split the string in array of string.

Example 1:

String.Split( char[])

Code:
string words = "string1,string2,string3,,string4 string5.";
string [] split = words.Split(new Char [] {' ', ','});

Above code create a string array which has

//result
split[0]=string1
split[1]=string2
split[2]=string3
split[3]=
split[4]=string4
split[5]=string5

but What If I want to remove empty string from the array when I split string.
Solution to this problem is to make use of second overload method of the the string Split where you can specify the option to remove string. So above code is rewritten as

Overload method with option
String.Split(Char[], StringSplitOptions)

Code:
string words = "string1,string2,string3,,string4 string5.";
string [] split = words.Split(new Char [] {' ', ','},StringSplitOptions.RemoveEmptyEntries);

Return split array->

//result
split[0]=string1
split[1]=string2
split[2]=string3
split[3]=string4
split[4]=string5

Example 2:

Now consider case where I have to limit no of return string. Consider for example

string a = "key:Testkey, Value : testValue1,testValue2";

Now I have to get the key:Testkeyin string 1 and Value : testValue1,testValue2in string 2.
Overload function to split string in limited no. of string

Split(Char[], Int32)

Code:
string a = "key: Testkey, Value : testValue1,testValue2";
string [] split = words.Split(new Char [] {','},2);

Return split array->

//result
split[0]= "key: Testkey";
split[1]= "Value : testValue1,testValue2";

For more information:
String.Split Method (Char(), Int32):
http://msdn.microsoft.com/en-us/library/c1bs0eda.aspx

String.Split Method (Char(), Int32, StringSplitOptions):
http://msdn.microsoft.com/en-us/library/ms131450.aspx

RequiredField Validator not working with CKEditor in ASP.Net

Last month I had worked on a project where we were using CKEDITOR. For validation using asp.net required field validator. It is working for all control but unfortunately required field validator is not working for CKEDITOR.

After searching I have got the reason and solution for this.

Reason:

The requiredfield validator control will not work properly when it is used with a textarea that is configured with CKEditor. This is due to the fact that, the CKEditor content will not be synched to the page element(textarea) properly when the validator control fire.

Solution:

To overcome this difficulty, we need to call the method updateElement() in order to sync or post the content back to the textarea. The below code does that,

<head>
<script src="_scripts/jquery-1.3.2.min.js" type="text/javascript"></script>
<script type="text/javascript" src="ckeditor/ckeditor.js"></script>
<script type="text/javascript" src="ckeditor/adapters/jquery.js"></script>

<script type="text/javascript" language="javascript">
$(document).ready(function() {
$('#TextBox1').ckeditor();
});

function UpdateContent() {
var ckeditorinstance = $('#TextBox1').ckeditorGet();
ckeditorinstance.updateElement();
}
</script>
</head>

<body>
<form id="form1" runat="server">
<div>
<asp:TextBox ID="TextBox1" TextMode="MultiLine" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server"
ControlToValidate="TextBox1" ErrorMessage="No content in CKEditor!"></asp:RequiredFieldValidator>
</div>
<asp:Button ID="btnSave" OnClientClick="javascript:UpdateContent()" runat="server" Text="Save" onclick="btnSave_Click" />
</body>

In the above code, the javascript method UpdateContent() will update the page elements with ckeditor content whenever tha Save button is clicked. Thus, on save click the requiredfield validator control will fire properly now.

"This request has been blocked because sensitive information could be disclosed to third party web sites when this is used in a GET request. To allow GET requests, set JsonRequestBehavior to AllowGet."

Very recently I have worked on asp.net MVC application. Everything is working fine for MVC v1. But when move to MVC v2 I have gotten this error-

"This request has been blocked because sensitive information could be disclosed to third party web sites when this is used in a GET request. To allow GET requests, set JsonRequestBehavior to AllowGet."

After making some r & d I have found the solution:

Reason:

In MVC v2 they block Json for GET requests (as you can tell from the error) for security reasons.

If your JSON payload:

1.Contains sensitive non-public data
2.Returns an Array
3.Responds to a GET request
4.Browser making the request has JavaScript enabled (very likely the case)
5.Browser making the request supports the __defineSetter__ method.

Then the data is vulnerable to a JSON hijacking. Typically, it's not *your* data but the data of the users of your website.

For more details about JSON Hijacking.

Solution:
1.A possible solution I found online is to set the request to "POST" method instead of "GET" method.

2.If you want to override the behavior, check out the overload for Json that accepts a JsonRequestBehavior parameter.

public ActionResult Index()
{
//Return Json result using LINQ to SQL

//###################################################
//MVC 1.0 specific implementation - A JSON Result
//is returned.
//###################################################
//return new JsonResult
//{
// Data = (from p in Product.GetProductDataList()
// where p.ColorId == colorid
// select p).ToArray()
//};

//###################################################
//MVC RC2 specific implementation - A JSON Result
//is returned, and the AllowGet property is set for
//the JsonRequestBehavior.
//###################################################
var data = (from p in Product.GetProductDataList()
where p.ColorId == colorid
select p).ToArray();

return Json(data, JsonRequestBehavior.AllowGet);
}

Thursday, January 26, 2012

Stopwatch class to determine the execution time for an application

A Stopwatch instance can measure elapsed time for one interval, or the total of elapsed time across multiple intervals. In a typical Stopwatch scenario, you call the Start method, then eventually call the Stop method, and then you check elapsed time using the Elapsed property.

If you want to measure the time required for your programs written in the C# language. This could be for a micro-benchmark or for routine and continuous performance monitoring.

Example

First sample:
In this sample you must create Stopwatch as an instance. This makes it useful in multithreaded applications or websites.

using System;
using System.Diagnostics;
using System.Threading;
class Program
{
static void Main(string[] args)
{
Stopwatch stopWatch = new Stopwatch();
stopWatch.Start();
Thread.Sleep(10000);//or do some work
stopWatch.Stop();
// Get the elapsed time as a TimeSpan value.
TimeSpan ts = stopWatch.Elapsed;

// Format and display the TimeSpan value.
string elapsedTime = String.Format("{0:00}:{1:00}:{2:00}.{3:00}",
ts.Hours, ts.Minutes, ts.Seconds,
ts.Milliseconds / 10);
Console.WriteLine("RunTime " + elapsedTime);
}
}

Second sample:
In this sample we use the StartNew method. This uses a creational design pattern to return a new instance from a static type method. It eliminates typing and simplifies your code.

class Program
{
static void Main(string[] args)
{
// Create new stopwatch
var stopwatch = System.Diagnostics.Stopwatch.StartNew();

// Do something

// Stop timing
stopwatch.Stop();

// Write the results
TimeSpan ts = stopWatch.Elapsed;

// Format and display the TimeSpan value.
string elapsedTime = String.Format("{0:00}:{1:00}:{2:00}.{3:00}",
ts.Hours, ts.Minutes, ts.Seconds,
ts.Milliseconds / 10);
Console.WriteLine("RunTime " + elapsedTime);
}
}

For more details please visits here.

SQL Server case/when type conversion problem

In my last project I wrote a query where I have to sort data based on the user input but each column in table has different data type. So to meet with this type of requirement I have used case..when block of the sql server.


Problem: Sample query

DECLARE @sortby Varchar(10)
Set @sortby = 'A1'

Select String1,String2,DateCol
from (
select 'A1','B1', GetDateTime()
union
select 'A2','B2', GetDateTime()
) As d(String1,String2,DateCol)
Order by
Case
When @sortby = 'A1' then String2
When @sortby = 'B1' then String1
When @sortby = 'Date' then Date1
End

there is not syntax error when you check for the syntax error but when execute code you find there is error

ERROR:Conversion failed when converting datetime from character string.

the problem here is first two having databype Varchar and last one having datatype DateTime. So when you executing its found that one branch having datetime so its gives error even its not executing that.

Solution

First Solution
So to avoid this problem you require to convert dateTime to the string

DECLARE @sortby Varchar(10)
Set @sortby = 'A1'
Select String1,String2,DateCol
from (
select 'A1','B1', GetDateTime()
union
select 'A2','B2', GetDateTime()
) As d(String1,String2,DateCol)
Order by
Case
When @sortby = 'A1' then String2
When @sortby = 'B1' then String1
When @sortby = 'Date' then Cast(Date1 as varchar(20))
End


Second Solution
Divide the Case when in multiple statement

DECLARE @sortby Varchar(10)
Set @sortby = 'A1'

Select String1,String2,DateCol
from (
select 'A1','B1', GetDateTime()
union
select 'A2','B2', GetDateTime()
) As d(String1,String2,DateCol)
Order by
Case When @sortby = 'A1' then String2 End,
Case When @sortby = 'B1' then String1 End,
Case When @sortby = 'Date' then Date1 End

Thursday, January 19, 2012

Html stripper (Remove Html tag)

This is a common problem when we want to show any data in gridview(asp.net) or table or repeater it breaks the page or design of the page due to html tag inside the presented date.

It will also cause the problem if we want use CKEDITOR to insert data. Because when we insert anything using rich editor it is wrap the text with <p></p>. If we want to show partial of the string it will cause page break because last </p> is missing.

So to avoid this problem we need to strip the Html tag from the string. We can do it in various ways such as regular expression and character array.

Solution 1(Good):

using System.Text.RegularExpressions;
//Remove HTML from string with Regex.
public static string StripTagsRegex(string source)
{
return Regex.Replace(source, "<.*?>", string.Empty);
}


Solution 2(Better):

using System.Text.RegularExpressions;
// Compiled regular expression for performance.
static Regex _htmlRegex = new Regex("<.*?>", RegexOptions.Compiled);

// Remove HTML from string with compiled Regex.
public static string StripTagsRegexCompiled(string source)
{
return _htmlRegex.Replace(source, string.Empty);
}

Solution 3:(Best)

//Remove HTML tags from string using char array.
public static string StripTagsCharArray(string source)
{
char[] array = new char[source.Length];
int arrayIndex = 0;
bool inside = false;

for (int i = 0; i < source.Length; i++) { char let = source[i]; if (let == '<') { inside = true; continue; } if (let == '>')
{
inside = false;
continue;
}
if (!inside)
{
array[arrayIndex] = let;
arrayIndex++;
}
}
return new string(array, 0, arrayIndex);
}

Fixed problem for continuous string(long string without space) using regular expression

Last day I have faced a problem for a long string like(adfdsfsdfdsfdsfsdafdsfsdfsdfsdfsdfsdfsdfsdfsdffdsfsdfsdfsdafsdfsdfsdfsdfsdfsdafsdf) which make my application's UI design break. So to fixed this issue I have used regular expression which insert a space after n characters.




To insert a space after every n characters:

var newString = Regex.Replace(oldString, new string('.', n), m => m.Value + " ");

Sample solution:
string longWord = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaassssssssssssssssssssssssdddddddddddddddddddddddddddddaaaaaaaaaafffffffffffffffffffffffffadfdsfsdfdsfdsfsdafdsfsdfsdfsdfsdfsdfsdfsdfsdffdsfsdfsdfsdafsdfsdfsdfsdfsdfsdafsdffdsfdsfdsfsdf";

Regex.Replace(longWord, new string('.', 16), m => m.Value + " ");


In above image it shows that regex place a space after every 16 character for that long string.

JavaScript parseInt() bug

Very recently I have faced a strange problem with JavaScript parseInt() function. It returns incorrect result when try to parse value like "08","09"...... But it works for "01" to "07".
So I have tried to find solution in community. Then find that this was a JavaScript bug.

Problem:

There is a "bug" with the parseInt JavaScript function. The bug is not something that will affect you very often, but it is something you should be aware of. We've seen the bug in every browser except Opera.

I've created a button to demonstrate the bug. The bug is that parseInt can return an incorrect value. For example, parseInt("08") results in 0 instead of 8. And parseInt("09") results in 0 instead of 9. The reason for this is because the zero in front is trying to tell the browser that this is an octal (base 8) number, and "08" and "09" are not valid octal numbers. The button below builds statements from parseInt("01") through parseInt("09") and shows what the resulting value is. But it also does parseFloat("01") through parseFloat("09"). This shows that the bug does not exist with parseFloat.

Solution:

parseInt(parseFloat(09))
Or,
parseInt(09, 10)
The "10" in the second example tells the browser that base-10 values should be used.

Hope that it will helpful for other developers.Thanks.

Method 'StartWorkflowOnListItem' in type 'Microsoft.SharePoint.WorkflowServices.FabricWorkflowInstanceProvider'

Exception: Method 'StartWorkflowOnListItem' in type 'Microsoft.SharePoint.WorkflowServices.FabricWorkflowInstanceProvider'...