Thursday, September 30, 2010

Grid View – Ilist & Dataset

we all know that with c# 3.5 & now 4, we have generics and LINQ – which makes it incredibly easy to Bind grid View to ilist that you get from a LINQ query when you use the entity data model.

However, After binding this data to Grid, you want to use the template columns to update the individual rows, also you want to save the data on post backs. I found that Ilist is not the best way to go (very much depends upon situation). Here the old friend – Dataset comes to rescue.

You can bind the dataset, Cache it and update the columns after every update. [ Think about this only for Selects] as you loose entity connections when you go the dataset way (There are ways to keep this dataset and entity in Sync but i will not talk about it now)

 

So, here is a small extension function to Ilist

[Uses Reflection ]

 

public static DataSet GetDataSet<T>( IList<T> list)
    {
        Type elementType = typeof(T);
        DataSet ds = new DataSet();
        DataTable t = new DataTable();
        ds.Tables.Add(t);

        //add a column to table for each public property on T
        foreach (var propInfo in elementType.GetProperties())
        {
            Type ColType = Nullable.GetUnderlyingType(propInfo.PropertyType) ?? propInfo.PropertyType;

            t.Columns.Add(propInfo.Name, ColType);
        }

        //go through each property on T and add each value to the table
        foreach (T item in list)
        {
            DataRow row = t.NewRow();

            foreach (var propInfo in elementType.GetProperties())
            {
                row[propInfo.Name] = propInfo.GetValue(item, null) ?? DBNull.Value;
            }

            t.Rows.Add(row);
        }

        return ds;
    }

Tuesday, July 20, 2010

REST and SOAP

As we all know that this is more of a Architectural decision, there are few things that I would like to keep handy while deciding among two. These should help me taking the right design decision for right type of end point.

Here I am trying to Simplify the WCF stuff. There are 2 Major type of services and clients that you would need to know for majority of the Services consumers.

- For using WS* and all the high end transactional features of WCF, USE SOAP

Easy to consume – sometimes
Rigid – type checking, adheres to a contract

- For light weight, simple XML, if you can take care of security user REST

Lightweight – not a lot of extra xml markup
Human Readable Results

Examples -

REST - Twitter, Yahoo’s web services , Flickr, del.icio.us, pubsub, bloglines, technorati best is? – Craigslist !

SOAP - Google is consistent in implementing their web services using SOAP, with the exception of Blogger, which uses XML-RPC.

Both? -  eBay and Amazon

Now REST vs SOAP - 

1 API Flexibility & Simplicity – Rest is simple and SOAP is not

2. Rest APIs are lightweight – less bandwidth – SOAP requires Bunch of XML wrapped around where as for 4 digit stock price we dont need this overhead :)

3. Security- Posts using SOAP across organizational boundaries are safe, However RESTs Get are can always be consider safe because technically it can not modify an data. SOAP typically uses the POST to communicate with service. analyzing HTTP command in firewall is simple and REST can benefit out of it. However, to do this with SOAP you have to open the SOAP packet which makes it resource consuming. There is no way to know just by looking at the request if it wants to get or delete etc.

On the other hand, think about sending SSN as parameter in Query string. there rest goes down. Again Large data  becomes difficult

4. Authentication and Authorization – For SOAP its all upto developer. For REST – through use of certificates, common identity mgmt services like LDAP developers can make use of this

Clients – easier to create a Client for SOAPs that REST but this depends on how the framework is. Testing and troubleshooting is very easy with HTTP API than SOAP as building request is far simpler.

Caching – easer with REST as it is consumed with GET, intermediate proxies can cache the responses easily. 

Server Side complexity – SOAP is easier to code on server side, nearly all high level langs and framework makes it easy to create a  SOAP endpoints. With REST you are exposing objects methods as HTTP API and requires serialization of output to XML. Also you need to map the URI path to specific handlers.

Wednesday, June 30, 2010

Async Calls in C# – Should I blog about this?

Well, this may be for me to keep track but thought it would be usefull as I see more more and junior developer who do not understand the importance of Async programming and make blocking calls and it is frustrating especially in Web or Online apps.

There are too many frameworks available that you can take advantage of today. Another great video here I just wanted to give a very very simple steps to get this whole asynchronous business going. I assume that you know all the delegate concepts. Even if you dont know, dont worry, you really dont need to.

------------------------------------------------------------------------------------------------------

Scenario 1- Simplest of all. You want to call a function without blocking the main thread and dont care about return value dont want to know when called function finishes execution

a. Create a delegate –

 public delegate string  GetName (string myname);     –> note that you generally know what function to call and so you can decide on the delegate signature.

b. Then create object of delegate

GetName nameGetter = new GetName(GetMyRealName); <— GetMyRealName  is the actual function we want to call in Async manner.

c. Then Simply do

IAsyncResult result = nameGetter.BeginInvoke(name,null,null); <- Param 1 is parameter to original function, first null is Callback (explained latter) and last is object state (explained later)

A method GetMyRealName will be called without blocking your main thread. This is as simple as that.

*note that if your called function throws exception it will not come up

------------------------------------------------------------------------------------------------------

Scenario 2-  You want to call a function without blocking the main thread, At the same time do something else and then see what is the result of your async function

------------------------------------------------------------------------------------------------------

Scenario 3-  You want to call a function without blocking the main thread, then have another function called when your called function finishes execution

Tuesday, June 22, 2010

Showing HTML as is in Text box for ASP.NET 4.0

1. Simple thing but may get very annoying sometimes :)

2. you stored an HTML in DB. you want to show it as in Text box.

3. Note – Label and literal controls will show them as they encode by default. However Text box will not.

4. Fix – use HTML encode for the text box

ASP.NET Validate Request with .NET 4.0 – some breaking news

From old days -

1.  if you want to store HTML in DB – may be script you encode and store.

2. While post back you will get “potentially dangerous Request.Form value was detected” – To fix this you go ahead and make validateRequest=false on your page.

3. With .NET 4.0 this will not work Because this is now in the BeginRequest phase of a HTTP request, pages with validationRequest=”false”  will still get the dreaded message

Fix?

Set requestValidationMode=”2.0″ in which case the page setting will apply.

Put <httpRuntime requestValidationMode=”2.0″ /> in your web.config’s <syste.web> section

good article can be found here

Wednesday, June 16, 2010

SQL Server 2010 Express SP1 full install OR SQL Server 2010 Managements studio Express install After VS 2010

 

Invoke or BeginInvoke cannot be called on a control until the window handle has been created.

Hello all,

I had this nasty thing that came in my way when trying out SP1 for SQK 2k8 after VS 2010 install in Win 2k8 or Win7

Here are the steps

1. Start the install.

2. Let the UAC prompt come up and then say yes.

3. Install will start. Keep clicking next ok etc..the goal is to get to the Error dialog box

4. Once you get the error dialog, stop and do not click “OK”.  Instead go to c:"{GUID} and then copy the folder to some location. If you click ok the temp folder will be cleaned up

SQL Setup

5. Run the setup from this folder. For Win2k8, “Run as Administrator”

6. There are some more solutions given here but this worked for me 99% of the time

Thursday, January 07, 2010

Case sensitive "=" or like clause in SQL Query analyzer

In your query in query analyzer - Put this next to the case sensitive word that you querying


COLLATE SQL_Latin1_General_CP1_CS_AS


For Ex  - 

select * from EntryMain where customer = 'XXXxxxxXXXX' COLLATE SQL_Latin1_General_CP1_CS_AS



Here XXXxxxxXXXX is case sensitive.


You can also set the Collation to default using system store procs permanently.