Archive for April, 2008

Guide For Cross Browser Development Series 2 – Session Variables and Cookies are lost in IE 6.0

April 26th, 2008 by Sidar Ok

In the first post of this series, I tried to warm it up a bit and gave introductory information and talked a bit about the tools that we can use for developing and testing applications for cross browser compatibility. Now it is time to discuss the specific issues. Fun begins.

You are using Internet Explorer 6.0 to test your application. You have frames and framesets in your application, and everything works fine. But you notice that you loose the session intermittently, without receiving any appropriate errors. You are sure that you turned cookies on and everything.

Before suspecting your code and beating yourself up see this:

http://support.microsoft.com/kb/323752 

‘Internet Explorer 6 introduced support for the Platform for Privacy Preferences (P3P) Project. The P3P standard notes that if a FRAMESET or a parent window references another site inside a FRAME or inside a child window, the child site is considered third party content. Internet Explorer, which uses the default privacy setting of Medium, silently rejects cookies sent from third party sites.’

As you notice it basically means that ALL your cookies are going to be rejected without any prompt, including form authentication and session cookies (Remember Me functionality in your login page will not work). That’s really annoying if you notice unexpected empty strings in your application, because you receive NO errors, notification and anything like that.

For ASP.NET you need to add following code to all your pages (if you have a base page it probably is the ideal place for this)

Response.AddHeader(”P3P”, “CP=\”CAO PSA OUR\”");

If you need a quick fix you can consider to put it in your Application’s BeginRequest event in your Global.asax file or implement your own HttpModule for this to inject this header in.

Here CAO means that this is your own contact site or in other words IE 6.0, I beg you don’t delete my cookies!

We will continue talking about cross browser development, so stay tuned!

kick it on DotNetKicks.com


Share it on: These icons link to social bookmarking sites where readers can share and discover new web pages.
  • Digg
  • Sphinn
  • del.icio.us
  • Facebook
  • Mixx
  • Google
  • Blogosphere News
  • e-mail
  • YahooMyWeb
  • DotNetKicks
  • DZone

Sidar is Crossing the Browser – Guide for Cross Browser Development Series – 1

April 24th, 2008 by Sidar Ok

Ok, this is not one of the other posts devoted to blame Microsoft on not obeying the standards. I leave that area to the “debate experts” and wash my hands off. I am now looking from the poor (and pure) developer’s perspective: whether we like it or not, we have to live with it. We want our applications work in a variety of environments, regardless of the browser used. (That was the whole point of HTTP did we miss it?)

So we need to identify the areas of differences between browsers and try to fix the issues to support other browsers too.

Hence I am starting “Sidar Crossing the Browser” series in this blog. Hoping that it will be the place to pile up this PITA .

What bits of web site development have the risk of being incompatible with a type of browser?

Almost every. Html tags, cookies, script files, stylesheets – and of course add-ons and executables.

Get Equipped To Start

We know what to do so let’s proceed to how to do.

a) “Good to know”s

Since everybody can write a browser, it is almost impossible to support all browsers or all html rendering engines. So the best strategy would be just to make the majority happy. This depends on your application needs,e.g if you are developing an application for the whole internet you’ll need to take care of Internet explorer (7.0 and 6.0 mainly), Mozilla, Opera and Safari browsers. But if your clients are going to be using Linux, to be supported, then you of course don’t need to spend time on IE compatibility.

b) The Tools

Of course after modifying your code you’ll want to see that if it is working or not, and if it is not working trouble shoot it. To do this, you should be fine to install as many browsers as you can onto your operating system. But as you’ll figure, testing with Different Major Versions of a browser becomes an issue.

As you know IE 7.0 is not forcing itself to be installed on IE 6.0. But it is normally not possible to run these 2 version of IE in parallel. So here comes a brilliant tool : MultipleIE . When you run the application, a screen similar to the following is the thing you actually need :

clip_image002

Picture 1 : Multiple IE Running App Window

Debugging

OK, we have to confess that we don’t consider about browser compatibility until we bump into it – of course this is wrong but is the usual case. With the new world with AJAX and the promotion of script files, css based designs etc “view source” is not your best friend any more. In IE, even the line number you get the error is usually wrong !

Having worked much with CSS, one of the pains is nested – css and trying to find which css definition the nasty looking control is picking up. (Spending hours on trying to find the right class and at the end seeing that it is embedded in the page is not very tempting !)

So here are the tools I use for debugging :

Fiddler

Of course Fiddler rocks! Fiddler is basically an HTTP debugger from Microsoft, letting you to analyze and debug Http Requests and Http Response. This was very useful for me especially when developing AJAX applications, that the html is coming and being rendered on the fly.

The coolest thing is you can generate your own requests with the headers you want, and see the response.

Here is a snapshot of Fiddler main screen :

clip_image004

Picture 2 : Fiddler

For Internet Explorer

- Internet Explorer Web Developer Toolbar : This is the one of the best tools for web page development. It’s support for viewing the style of a selected element (you can select an element by click, so even if it is visible buy some ajax condition, you’ll be able to see the mark up) and CSS Style tracer is two of the most that I enjoy. Below you see a picture of the helper window that resides at the bottom of the page. See the DOM browser on the very left. I selected a menu item (partner & customer solutions) and seeing its properties in the window :

- clip_image006

Picture 3. Internet Explorer Developer Toolbar

One of the many cool things about this tool is that you can dynamically add properties via green button (these can even be a DOM event and call a js method).

Nikhil Kothari’s Web Application Helper

Asp.NET Architect at Microsoft, Nikhil Kothari has written an excellent tool that comes with a bunch of cool features, such as the ability to execute new scripts within the current context, debugging on the fly generated javascript and building & managing request & response objects in specific scenarios.

For Firefox

I can already hear the fans shouting FireBug name,that’s the group of which I also am a proud member. It is the best ever to provide excellent debugging and javascript management environment for FireFox. On top of the ability to inspect & edit html and javascript, you can monitor the bandwidth coming to the browser and forth.

Another cool feature is it enables javascript logging so you can see what’s happening without interfering the process.

Below is how firebug looks like after enabled in a firefox browser:

clip_image008

Picture 4: Firebug

Another excellent add on for Firefox that I have to mention here is “User Agent Switcher” by Chris Pederick. As name states, it lets you to test how your application behaves with different user agents.

For Safari

Next version of Safari is supposed to include a release version of Web Inspector. It has lots of great futures such as inspecting an element and viewing the page metrics.

clip_image010

Picture 5 : Safari Web Inspector

For Opera

Opera has a web developer tool which offers a large variety of functionalities; it is an integration of a bunch of add-ons.

clip_image012

Picture 6 : Web Development Helper for Opera

So now, we are pretty much ready to start to rock and roll. The following posts will be shorter and each one will be about a different browser compatibility issue. Don’t hesitate to let me know if you need to ask or request anything.

kick it on DotNetKicks.com

Share it on: These icons link to social bookmarking sites where readers can share and discover new web pages.
  • Digg
  • Sphinn
  • del.icio.us
  • Facebook
  • Mixx
  • Google
  • Blogosphere News
  • e-mail
  • YahooMyWeb
  • DotNetKicks
  • DZone

A Brief Introduction to LINQ to SQL

April 21st, 2008 by Sidar Ok

Introduction to LINQ to SQL

I know there are a lot of LINQ 2 SQL introductions, and you already are sick about them. So I will keep this section as brief as possible.

Over the years the community kept fancying strongly typed objects rather then not OO friendly Datatables and Datasets, Microsoft kept pushing them to go in that way. Since there are understandable reasons, (such as performance) this didn’t change the fact that in an object oriented world, whose requirements are already getting more complex and complex. Typed Datasets couldn’t be response to these requirements even it was making things easier to manage.

This approach also had a consequence of ignoring multi tier and professional real world applications (It would be more difficult to support these scenarios in a 5 minutes of drag & drop presentation!)

Lots of companies(such as CodeSmith)had seen an opportunity here, and they were damn right, so they made lots of money out of that.

So What is Linq 2 SQL and Does it fit in this picture ?

Linq 2 SQL is both an ORM and Code Generator. Although (mostly java guys) humiliate it, I see it as a great step forward for .NET environment, and has a lot of nice features. It speeds up the data managing & generating entities process (no tricks this time, really drag & drop & tweak and it works). And of course it has lots of cons which I will talk about in the later posts.

Following gives an idea where Linq 2 SQL resides in all this LINQ 2 X family :

clip_image001

                                            Figure 1.1 Linq Architecture Overview

Linq 2 SQL is coming with very easy to use tools to ease the code generation. And the generated code is surprisingly good, and using the new .NET framework 3.5 features, such as automatic properties, extension methods and lambda expressions. It is full object oriented and provides a very good level of abstraction.

Scott Guthrie has explained a while ago how to use designer in several blog posts and a very nice video . So be calm, I wont go down in that way J .

The good thing about designer is it picks up about everything that you defined in your db, tables, functions, stored procedures, primary-foregin keys and other constraints etc. It builds the object structure and relations between them based on these, and puts it into a DataContext that you specified before. You can manage your own DataContext and inherit from your DataContextBase for your architectural and business needs again, the designer tool is friendly to this approach.

To understand how LINQ 2 SQL works, understanding DataContext is essential. DataContext itself has lots of good features.

Being Aware of Context

There are 4 DataContext Constructors lets you create a data context. When you create a DataContext of your choice through designer, it creates and associates a connectionstring in settings file or app.config if it exists. Beware that if you want to replace this behaviour in configuration file (a common practice it to put it to web.config for web applications for instance) you need to make sure that a connection string with the same name exists within the current context.

But if you want to do it programmatically, you need to create the DataContext with an IDbConnection .

Understanding How DataContext Works

If I say that the LINQ 2 SQL world revolves around DataContext, I wouldn’t be much exaggerating. Our aim is to do basic insert, update and delete operations as quick & efficient as possible, so we need to understand that DatContext is the gateway to perform this goal.

DataContext is pretty flexible and enables you to work directly with objects or run your own queries / stored procedures or user functions.

1 – Working with the Objects

A cool way of using DataContext is making it to generate Insert, Update and Delete SQL statements against your data model. This works pretty well if you really know what you are dealing with. After generating your context via designer or SqlMetal code generator tool, you have your DataContext with your Entities generated and attached to it. Below is how Northwind Data Context looks like after a generation is performed :

clip_image003

                                                   Picture 1 : Northwind Entities

As you see categories table is mapped to Categories Generic Table that consists of a Category Type that’s mapped to each row.In this table class, there is a set of extension methods that you can use (we will in later posts) to construct SQL statements in a better object oriented way.

However, as you would expect, the relations between types shouldn’t be Table object or something that reminds db to us. EntitySet and EntityRef is there for this purpose. EntitySet in the context. EntitySet is a generic set of entities specified, Category in our case. It implements IList interface so there is no harm to say this is basically a list and we can use every method, including extension methods that a Generic IList can benefit.

If the relationship is one-to-one between the tables then an EntityRef is created for that entity.

Just to keep in mind that these two are NOT serializable, we are going to discuss this issue in later posts.

There are 2 cool features of data context that we need to know here: Object Tracking and Deferred (or Lazy) Loading.

- Object Tracking

This is the change tracking system that Linq to SQL provides. If you want your queries to be generated on the fly automatically, this is the system that provides it. However, if you only do want to select and perform read only operations and don’t want to track any changes, disabling it will improve the retrieval performance.

To disable it, you need to set ObjectTrackingEnabled property of your context to false. The default is true.

The golden rule working with object tracking is : “Data Context needs to be aware of every insert, update and delete to generate appropriate sql statement”. You need to tell DataContext what objects to insert, what to delete and what to update.

You can work with a DataContext that has ObjectTrackingEnabled in 2 ways : Connected and Disconnected.

In connected mode, everything is easy, and world is a very nice place to live. You add, delete, update from/on context and these are all trivial operations: You just manage the collection, add, update or remove an object, and call the magical context.SubmitChanges() method, and that’s it. Your statements are generated and executed. Everyone is happy.

But things aren’t as simple and this is usually not the case. In a service oriented, n-tier world, or long running sessions, keeping DataContext alive is an unreasonable hope. So in disconnected mode you need to tell explicitly what you need to insert, update and delete.

You do this with a bunch of method provided in the generic table that is associated . I will try to show how to use these methods in action in another post but to name them here :

For Insertions => InsertOnSubmit for a single entity, InsertAllOnSubmit for collections.

For Deletions => DeleteOnSubmit for a single entity and DeleteAllOnSubmit for collections.

For Updates => You need to use Attach for a single entity and AttachAll for collections. You’ll see that Attach methods have 2 overloads, one with the entity and the other one with asModified boolean. Setting this to true means that your entity will be included in the generation process even if you made any changes on that.

The way only way of informing that a disconnected object had been changed is through Attach methods. For instance, If you want to delete an object that is not in the context, you first need to attach it to the context. Otherwise, your delete will fail with this message

System.Data.Linq.ChangeConflictException: Row not found or changed

We are doing these to inform context about object tracking states. Each method changes the object’s state to a corresponding value to be able to generate the appropriate query at the end.

- Lazy Loading (Deferred Loading)

In LINQ, if you query for an object, you get the object that you requested. Nothing else, no child relations or back references are loaded. This is achieved because DeferredLoadingEnabled is true by default. You can set this to false if you want to disable it, but that is usually not the best thing to do. We usually need to customize what to load and what not to load.

In this sense, there is a property called LoadOptions of type DataLoadOptions in System.Data.Linq namespace.

The code below illustrates an example usage of this.

1:  private IQueryable<Category> GetDescribedCategoriesWithPicturesAndProducts()
2:  {
3:     using (NorthwindDataContext context = new NorthwindDataContext ())
4:     {
5:         System.Data.Linq.DataLoadOptions options = new System.Data.Linq.DataLoadOptions();
6:         options.LoadWith<Category>(ct => ct.Picture);
7:         options.LoadWith<Category>(ct => ct.Products); // first level
8:         options.LoadWith<Product>(p => p.Supplier);
9:         options.LoadWith<Product>(p => p.Order_Details); // second level
10:   
11:         return context.Categories.Where<Category>(ct => !string.IsNullOrEmpty(ct.Description));
12:      }
13:  }

As you already noticed, you can submit a request to load second or Nth level loading (I would appreciate if you let me know if you know the upper limit of this N). One good thing to keep in mind here is to avoid cyclic loads.

2 – Running Plain Text-Based SQL Queries

One other usage of LINQ is to use context as a gateway to run your predefined sql statements.

a) ExecuteCommand

You can call DataContext.ExecuteCommand to achieve this.

1:  using (NorthwindDataContext context = new NorthwindDataContext())
2:  {
3:     int rowCount = context.ExecuteCommand(“SELECT * FROM CATEGORIES”);
4:  }

b) ExecuteQuery

You can call ExecuteQuery generic method and map the results to an entity of your choice as follows.

1:  using (NorthwindDataContext context = new NorthwindDataContext())
2:  {
3:    IEnumerable<Category> categories =   

context.ExecuteQuery<Category>(“SELECT * FROM CATEGORIES”);
4:  }

This was the end of the introduction. Hope it helped you a bit to figure the concepts out and get started. In later posts I will try to get into more advanced topics and create a real world application using LINQ in a multi tiered environment in conjunction with WCF.
kick it on DotNetKicks.com

Technorati Tags: ,,,


Share it on: These icons link to social bookmarking sites where readers can share and discover new web pages.
  • Digg
  • Sphinn
  • del.icio.us
  • Facebook
  • Mixx
  • Google
  • Blogosphere News
  • e-mail
  • YahooMyWeb
  • DotNetKicks
  • DZone

Chato’s 26 th birthday

April 17th, 2008 by Sidar Ok

Today, is a big day, a doom for humanity. The reason why the world is not a good place any more was born today 26 years ago.

If Chato had become a human rights activist instead of being a .net nerd, the world would be a better place to live. But anyway, it is not so bad that I had a chance to know this guy.

Happy birthday chato, wish you all happiness, and wish I was there to cut you a piece of birthday cake !

Share it on: These icons link to social bookmarking sites where readers can share and discover new web pages.
  • Digg
  • Sphinn
  • del.icio.us
  • Facebook
  • Mixx
  • Google
  • Blogosphere News
  • e-mail
  • YahooMyWeb
  • DotNetKicks
  • DZone

Just started blogging !

April 7th, 2008 by Sidar Ok

Hey you ! After a long period of resisting, here I am, starting to my technical blog. Great for a such a lazy guy like me, isn’t it ? I will try to share my experiences, thoughts and some of my work (dammit, why cant I charge you for this ? ) here and hopefully receiving some feedbacks from you.

I will mostly be talking about enterprise software development, aspects, architecture, development technologies like ASP.NET, ADO.NET, XML Web Services, SQL, WCF, MS AJAX etc, and methodologies.

Yes this one is a nerdy blog so get outta here you social guy and drink some beers ! We have to spend some time here with the rest of loosers.

Hope to see you around !

Sidar Ok

Share it on: These icons link to social bookmarking sites where readers can share and discover new web pages.
  • Digg
  • Sphinn
  • del.icio.us
  • Facebook
  • Mixx
  • Google
  • Blogosphere News
  • e-mail
  • YahooMyWeb
  • DotNetKicks
  • DZone