Programmer’s Backdoor Trap
Today I’ve encountered something that made a programmer happy but made me sad.
He had to pull data out of Data Warehouse and use it for his system.
Later, he was informed that DWH personnel made his life easy: They’ve decided to write the data into his own database so he wouldn’t have to work so hard.
Unfortunately this news made him happy, and therefore he went on with it, which made me even sadder.
What’s wrong with it?
Well, allot.
1. It opens a backdoor to the system because you have to give permission to another to your
database.
2. It’s hard to maintain. What happens when you deploy\move your database to another
server? Starts making calls to the other system’s owner so he will update his own?
3. Let’s assume you gave the permissions so the other system’s will update your database,
What happens when it fails to do so? Who will know? (a hint, not you, not at first at least).
4. What happens when you need to change your DB schema? How many system owners
will you need to inform? do you wish to keep track? (you probably won’t).
There are more reasons but I think I can leave you with the one’s written above, feel free to come up with some more on your comments.
That’s was a classic programmer’s trap
It is very tempting to have your job easier at the beginning but the price is opening a backdoor to your system, which is too high.
Fortunately it took only a while to persuade everyone that it is not the way to do things. Now, exchanging data between the databases was replaced by reading the data through a web service.
That's was one system I’ve caught at development stage. This also exists on many production systems at the customer I work for. They mainly let the integration system to write on various system’s databases which I struggle hard to prevent.
If you, as a developer, a team leader or an architect see this trap, please identify it, don’t fall and don’t let others fall into it.
KnockoutJS–Dependencies

One of the things we’ll probably need is to be able to have dependency tracking in our bounded data. For example – if we have a customer’s list, we’d like to see the customer’s orders whenever we click on a customer. In this post I’ll demonstrate how to do it using the dependentObservable function of KnockoutJS
Let’s look at the following JavaScript code:
var viewModel = {
customers: ko.observableArray([]),
selectedCustomer: ko.observable(),
orders: ko.observableArray([]),
order: function () {
return { itemName: "", description: "", unitPrice: 0, units: 0 }
},
customer: function () {
return { firstName: "", lastName: "", joinedDate: new Date(), orders: ko.observableArray([this.order()]) }
},
addOrder: function () {
this.orders.push(this.order());
},
addCustomer: function () {
this.customers.push(this.customer());
},
setSelectedCustomer: function(customer)
{
this.selectedCustomer(customer);
}
};
In here, I’ve declared two data structures: customer and order. I’ve also exposed two data members: customers and orders which have the types above respectively. I’ve also exposed the selectedCustomer data-member which will be used for us in the future.
Now, let’s go to our HTML content.
In here we’ll have two tables – one for customers and one for orders. We’ll use templates for our data binding so it will look like that:
<body>
<table>
<thead>
<tr>
<th>
First Name
</th>
<th>
Last Name
</th>
<th>
Joined Date
</th>
</tr>
</thead>
<tbody data-bind="template : {name: 'customersTemplate', foreach: customers}"></tbody>
</table>
<button data-bind="click: function() {viewModel.addCustomer()}">Add customer</button>
<table>
<tbody data-bind="template: {name: 'ordersTemplate', foreach: orders}">
</tbody>
</table>
<button data-bind="click: function() {viewModel.addOrder()}">Add Order</button>
<script type="text/html" id="customersTemplate">
<tr data-bind="click: function() {viewModel.setSelectedCustomer($data)}">
<td>
<input type="text" data-bind="value: firstName" />
</td>
<td>
<input type="text" data-bind="textvalue: lastName" />
</td>
<td>
<input type="datetime-local" data-bind="value: joinedDate"/>
</td>
</tr>
</script>
<script type="text/html" id="ordersTemplate">
<tr>
<td>
<input type="text" data-bind="value: itemName" />
</td>
<td>
<input type="text" data-bind="value: description" />
</td>
<td>
<input type="text" data-bind="value: unitPrice"/>
</td>
<td>
<input type="text" data-bind="value: units"/>
</td
</tr>
</script>
You can notice from the HTML another three things:
1. There’s a button to add customer, when clicked it calls the addCustomer function
2. There’s a button to add order, when clicked it calls the addOrder function.
3. Whenever a customer row clicked, the setSelectedCustomer function is called.
All setSelectedCustomer does is assign the customer who’s row was clicked on, to the
selectedCustomer data member. The dependentObservable function will do the rest.
All of that is achieved using the event bindings of KnockoutJS
Now, Let’s have dependencies between the selected costumer and it’s orders:
ko.dependentObservable(function () {
if (this.selectedCustomer()) {
this.orders(this.selectedCustomer().orders());
}
}, viewModel);
What does it do? whenever the selectedCustomer member is changed, it assigns it’s orders to the orders data member, and that’s how we’ve achieved dependencies between the customer and it’s order.
In the function of it’s first parameter, we can have all our dependency tracking code (and that’s all our dependency tracking). The word “this” inside the function refers to the view-model we’ve provided on the second parameter.
Summary
Dependency tracking is something we’d probably want when having data binding with complex data (parent-child structures for example), having master-details view or even computed values. The dependentObservable function of KnockoutJS allows as to do so in a very easy manner. All we have to do is plant our code in the function at it’s first parameter and well… that’s it.
Here is the full example:
<!DOCTYPE HTML>
<html>
<head>
<title></title>
<script type="text/javascript" src="../scripts/jquery-1.6.2.min.js"></script>
<script type="text/javascript" src="../scripts/jquery.tmpl.min.js"></script>
<script type="text/javascript" src="../scripts/knockout-latest.js"></script>
<script type="text/javascript">
var viewModel = {
customers: ko.observableArray([]),
selectedCustomer: ko.observable(),
orders: ko.observableArray([]),
customerFirstName: ko.observable(),
order: function () {
return { itemName: "", description: "", unitPrice: 0, units: 0 }
},
customer: function () {
return { firstName: "", lastName: "", joinedDate: new Date(), orders: ko.observableArray([this.order()]) }
},
addOrder: function () {
this.orders.push(this.order());
},
addCustomer: function () {
this.customers.push(this.customer());
},
setSelectedCustomer: function (customer) {
this.selectedCustomer(customer);
}
};
ko.dependentObservable(function () {
if (this.selectedCustomer()) {
this.orders(this.selectedCustomer().orders());
}
}, viewModel);
</script>
</head>
<body>
<span data-bind="text: customerFirstName"></span>
<table>
<thead>
<tr>
<th>
First Name
</th>
<th>
Last Name
</th>
<th>
Joined Date
</th>
</tr>
</thead>
<tbody data-bind="template : {name: 'customersTemplate', foreach: customers}">
</tbody>
</table>
<button data-bind="click: function() {viewModel.addCustomer()}">
Add customer</button>
<table>
<tbody data-bind="template: {name: 'ordersTemplate', foreach: orders}">
</tbody>
</table>
<button data-bind="click: addOrder">
Add Order</button>
<script type="text/html" id="customersTemplate">
<tr data-bind="click: function() {viewModel.setSelectedCustomer($data)}">
<td>
<input type="text" data-bind="value: firstName" />
</td>
<td>
<input type="text" data-bind="value: lastName" />
</td>
<td>
<input type="datetime-local" data-bind="value: joinedDate"/>
</td>
</tr>
</script>
<script type="text/html" id="ordersTemplate">
<tr>
<td>
<input type="text" data-bind="value: itemName" />
</td>
<td>
<input type="text" data-bind="value: description" />
</td>
<td>
<input type="text" data-bind="value: unitPrice"/>
</td>
<td>
<input type="text" data-bind="value: units"/>
</td
</tr>
</script>
<script type="text/javascript">
ko.applyBindings(viewModel);
</script>
</body>
</html>
KnockoutJS–Event binding

After binding the data into our page, we wish to be able to create an interactive page. This means that we want to be able to add some behavior to our view-model, triggered by an event on the page. (A button being clicked for example).
You can bind to the click binding the same as you bind to the value only that now it’s expects a parameter-less function. In case you have a method that expect parameters you can have a binding expression like that:
<button data-bind="click: function() {viewModel.setSelectedCustomer(yourParameter)}">Set customer </button>
On that binding you’re operating a function on your view-model triggered by the button click.
The click binding is not restricted to buttons of course, you can triggered event for every clickable HTML element.
If you wish to bind to another events such as mouseover, keypress etc. you need an event-binding. It’s syntax is slightly different but there isn’t a big change.
All events you wish to bind are to be kept inside one block ({event1: handler, event2: handler }) every handler is a parameter-less function however you can bind to an expression the same as the click binding above.
See below, example for event binding with mouseover and mouseout:
<input type="text"
data-bind="value: channelUrl, event: {mouseover: function() {viewModel.title('Get Items')}, mouseout : function() {viewModel.title('')}}" />
Summary
In order to add interactivity to our page (otherwise it won’t be an application) we need to bind events to functions on our view-model. The function expected to be bound are ones without parameters however we can bind to an expression by having the event name, followed by the function() keyword and then, our Javascript expression.
When the event is fired, the bounded function on our view-model will execute. On that function we ought to change another bounded data, call server side by AJAX and so on.
KnockoutJS–Templates
After being introduced
to KnockoutJS concept and go to know the
basics of data-binding with Observable and
observableArray, let’s move on to how to work with templates and our collection to them.
In this post I’ll explain how to bind a collection with template.
Prerequisites
Now, adding to KnockoutJS Prerequisites (jQuery 1.4.2 and above) you’ll need another Javascript library: jQuery.tmpl . You can download this version or visit the project page for latest version.
HTML as script
The templates are HTML content written inside of a script tag, and it looks like that:
<script type="text/html" id="itemsTemplate">
<!-- Your HTML template content here -->
</script>
The script tag has an ID, it will be used to associate the template to a place in a document where it should be presented
Associate the template
The following HTML element (Unordered list in here) will be associated to the template, as below. the template binding has tow main attributes: name to associate with the template (corresponds to the ID attribute of the template above) and the foreach which corresponds to the observableArray member of the view-model we’d like to bind.
<ul data-bind='template: {name: "itemsTemplate", foreach: rssItems} '>
</ul>
Now, the HTML element is associated with a template and bounded to a data member.
Let’s have a look inside the template:
Binding inside the template
Binding inside the template is very similar to regular binding, only that we bind to and item within a collection instead of binding to a data member inside our view-model.
In order to bind data where there is no suitable type for us (Assign a css class to an input element according to the item’s data) we can use the ($data) expression which points at the whole bounded item and have a JavaScript expression with it, as seen at the example below: (For our XAML friends – let’s say that this is a converter)
<input type="text" data-bind="css:{selectedCustomerClass : ($data) == viewModel.selectedCustomer()}"/>
Summary:
After heaving simple binding we’d like to bind a collection and as we did in every other technology (ASP.Net, WPF, WinForm you name it…) we need a template to bind it to.
Heaving included the template JavaScript library of jQuery.tmpl, we can now write our own templates and bind it to our observableArray .
KnockoutJS–The Observables
On my previous post, I’ve demonstrated a simple example
of data binding between our HTML content (view) and our Javascript (view-model). On this post I’ll dive, not deeply, to the javascript on our view-model and explain some of it’s basics, the ones that causes it to act as a real view-model.
ko
KO stands for Knockout and it will be used whenever we use the KnockoutJs library
ko.observable()
This function, of the KnockoutJs library notifies the view of every change of the bounded member’s value. Please note that in Javascript you don’t have actual properties (unlike C#) and you cannot use simple assignment syntax to invoke get method. Therefore, whenever you change member you use <member name>(<new value>). The library upon invocation will reflect the change on the browser’s screen.
Binding in KnockoutJs is two-way. (There is no binding-mode like XAML), meaning that the user changes the values whenever the member is bounded to an editable element (textbox, checkbox, combo-box etc.).
The observable method can be invoked with no parameters or with a value of which the member is initialized with.
For collections we have the observableArray who can have an empty array as parameter ([]) or with some items (syntax: ko.observableArray('[{item1, item2, …]}) );
More about collections when I talk about templates.
ko.applyBindings
That’s the command that set’s the HTML page’s data-context (XAML term once again). It get’s our view-model as a parameter.
Summary:
In this post I’ve reviewed some of the basic code of the view-model javascript. For every member we wish to bind we have to declare it as ko.observable or as ko.observableCollection for collections. At the end we should invoke the ko.applyBindings function which actually binds the data to the HTML element, or set the HTML page’s data context if you prefer XAML terminology.
Note: The ko.applyDataBindings() should come after the HTML content, otherwise it won’t know where to bind the data to.
KnockoutJs – MVVM in HTML & Javascript
Previously I’ve posted about MVVM and Silverlight, It seems long ago, before Microsoft has begun focusing on HTML & Javascript as a client development platform.
One of the things I’ve cherished the most about XAML related technologies development was the ability to completely decouple behavior and UI using MVVM. I didn’t know about any possibility to implement the same pattern on HTML & Javascript based applications.
In order to do so, we can now use KnockoutJS, a Javascript library based on jQuery that allows as to write an MVVM application with HTML and Javascript.
The first thing we’ll look for in MVVM is how to bind data from the View-Model. Our view-Model in this case will be a Javascript section separated from our HTML and looks like it doesn’t know anything about it (as MVVM should be). The view-model can certainly be on a separate file, however we’ll lack the intellisences doing so.
So, How we do it?
1. Obtain jQuery, you can do it by download it or linking to it directly. Note: You cannot use the version supplied by Visual studio 2010 because it’s minimum version is 1.4.2 (VS supplies 1.4.1)
2. Download KnockoutJs, latest javascript file. You can find the latest version on this download page.
3. Link your HTML file to both jQuery and KnockoutJs files
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script type="text/javascript" src="Scripts/jquery-1.6.2.min.js"></script>
<script type="text/javascript" src="Scripts/knockout-latest.js"></script>
<title></title>
</head>
<body>
<!-- Your Page layout HTML (view) here -->
<script>
//Your View-Model code (javascript) here
</script>
</body>
</html>
Note: The view-model code has to be after your HTML content.
After having our page set-up, let’s have some javascript at the view model.
on our HTML content let’s make a span, and bind it’s text content to a property in the view-model:
<span>The time now is : </span>
<span data-bind="text: today"></span>
Let’s look at our view-model code. There we’ll create a view-model, add a data member called “today” (which we’ve bind our span text to) and with a simple javascript code have it updated every second
var viewModel =
{
today: ko.observable(),
updateDate: function () {
viewModel.today(new Date());
}
}
}
//Init data
viewModel.today(new Date());
// call updateDate every second
setInterval(viewModel.updateDate, 1000);
//Sets the page's data context
ko.applyBindings(viewModel);
Now, when browsing our page, we’ll see the clock at the span.
Summary:
This is, of course, a very simple example of how we can bind, but imagine the possibilities now of having an entire application with javascript and HTML, contacting the server through AJAX and not through for submission. You can now separate completely your javascript code from your UI design just as you did in WPF/Silverlight working with XAML & C#.
Of course, there’s still need for templates, handle events such as button click or text changes but this is for later posts.
A problem I’ve encountered at a customer I work for was very strange behavior regarding
the WSDL being generated by it’s service. The WSDL didn’t contain any class property, moreover it did contain private members of a class being exposed by the service.
Let’s have a look on a repro:
1. Here’s the class being exposed:
namespace SerializationDemo.Entities
{
[Serializable]
public class SerializableEntity
{
public int SomeProperty { get; set; }
}
}
2. Here’s the class schema representation as being exposed in WSDL
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:tns="http://schemas.datacontract.org/2004/07/SerializationDemo.Entities" elementFormDefault="qualified" targetNamespace="http://schemas.datacontract.org/2004/07/SerializationDemo.Entities">
<xs:complexType name="SerializableEntity">
<xs:sequence>
<xs:element name="_x003C_SomeProperty_x003E_k__BackingField" type="xs:int"/>
</xs:sequence>
</xs:complexType>
<xs:element name="SerializableEntity" nillable="true" type="tns:SerializableEntity"/>
</xs:schema>
3. Here’s the class as generated on client side
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Runtime.Serialization", "4.0.0.0")]
[System.Runtime.Serialization.DataContractAttribute(Name="SerializableEntity", Namespace="http://schemas.datacontract.org/2004/07/SerializationDemo.Entities")]
[System.SerializableAttribute()]
public partial class SerializableEntity : object, System.Runtime.Serialization.IExtensibleDataObject, System.ComponentModel.INotifyPropertyChanged {
[System.NonSerializedAttribute()]
private System.Runtime.Serialization.ExtensionDataObject extensionDataField;
private int SomePropertyk__BackingFieldField;
[global::System.ComponentModel.BrowsableAttribute(false)]
public System.Runtime.Serialization.ExtensionDataObject ExtensionData {
get {
return this.extensionDataField;
}
set {
this.extensionDataField = value;
}
}
[System.Runtime.Serialization.DataMemberAttribute(Name="<SomeProperty>k__BackingField", IsRequired=true)]
public int SomePropertyk__BackingField {
get {
return this.SomePropertyk__BackingFieldField;
}
set {
if ((this.SomePropertyk__BackingFieldField.Equals(value) != true)) {
this.SomePropertyk__BackingFieldField = value;
this.RaisePropertyChanged("SomePropertyk__BackingField");
}
}
}
public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged;
protected void RaisePropertyChanged(string propertyName) {
System.ComponentModel.PropertyChangedEventHandler propertyChanged = this.PropertyChanged;
if ((propertyChanged != null)) {
propertyChanged(this, new System.ComponentModel.PropertyChangedEventArgs(propertyName));
}
}
}
As seen from the WSDL and from the auto-generated client code, instead of getting the property SomeProperty of SerializableEntity you get the class's private field, which was the compiler-generated backing field (_x003C_SomeProperty_x003E_k__BackingField) of the automatic property.
Why did it happened?
SerializableAttribute indicates that all fields of the class marked Serializable can be serialized, including of course the private ones. However, it doesn’t say anything about the properties.
When getting the entity schema, the WCF invokes the the default formatter, having the class marked Srializable only (without DataContract) causes all fields to be serialized but no property is. Therefore we’ll see no property but private member.
That’s because the Serializable attribute aimed at binary serialization which serializes the data and not the methods. And data stored in fields and not in properties that are nothing more than methods accessing fields.
Solutions:
1. One solution is to have all service methods exposing the Serializable marked type use the XmlSerializerFormat simply by marking the method’s declaration at the service contract. This will cause the WSDL to be generated using XML serializer and will ignore the Serializable attribute and will serialize all public members including read-write properties.
This solution is good when the entities being exposed are in external DLLs or we can’t change their code for some reason.
2. At the exposed entities, add the DataContract attribute with DataMember attribute on each member we’d like to expose. After doing so, the DataContractFormat (which is the default format being used) will ignore the Serializable attribute and use only the DataMember attribute to serialize the schema.
Summary:
Serializable attribute aimed at binary serialization, which uses all data in the class which stored in fields and not in properties. Therefore, colliding with DataContract serialization it produces an odd behavior of serializing all fields, including private ones and no property.
Using XmlSerializerFormat on the method declarations or DataContract on the very entity being exposed can solve the problem.
Handling application states on Windows 8
As heard on BuildWindows and over and over agai
n
throughout the sessions there is new application
state called Suspended.
When using the computer in Metro style mode the application
changes state to “suspended” when the user moves to another
application. This is mainly for power saving since Windows 8 targeted to portable devices such as tablets.
So, when developing an application we would like to do some operations when changing states. Let’s see how an application written in C# will handle it:
protected async void OnSuspending(object sender,
Windows.ApplicationModel.SuspendingEventArgs args)
{
SuspendingDeferral deferral = args.SuspendingOperation.GetDeferral();
await SuspensionManager.SaveAsync();
deferral.Complete();
}
the OnSuspending method is set as the event handler for the application suspending event. it receives a SuspendingEventArgs which has the data for the suspending event. one important part of it is the SuspendingDeferral class which manages the suspension operation.
the code calls a method called SaveAsync which saves the application state somewhere. then the deferral variable notifies the system that the application has done what it has to do and can be suspended.
another thing to keep in mind is that we see here allot of asynchronous operations. that’s because one of the main concerns on windows 8 is to have the ui as much responsive as possible. however, instead of placing a callback before calling an asynchronous operation we use the new await keyword, where’s the callback is actually the code coming after the async call.
you can use the await keyword before every method that has another keyword which is async. you can see that the onsuspending method has that keyword but also the saveasync as seen below:
static async public task saveasync()
{
await Windows.System.Threading.Threadpool.RunAsync((wiargs) =>
{
Suspensionmanager.SaveimplAsync().Wait();
}, Windows.System.Threading.WorkItemPriority.Normal);
}
And what about going back from suspension mode? well, that’s the same as being launched. therefore thee app.xaml class has overridden the OnLaunched method, than it simply does the opposite and restores the application’s state:
protected override async void OnLaunched(LaunchActivatedEventArgs args)
{
if (args.PreviousExecutionState == ApplicationExecutionState.Terminated)
{
// Do an asynchronous restore
await SuspensionManager.RestoreAsync();
}
//Set the main window
Window.Current.Content = new MainPage();
Window.Current.Activate();
}
apart from launching the application’s start page – you can see that when the application launches it checks for it’s state and restores when it the application somehow got terminated (aka – suspended).
the very implementation of RestoreAsync and SaveAsync differs of course between one application and another, that’s why i’ve chosen not to paste the entire implantation here on the code.
Summary:
Windows 8 tries not to encourage applications running side by side. therefore on the metro mode when switching from one application to another, the application you switched from becomes suspended, and simply won’t run.
therefore, upon suspension, you need to save your last state and use it upon re-launching to take the application where the point it was left off.
And – a little apology towards the end, This is my first post from my new Windows8 Tablet. It doesn’t work that well with Windows Live Writer so this post might not look so well. As being said on the Build keynote – this is a developer preview, not an RTM…
Windows 8 For developers - what’s new?
Today in BUILD, it was all about Windows 8 and it seems like a very big change from what we’ve known so far.
And what is the big change?
JavaScript & HTML have become a native part of windows application. That is something completely new for us. HTML comes out of the browser for windows 8 and it can be a UI for a “regular” windows application.
The Metro style applications, meaning that application doesn’t stand alone but it is a part of “Application web” as put by the keynote various speakers.
It means that if you write some text in a word processor and you want to translate it using a translation app, you can pick the translation app after selecting text instead of Copy –> Open translation app –> Paste –> translate.
This is done by contracts. These contracts defined by the OS and each application can choose whether and how to implement them.
This means that the applications share content, not only by the clipboard. The applications share content using contracts.The contract are predefined by the OS (Picker, Share & Search contracts)
To see the whole story let’s take a look at the “Windows 8 Platforms and tools” below:

The WinRT API is a native API but it can be easily used by C# & VB (easier than win32 API)
but moreover, by JavasScript. From this picture we can also see that a XAML application
can be written in C/C++ rather than just .Net language, that’s because XAML was re-implemented natively and now can serve native code as well.
To sum things up: Building application for windows has changed. The most important news, if you ask me, is the contracts that allows application to speak with one another (aka Metro-Style apps). The second most important is the ability to develop application using HTML & Javascript. There are of course some other things like the new App store, the fact that the apps I’ll post more about the development tools as the convention continues.
It’s BUILD time
Today I’m off to BUILD/Windows among a delegation of almost 20 experts from SELA.
As everyone, I’m looking forward for this conference. Hope to see you there.
You can find us with our orange shirts.
See you there,
Ran.
A very strange phenomenon I came across while developing web application for a customer.
A Jpeg formatted picture wasn’t shown on IE8 browsers, while shown on others (Firefox 5, Chrome 12, IE9).
The browser displayed an empty placeholder with a red ‘X’ as it does when not finding an image. This led as to searching for causes such as wrong URL, communication problems etc. .
After a while, one of our IT personnel have discovered that when requesting the image, there’s some XML inside the content delivered in the response.
The content injected looked like that:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>com.apple.print.PageFormat.PMHorizontalRes</key>
<dict>
<key>com.apple.print.ticket.creator</key>
<string>com.apple.jobticket</string>
<key>com.apple.print.ticket.itemArray</key>
<array>
<dict>
<key>com.apple.print.PageFormat.PMHorizontalRes</key>
<real>72</real>
<key>com.apple.print.ticket.stateFlag</key>
<integer>0</integer>
</dict>
</array>
</dict>
<key>com.apple.print.PageFormat.PMOrientation</key>
<dict>
<key>com.apple.print.ticket.creator</key>
<string>com.apple.jobticket</string>
<key>com.apple.print.ticket.itemArray</key>
<array>
<dict>
<key>com.apple.print.PageFormat.PMOrientation</key>
<integer>1</integer>
<key>com.apple.print.ticket.stateFlag</key>
…
This content was injected somehow, by a graphic editor at the marketing company we’re working with, to the image file. It has been handled well at all new browsers but wasn’t
in IE8 which is still wide spread browser we have to support.
What can you do to solve this?
Simply open the same file in some basic graphic editor (Paint.Net will do, Windows Paint won’t) and re-save it. The content seen above will be removed.
In conclusion: An odd behavior by some graphic editor costs us some working hour. The solution for this is very simple and involved no coding. I hope this small post saved you the headache we’ve got.
Changing namespace in ASP.NET Web-Form
When converting VS Web-Site to VS Web application One of the problem you might stumble upon is class name collisions. It is due to the fact that web-site, because of it’s compilation mode, can have the same class name (and no namespace) on different files because they will end up in different assemblies.
On web-application though, it is a different story. All classes ends up in the same assembly
and therefore we have to name them differently. You will encounter this problem when the compiler will say that '<YourPage>' already defines a member called 'Page_Load' or some other method /property/ field while you won’t see it anywhere else on the same file.
So, What do you need to do?
1. Add namespace to the code behind, do so for both aspx.cs and aspx.designer.cs files.
2. On the markup file (.aspx) page directive, change the “Inherits” attribute so it will corresponds to the new type name (<namespace>.<class>).
What not to do?
Do not use the option of overall changing the namespace. It will add namespace to all
classes by the same name and keep your name collisions in tact.
Summary
When converting some (not so) good old VS Web Site to VS Web Application you might encounter some class name collision. You can solve this collision by changing
namespaces however you should be very cautious while doing so.
Code snippet for session wrapped properties
Long ago, I’ve written about session manager class which provides type safety while
accession Session variables.
One of it’s foundations is the very properties we write that wraps the session variables.
These properties tends to be very much alike and therefore I’ve written a code snippet
for them.
It’s shortcut is propsess , you can copy it from below
<?xml version="1.0" encoding="utf-8" ?>
<CodeSnippets xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">
<CodeSnippet Format="1.0.0">
<Header>
<Title>Session based Property</Title>
<Shortcut>propsess</Shortcut>
<Description>
Code snippet for property with get and set accessors
that wraps a session variable
</Description>
<Author>Ran Wahle</Author>
<SnippetTypes>
<SnippetType>Expansion</SnippetType>
</SnippetTypes>
</Header>
<Snippet>
<Declarations>
<Literal>
<ID>type</ID>
<ToolTip>Property type</ToolTip>
<Default>string</Default>
</Literal>
<Literal>
<ID>name</ID>
<Default>PropName</Default>
<ToolTip>Property name</ToolTip>
</Literal>
<Literal>
<ID>sessionKey</ID>
<Default>SessionKey</Default>
<ToolTip>Session Key</ToolTip>
</Literal>
<!--<Literal>
<ID>controlInnerProperty</ID>
<Default>Text</Default>
<ToolTip>Control Inner property</ToolTip>
</Literal>-->
</Declarations>
<Code Language="csharp">
<![CDATA[
/// <summary>
/// Put summary for $name$
/// </summary>
public $type$ $name$
{
get
{
return Session["$sessionKey$"] as $type$;
}
set
{
Session["$sessionKey$"] = value;
}
}
]]>
</Code>
</Snippet>
</CodeSnippet>
</CodeSnippets>
Enjoy 
Using Session manager class in Global.asax
Long ago, I’ve written about Session Manager class. The class purpose was to wrap
session variables in properties and gain type safety to them.
In this class we’ve added a Session property with get accessor, which wraps the
HttpContext.Current.Session. Everything went well until I’ve encountered the need
to use this class on Session_End method in global.asax
Global.asax is not a regular Http Handler and therefore it doesn’t hold an HttpContext
This means that when going to the Session we’ve received our good old
NullReferenceException.
On global.asax there is access to the session variables but through it’s own Session
property.
So, what can we do?
One and not so recommended solution is skip the use of Session Manager and go directly
to the session variables in the old fashion way. That’s how you skip the type safety
provided by this class. This is not so recommended because of the type safety being broken
and code being replicated instead of being reuse
The other approach is to create Session property on the Session Manager class and set
it from the constructor. We’ll allow setting it from the constructor because we wouldn’t
want any unexpected corruption of this property.
And that’s how the constructor and the session property will look like:
public SessionManager(HttpSessionState session)
{
Session = session;
}
public virtual HttpSessionState Session
{ get;
private set;
}
All other properties we might want to put there, should stay exactly the same.
The Session property is virtual because if we would want to use it from our application’s pages
we’d like to inherit and use HttpContext.Current.Session
In order to use it from our regular pages (the one that holds HttpContext during their Load -->
Render lifecycle) we can inherit and override the Session property.
The code of the derived class will look like that:
public class CurrentContextSessionManager : SessionManager
{
public CurrentContextSessionManager()
:base(null)
{
}
public override HttpSessionState Session
{
get
{
return HttpContext.Current.Session;
}
}
}
Now we can gain back our type safety from SessionManager class. Here is
some example of how we can use the base class (a cleanup mechanism called
from Session_End).
protected void Session_End(object sender, EventArgs e)
{
ProductsBL productBL = new ProductsBL();
SessionManager sessiongManager = new SessionManager(this.Session);
productBL.ClearShoppingCart(sessiongManager.ShoppingCart);
}
Where Shopping cart is a property wraps a session variable.
Summary
Our Session Manager class is good to go from every page in our application until
we have to do some actions with it from Async Http handlers such as global.asax
In these cases we have to set our own Session property. For all other pages we
can use a derived class that gets it’s session from HttpContext.Current.Session.
At the end, everyone points at the same session variables, and our type safety
won’t harm.
404.2 and , ISAPI restriction and Web Service Extension
A common and very misleading http error is the status with code 404.2 .
It is misleading because it belongs to the 404 family which may indicate
that the resource was not found, however this error indicates that the
server has blocked our request by it’s lockdown policy.
The web server lockdown policy’s job is restrict the requests to a known
and valid pages / resources. For example, this is very rare to find servers
that allows you to run executable programs remotely by HTTP requests.
Another common scenario of request blocking is for known extension,
registered to an ISAPI executable which was not allowed by the server’s
configuration. The most common scenario I’ve encountered was that ASP.NET
4.0 ISAPI was not allowed. (occurs on machines installed initially without
.Net 4.0) One good examples for this scenario can be seen on Gil Fink’s post.
One other common scenario I’ve encountered was heaving to host Magic
application on IIS. Magic web application required a special ISAPI executable.
In order to do so, we have to add new extension and add the Magic’s ISAPI
DLL to it.
How can we configure these settings?
IIS 6: In here it is called Web Service Extensions, You can find it by clicking
it’s corresponding folder. You can allow or prohibit each extension.

In case of new extension, you need to press on the “Add new web service extension”
(circled above), and add the required file(s). You can also add / remove files and
and allow / prohibit each one of them.

IIS7: On that IIS, it called ISAPI & CGI restrictions. You can choose it by
clicking once on the server’s name, and then from feature view selecting
ISAPI & CGI restrictions (circled below)

The registration list looks a bit different from the extensions list on IIS6,
in here wee see every file on that list along with it’s description
By looking at the figure below you can see some description that repeat
themselves (like Web Service Extension in IIS6 that have more than one file).

Summary:
In this post we’ve seen the connection between IIS lockdown
(HTTP error No. 404.2), Web Service Extension and ISAPI
Restrictions. In fact, we’ve seen that installing the appropriate
ISAPI executable is not enough, we have also to allow it.
We’ve seen how to allow it on both IIS6 and IIS7
More Posts
Next page »