Thursday, December 6, 2012

Silverlight key event modifier key

Just wanted to share a quick tips, in WPF , and WINForms many times we needed to use the modifier key, and so does it needed in silverlight for taking special input and tab navigation, reverse tab navigation etc.

well no more talk just a code snippet

//modifier key in silverlight
bool isShift = (Keyboard.Modifiers & ModifierKeys.Shift) == (ModifierKeys.Shift);


Cheers!

Friday, November 9, 2012

String replace: case insensitive issue

I one of my product i build a file renaming system. User has many options to rename file. Among those we have some string replace cases.

At first we tried String.Replace Method (System) to replace texts. Below code snipped is given how things look, the code is simple and may seems different as it taken from different context.

public string ApplyRule(FileRenamePreview preview)
{
if (string.IsNullOrEmpty(SearchText))
return preview.NewFile;

if (IsFirstOnly == false)
{
var changedFileName = preview.NewFileName.Replace(SearchText, ReplaceText);
preview.NewFileName = changedFileName;
}
else
{
var regex = new Regex(SearchText);
preview.NewFileName = regex.Replace(preview.NewFileName, ReplaceText, 1);
}

return preview.NewFile;
}

Now the client wanted the replacement as such so that the search string should be case insensitive. Trick is simple we have to use regex in place of normal string replace, but with Regex option set to ignore case. Below code segment is given to show how it is done.


public string ApplyRule(FileRenamePreview preview)
{
if (string.IsNullOrEmpty(SearchText))
return preview.NewFile;

if (IsFirstOnly == false)
{
var changedFileName = Regex.Replace(preview.NewFileName, SearchText, ReplaceText,RegexOptions.IgnoreCase);
preview.NewFileName = changedFileName;
}
else
{
var regex = new Regex(SearchText,RegexOptions.IgnoreCase);
preview.NewFileName = regex.Replace(preview.NewFileName, ReplaceText, 1);
}

return preview.NewFile;
}

Last trick, while searching for text for first index, there is option to state ignoring case we have to use it.


int iIndexOfBegin = strSource.IndexOf(strBegin,StringComparison.InvariantCultureIgnoreCase);

Until next time.

Friday, November 2, 2012

Create custom project file using c# object serialization. Its easy! only few step and works perfectly.

Introduction

Recently I did couple of projects where I needed to save objects in a file and then load back to the system for some processing. I thought of couple of solutions but at last stick to a simpler solution. In one of our project we did something like the bellow solutions.

Step 1: Serialize the related class in separate files.

Step 2: Use Open source zip technology to zip the files in a single file.

Step 3: Rename the zip file with custom extension for instance “filename.xte”

Serialize a collection of class objects

In this post I have some classes to show In case of a simple serialization context. Below I have my data class named “Bond” with only 5 properties. Below the code snippet is given how the class looks like.

using System;

namespace PrizeBonds.Objects
{
[Serializable]
public class Bond
{
public long Id { get; set; }
public long Serial { get; set; }
public string Owner { get; set; }
public DateTime CreatedDate { get; set; }
public DateTime ModifiedDate { get; set; }
}
}


Next I have a class which will be serialized and saved in a file. In this class I have a List of Bond class, and of course it  implements the ISerializable interface. Below a code snippet is given to show the the code looks like.


using System.Runtime.Serialization;

namespace PrizeBonds.Objects
{
[Serializable()]
public class ObjectToSerialize:ISerializable
{
private List<Bond> _bonds;

public List<Bond> Bonds
{
get { return _bonds; }
set { _bonds = value; }
}

public ObjectToSerialize()
{
}

public ObjectToSerialize(SerializationInfo info, StreamingContext ctxt)
{
_bonds = (List<Bond>)info.GetValue("Bonds", typeof(List<Bond>));
}

public void GetObjectData(SerializationInfo info, StreamingContext ctxt)
{
info.AddValue("Bonds", _bonds);
}
}
}


The final piece of work that to the all kind of lifting is the serialize, below the code snippet to is given to demonstrate the idea. The responsibility of the below code is to serialize and de-serialize the objects.



using System.IO;
using System.Runtime.Serialization.Formatters.Binary;

namespace PrizeBonds.Objects
{
public class Serializer
{
public void SerializeObject(string filename, ObjectToSerialize objectToSerialize)
{
Stream stream = File.Open(filename, FileMode.Create);
var bFormatter = new BinaryFormatter();
bFormatter.Serialize(stream, objectToSerialize);
stream.Close();
}

public ObjectToSerialize DeSerializeObject(string filename)
{
Stream stream = File.Open(filename, FileMode.Open);
var bFormatter = new BinaryFormatter();
var objectToSerialize = (ObjectToSerialize)bFormatter.Deserialize(stream);
stream.Close();
return objectToSerialize;
}
}
}



In first method of above code  we pass the file name and the object that need to serialize, it serialize the object with binary formatter and save in the file that is provided. In second method we provide a file name where the serialized file is it desterilize the file and build the wrapped object.


using System.Windows.Forms;

namespace PrizeBonds.Objects
{
public class BackUpManager
{
public void LoadRule()
{

// Configure open file dialog box
var dlg = new OpenFileDialog { FileName = "Prize Bond Manager",
DefaultExt = ".pbm", Filter = @"Prize Bond Manager Files (.pbm)|*.pbm" };

// Show open file dialog box
var result = dlg.ShowDialog();

// Process open file dialog box results
if (result == DialogResult.OK)
{
// Open document
var filename = dlg.FileName;
var serializer = new Serializer();
var deSerializeObject = serializer.DeSerializeObject(filename);
var bonds = deSerializeObject.Bonds;
var dal = new DAL();
foreach (var bond in bonds)
{
dal.AddBond(bond);
}
}
}

public void SaveRule()
{
var dal = new DAL();
var bonds = dal.GetList();
if (bonds.Count == 0)
{
const string message = @"You do not have any bonds to Save, thus I am unable "
+ @" to save any bonds. Please add some bonds before Saving";
MessageBox.Show(message);
return;
}

var dlg = new SaveFileDialog { FileName = "Prize Bond Manager",
DefaultExt = ".pbm", Filter = @"Prize Bond Manager Files (.pbm)|*.pbm" };

// Show save file dialog box
var result = dlg.ShowDialog();

// Process save file dialog box results
if (result == DialogResult.OK)
{
// Save document
string filename = dlg.FileName;
var serializer = new Serializer();
var objectToSerialize = new ObjectToSerialize { Bonds = bonds };
serializer.SerializeObject(filename, objectToSerialize);
}
}
}
}


 


In above code I have a class named “BackUpManager” where we have two method, in first method using file open dialog and using Serializer class we saved the file. And in second method using Serializer class we saved a file, and in both case we have our own extension.


Conclusion


In the above short article we have seen a simple serialization scenario. And I explained why we need it. And also shown some classes to demonstrate the idea.


Reference



  1. http://tech.pro/tutorial/618/csharp-tutorial-serialize-objects-to-a-file

  2. http://msdn.microsoft.com/en-us/library/system.runtime.serialization.iserializable.aspx

Friday, October 26, 2012

A simple prize bond manager: old technology still works!

Introduction

The story begin with a simple problem, my father-in-law having some problem with his prize bonds. He has several prize bonds and each quarter government publish the prize bond lottery draw and he had to take each bond then go through the numbers. And it became hectic job for him.

Few days ago,  in a family dinner he told me about his problem, and asked me can I make a simple program so that his problem can be resolved. I kind of smiled and told him that I would be able to write something for him. Last weekend I sit and wrote some thing for him. Then I thought lets write an article about it, should be fun!.

My problems:

  1. It needs to be very simple.
  2. I can’t force him to use advance technology.
  3. Need to have some backup of data.
  4. Easy deployable.

It needs to be very simple

Decided to keep it very simple, so no login what so ever. One Main Screen where every thing is listed. A data add screen. And a simple match bond number screen to finding winning numbers. One interesting thing is that my father-in-law keep buying bonds for all the family members. so need to back up the data and ability to load backed up data.

I can’t force him to use advance technology

After little thought I decided to choose old technologies, because my client knows computer but i guess fancy advance technology might scare him off and my client will runway. And I believe it or not he use “windows xp” so what ever available with windows update.

Need to have some backup of data

Should be simple pretty simple steps to add delete and modify data. In case  user manage to screw thing up there should be a simple process with which he can backup the data and also restore data. Of course we have SQL Server and Enterprise manager to do that, but we don’t what clients to mange all those things. So I better use simple xml to generate back up.

Easy deployable

Important part, I don’t want to install anything in my pc beside the software, second the steps should be damn easy. kind of one client installer.

First thing First

Before writing any code I setup a open source project in github to keep my code. It’s a open source only because I want people to some how criticize me about my code and learn some thing out of it. Created my visual studio project. Now I have VS2012, and VS2010, I chose “VS2010” and as framework I chose “.net framework 2.0”.

Below the github project location is given. You guys can download and see what’s there if you want.

https://github.com/munnaonc/PrizeBondManager.git

Win forms 2.0 , .net framework 2.0 project

Alright, what ever I thought just gave me another shot to use some old technology, should be fun. After all the necessary code the solution explorer looks like the below screen shot.

image

Figure: Initial Project Structure in Solution explorer

To keep the data I have added a Microsoft SQL Server Compact Database also known as “.sdf” database named BondDB.sdf. Created a single table. In below screen shot the table structure is given.

image

Figure: Initial Project Structure in Solution explorer

For data retrieve and saving used one of the oldest technology that is typed dataset. Below screenshot gives you an idea of that work. In the dataset we have a custom query for the dataset named “GetDataBySerial” which returns the prize bond with serial number.

image

Figure: Initial Project Structure in Solution explorer

Wrapping Up the Coding

I added main feature as CRUD of Bonds, Backup Data, Load Data and of course Match a bond number, to find out if we have a winner or not. 

Without any user interface brush-up the application looks like the bellow screen shot. pretty bad right. We would make it presentable in future i guess, for the time being the idea is to get the application to my client quickly.

image

Figure: Main Application First Look

Data Layer codes for CRUD is given bellow

using System;
using System.Collections.Generic;
using System.Data;
using PrizeBonds.BondDBDataSetTableAdapters;

namespace PrizeBonds.Objects
{
public class DAL
{
public List<Bond> GetList()
{
var tBondTableAdapter = new t_bondTableAdapter();
var tBondDataTable = new BondDBDataSet.t_bondDataTable();
tBondTableAdapter.Fill(tBondDataTable);
var dataRows = tBondDataTable.Select();
return GetBonds(dataRows);
}

private static List<Bond> GetBonds(IEnumerable<DataRow> dataRows)
{
var bonds = new List<Bond>();
foreach (DataRow row in dataRows)
{
try
{
var bond = new Bond
{
Id = (Int64)row["ID"],
Serial = (Int64)row["Serial"],
Owner = row["Owner"].ToString(),
CreatedDate = (DateTime)row["CreatedDate"],
ModifiedDate = (DateTime)row["ModifiedDate"]
};
bonds.Add(bond);
}
catch (Exception exception)
{
exception.ToString();
}
}
return bonds;
}

public void AddBond(Bond bond)
{
var tBondTableAdapter = new t_bondTableAdapter();
tBondTableAdapter.Insert(bond.Serial, bond.Owner, bond.CreatedDate, bond.ModifiedDate);
}

public void DeleteBond(long id)
{
var tBondTableAdapter = new t_bondTableAdapter();
tBondTableAdapter.Delete(id);
}

public List<Bond> GetBondBySerial(long serial)
{
var tBondTableAdapter = new t_bondTableAdapter();
var bondDataTable = tBondTableAdapter.GetDataBySerial(serial);
if (bondDataTable.Rows.Count > 0)
{
return GetBonds(bondDataTable.Select());
}
return null;
}

public void UpdateBond(Bond bond)
{
var tBondTableAdapter = new t_bondTableAdapter();
var tBondDataTable = new BondDBDataSet.t_bondDataTable();
tBondTableAdapter.Fill(tBondDataTable);
var tBondRow = tBondDataTable.FindByID(bond.Id);
tBondRow.Owner = bond.Owner;
tBondRow.Serial = bond.Serial;
tBondRow.ModifiedDate = bond.ModifiedDate;
tBondTableAdapter.Update(tBondRow);
}
}
}


Created single object to manage and the application, named “bond”


using System;

namespace PrizeBonds.Objects
{
[Serializable]
public class Bond
{
public long Id { get; set; }
public long Serial { get; set; }
public string Owner { get; set; }
public DateTime CreatedDate { get; set; }
public DateTime ModifiedDate { get; set; }
}
}


 


Add, Update and match Bond serial


Below a very simple Add Bond window code is given. Its a win form window with tool window border style and displayed as a modal dialog.


image


same window is displayed with some property modified, to update the data also.


public void SetData(Bond dataBoundItem)
{
_updateBondCandidate = dataBoundItem;
txtOwner.Text = _updateBondCandidate.Owner;
txtSerial.Text = _updateBondCandidate.Serial.ToString(CultureInfo.InvariantCulture);
}


below the update window is given.


image


Below match bond window is given.


image


Code for Add update bond



private void UpdateBond()
{
_updateBondCandidate.Owner = txtOwner.Text;
_updateBondCandidate.Serial = Convert.ToInt64(txtSerial.Text);
_updateBondCandidate.ModifiedDate = DateTime.Now;

var dal = new DAL();
dal.UpdateBond(_updateBondCandidate);
this.Close();
}

private void AddNewBond()
{
var bond = new Bond
{
Serial = Convert.ToInt64(txtSerial.Text),
Owner = txtOwner.Text,
CreatedDate = DateTime.Now,
ModifiedDate = DateTime.Now
};
var dal = new DAL();
dal.AddBond(bond);
this.Close();
}






code for match bond


private void btnMatchBond_Click(object sender, EventArgs e)
{
if (ValidData())
{
var dal = new DAL();
var bonds = dal.GetBondBySerial(Convert.ToInt64(txtSerial.Text));
if (bonds == null)
{
lblMessage.Text = @"No match found!";
lblMessage.ForeColor = System.Drawing.Color.Red;
}
else
{
lblMessage.Text = @"Success! match found! You are a winner!";
lblMessage.ForeColor = System.Drawing.Color.Green;
}
}
}


private bool ValidData()
{
if (string.IsNullOrEmpty(txtSerial.Text))
{
ShowValidSerialMessage();
return false;
}
char[] charArray = txtSerial.Text.ToCharArray();
foreach (var val in charArray)
{
if (char.IsDigit(val) == false)
{
ShowValidSerialMessage();
return false;
}
}
if (txtSerial.Text.Length != 7)
{
ShowValidSerialMessage();
return false;
}
return true;
}

private void ShowValidSerialMessage()
{
MessageBox.Show(@"Please enter 7 digit valid Prize Bond Serial");
txtSerial.Focus();
}

private void btnCancel_Click(object sender, EventArgs e)
{
Close();
}

private void txtSerial_KeyPress(object sender, KeyPressEventArgs e)
{
char keyChar = e.KeyChar;
if (keyChar.Equals('\r'))
{
btnMatchBond_Click(sender,new EventArgs());
}
}



Save and Load Bond Data


For saving and loading data used old serialization concept. Below the code for saving and loading bond data is given.


using System.Windows.Forms;

namespace PrizeBonds.Objects
{
public class BackUpManager
{
public void LoadRule()
{

// Configure open file dialog box
var dlg = new OpenFileDialog { FileName = "Prize Bond Manager",
DefaultExt = ".pbm", Filter = @"Prize Bond Manager Files (.pbm)|*.pbm" };

// Show open file dialog box
var result = dlg.ShowDialog();

// Process open file dialog box results
if (result == DialogResult.OK)
{
// Open document
var filename = dlg.FileName;
var serializer = new Serializer();
var deSerializeObject = serializer.DeSerializeObject(filename);
var bonds = deSerializeObject.Bonds;
var dal = new DAL();
foreach (var bond in bonds)
{
dal.AddBond(bond);
}
}
}

public void SaveRule()
{
var dal = new DAL();
var bonds = dal.GetList();
if (bonds.Count == 0)
{
const string message = @"You do not have any bonds to Save, thus I am unable "
+ @" to save any bonds. Please add some bonds before Saving";
MessageBox.Show(message);
return;
}

var dlg = new SaveFileDialog { FileName = "Prize Bond Manager",
DefaultExt = ".pbm", Filter = @"Prize Bond Manager Files (.pbm)|*.pbm" };

// Show save file dialog box
var result = dlg.ShowDialog();

// Process save file dialog box results
if (result == DialogResult.OK)
{
// Save document
string filename = dlg.FileName;
var serializer = new Serializer();
var objectToSerialize = new ObjectToSerialize { Bonds = bonds };
serializer.SerializeObject(filename, objectToSerialize);
}
}
}
}



In future release I would try to improve the look and field of the application. since the purpose of the application is only to match and keep data. And of course the application will be used only in once a month so investing huge time to make it more stunning won't be  a good idea., but still will invest some amount of time.


Conclusion


In this short article we have built a small application for managing prize bond with some of the old technology exists in ms world. Hope you would like it. Please drop comment if you like it and don’t forget suggest me improvement tips.

Friday, October 19, 2012

SDF Database: Re Create objects if you missed setting primary key as identity

I was developing a demo application, as database I chose to add “.sdf” local database file. I added some columns and set primary key. Some how I forgot to set the identity property of primary key.

Went back to the same interface and try to modify the table schema and set identity property. End up with the following error.

image

I thought setting some property for instance “Prevent Saving changes that require table re-creation. In Options->Database Tools-> Table and Database Designers will do the job.

image

But it didn’t, Later what I did is very bad and didn’t feel any good about it. I cleared the table. Deleted the old ID field. And re-create the same ID column with right property again.

I would appreciate if any body help me on this issue to edit a primary key identity property without deleting or clearing the data.

Friday, October 12, 2012

Asp.net: Required Field Validator with DropDownList

Today I want to share a very simple stuff That I learned while working, its kind of a silly learning, but hopefully will help someone someday. I want to make sure that a DropDownList is been selected before submitting a form. In asp.net we have a control for validation name “RequiredFieldValidator”, till now I have seen using this with only textbox. Below an example is given.

<asp:TextBox runat="server" ID="txtNumber" Width="200px"></asp:TextBox>
<asp:RequiredFieldValidator ForeColor="red" runat="server" ID="rfvNewTrackingNumber"
ControlToValidate="txtNumber" ErrorMessage="* Please type number">
</asp:RequiredFieldValidator>


But we can actually use this required field validator with DropDownList as well. Below another example is given for using with DropDownList


<asp:DropDownList runat="server" ID="ddlMethods" AppendDataBoundItems="True" Width="205px">
<asp:ListItem Value="0">Select Method</asp:ListItem>
</asp:DropDownList>
<asp:RequiredFieldValidator ForeColor="red" runat="server" ID="rfvNewMethod"
ControlToValidate="ddlMethods" ErrorMessage="* Please select method" InitialValue="0">
</asp:RequiredFieldValidator>



Note that in ListItem we have assigned Value=0 and in RequiredFieldValidator InitialValue=0 that is the main trick. If you have binding code in c# please make sure you also Set DataValueField.


Until next time.

Friday, October 5, 2012

ProjectName.xml in project folder. What? Why?

Looks like it’s a documentation related file. How I got this file? I converted a project from c# to vb.net. Conversion process worked pretty well. When I tried to check in the codes I keep seeing an un versioned file name [ProjectName].xml

At first I thought it’s a dll xml but later found out that its not necessary at all to run my project, I deleted it and build it again. works file but the file again got generated. Then looking at the build configuration I found the solution.

image

Its XML documentation file. To switch off the auto file creation all we have to do is uncheck the “XML Documentation file” checkbox of Build Tab of project configuration.

That’s it, the file will not get generated after you build again.

Thursday, September 27, 2012

DBNull check and some other “Tips” from VB.net to c# project

In my previous blog post I have shared an easy tool to convert vb.net project. I have done a successful conversion of my projects data Layer from vb.net to c#, turned out it was awesome and less painful. So far every thing seems okay.

Then I found a small anomaly. In project reference I can see that “Microsoft.VisualBasic” library is referenced. That doesn’t sound right. And I deleted the reference and recompile the project. Some of the class thrown some compile error, and I had to fix them manually.

image

And today, I want to share those learning with the community. If you “Google” c# to vb.net cheat sheet you would get some very good cheat sheets.

VB.net Information.IsDBNull

There is my first lesson: When I deleted the “Microsoft.VisualBasic” I found out this little piece of code Information.IsDBNull:

protected static object SafeDisplayValue(object Value)
{
if (Information.IsDBNull(Value))
{
return null;
}
else
{
return Value;
}
}

So what's the equivalent c# code? bellow.


protected static object SafeDisplayValue(object Value)
{
if (Convert.IsDBNull(Value))
{
return null;
}
else
{
return Value;
}
}

Pretty interesting right, why IsDBNull check got into System.Convert namespace. Any way a good lesson learned.


Constants.vbNewLine


image


Any guess? yes that’s right “Environment.NewLine”


DateAndTime.Today


image


Yes that’s right DateAndTime.Today = DateTime.Now


I have more to share will share in next post.

Thursday, September 20, 2012

An easy tool to convert vb.net project to c# project in a flash

I would like to share a very interesting and helpful tool that made my life easier and hope in some corner another developer will be beneficial with it.
Recently we had a solution from one of our customer where we had around 50 project mixed and matched with VB.net and c# projects. It was getting hectic for our developers to switch context and syntax.
I finally took liberty to find out an easy way to convert the projects. With little bit of goggling I would this awesome tool that made my developer’s life easy.

VB.Net to C# Converter 3.02

image
It you can choose to select one single file or entire project or even a solutions, isn’t it great. After proceed with the conversion project you would see some warning and and possible conversion error. Those are easily handballed.
It took only 1 hour or so to convert a project with all kind of migration. I removed the old vb.net project and then add back the c# project. fixed the project references. That’s it.

Thursday, September 13, 2012

Visual Studio 2012 Web publisher Wizard messed up!

Hi guys want to share a tittle experience while testing some new feature of visual studio 2012, its one of the oldest feature, but found a bug today. Bellow I shared the screen shot.

image

Ah… looks kind of smashed right?, How did it get there, few simple steps actually,

Step1: Right Click on Web project and select “Publish” to lunch the publish wizard.

Step 2: Click on Click on the drop down and will find a new option called “<New…>”

Step 3: Now click on the <New…> this will bring out a window like bellow

image

Step 4: Now don’t put anything on the text box of the “New Profile” dialog , rather click on “Cancel”

Step 5: Now you would see the connection , settings, and preview tab got enabled.

Step 6: Click on Preview tab, you would see that the window is kind of messed up.

Hope it would be fix soon.

Until next time , cheers!

Monday, September 10, 2012

WOW, We can now debug browser specific right from our VS

Hi Guys, I kind of got excited and sharing it with the community, if you have different browser installed in your machine you can now debug web application as browser specific.

Bellow I have shared a screen shot with with browser selection menu while debugging a web application. 

image

Me like it!. Cheers!

How to resolve “_doPostBack is undefined” JavaScript error in IE10?

Today I am going to share a small piece of information, most probably all of you know it, still sharing it as it caused significant amount of time killing on our development team.

The problem started when we noticed no submit button is working in ie 10 in one of our development project. further more our client identified this bug as showstopper which raised the importance level of the issue to critical for the project. Hence we decided to take a look at this issue quickly.

After few minutes of testing we didn’t noticed any problem that can cause this issue, Later we enabled “Display a notification about every Script Error” in IE 10 and then we quickly find out the issue.

image

Then immediately the problem got visible to all of us. there is what the script error looks like.

image

What is the problem?

According to Scott Hanselman

“There is a bug in the browser definition files that shipped with .NET 2.0 and .NET 4, namely that they contain definitions for a certain range of browser versions. But the versions for some browsers (like IE 10) aren't within those ranges any more. Therefore, ASP.NET sees them as unknown browsers and defaults to a down-level definition, which has certain inconveniences, like that it does not support features like JavaScript. “

What is The solution?

There are two fixes for this problem

  1. Machine-wide fixes
  2. Site-only fixes

Machine-wide fixes

Please visit Hanselman blog for more information on this,

According to Mr. Hanselman

“We're releasing a hotfix that will fix these, which you'll be able to get to via some KB articles. These KBs with fixes are live and are the best way to update your system. The fixes solve the browser-detection issue forever for all sites on a machine. These will be rolled up into future versions of the framework and will eventually also be on Windows Update.

What the fixes do is update the ie.browser and firefox.browser files in \Windows\Microsoft.NET\Framework\<version>\Config\Browsers with new and future-proofed versions of these browser definitions. Nothing else is affected.”

 

Site only fixes

Go to http://nuget.org/packages/App_BrowsersUpdate, and copy the command and use nuget console to install right browser files.

The command is given bellow.

PM> Install-Package App_BrowsersUpdate

Make sure you have nuget package manager and then run the command from

image

As a Result two browser file will be added in App_Browsers folder.

image

Now if you deploy your application again you will see that every thing is working file. Cheers!

Reference

http://www.hanselman.com/blog/BugAndFixASPNETFailsToDetectIE10CausingDoPostBackIsUndefinedJavaScriptErrorOrMaintainFF5ScrollbarPosition.aspx

Thursday, September 6, 2012

How to resolve asp.net resend confirm with a wired technique?

Introduction

Today I want to share a small piece of information that I learned about Resend confirmation, window of browsers. Frist I thought that this is a default feature of all browser and can not be bypassed, but I was very wrong about it. Yes there is a real and technically sound way to over come this problem.

image

the problem

First lets discuss what actually happens. Lets say we have a button in our asp.net page and an event handler for that button. Upon clicking on the button we change the text of the textbox. pretty straight forward requirement. and the code is relatively simple.

Code for the button handler is given bellow:

using System;

namespace AspDotNetFormReSend
{
public partial class Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{

}

protected void Button1Click(object sender, EventArgs e)
{
TextBox1.Text = "Button Clicked!";
}
}
}

Clicking on the button works perfect. And get same result each time I click on it. But what happens when I try to refresh the browser with F5 Key or Reload Context menu or browser button. It simply throws a confirmation window asking user to confirm to resend the browser information once again.


How to resolve Resend?


Pretty Simple solution indeed, after googling for a few minutes found couple of suggestion and all of them saying pretty much same thing, “do a Response.Redirect to same page once again”, this will resolve the issue. Well I put the idea into text and the result is amazing.


Modified code for button and page load is given bellow:


using System;

namespace AspDotNetFormReSend
{
public partial class Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
var httpCookie = Request.Cookies["Action"];
if (httpCookie != null)
{
string action = httpCookie.Value;
if (string.IsNullOrEmpty(action) == false && action.Equals("Button_Click"))
{
TextBox1.Text = "Button Clicked!";
//Response.Cookies["Action"].Expires = DateTime.Now.AddSeconds(-100);
}
}
}
}

protected void Button1Click(object sender, EventArgs e)
{
Response.Cookies["Action"].Value = "Button_Click";
Response.Cookies["Action"].Expires = DateTime.Now.AddSeconds(100);
Response.Redirect("Default.aspx");
}
}
}


What we did here is to set what button action we want to perform in cookie and then do a Redirect in the same page. On Page_Load event I captured button action from cookie and then performed the desired changes in the textbox. Note that if you want to perform any action just once you should remove the cookie right after you used it.


Advantages


This works pretty great even if you are having a stateless web site, means no session state and view state. One more advantage is that if you navigate from page to page, since you set the action on cookie upon return to the same page you would get same data you kept few minutes or hours ago without pressing action button. Use the cookie smartly for more innovative interactions.


There are some down side also, but lets keep them hidden for now, and enjoy the moment thinking we have resolved the Resend issue.


Conclusion


In this short article we have seen how to resolve browser resend issue using cookie and Redirect to same page technique, please leave a comment for suggestion and criticism.


Looking forward to share more about this in future.

Friday, August 31, 2012

Visual Studio 2012 got rid of all unnecessary things!

I must say that I am not that much excited with the release of Visual Studio 2012, as I must learn everything from scratch again, in fact need to figure out what has changed since 2010. Once again I must confess that I liked vs 2010 more than vs 2012, let see where it goes as I would be exploring visual studio in coming weeks.

image

Only required project are in the window now Open-mouthed smile. No more lots of project template, but still we have one very interesting option now we can directly use online templates.

image

Man! why is this black and white crappy look, may be because of performance, once again I like vs 2010 more. I will create a web application now and see what is the difference.

Did anyone noticed we have still the web site creation feature in vs2012.

image 

Believe it or not web site template is not more improved and equipped with lot of modern technologies, I kind of sounds stupid but my feeling is funny and I can not express properly. Hope this will rock the world of Microsoft based technology developers.

Cheers!.

Thursday, August 16, 2012

How to manipulating master page controls in asp.net, when output caching is enabled?

Introduction

In this short article we are going to see how we can use some smart tricks for manipulating controls in master page of asp.net, from a content page. The topic seems a little bit lame and should be pretty strait forward but I wouldn’t be discussing with the community unless it has a very unexpected turn.

image

Here is the situation, we have a asp.net 4.0 web application with a single master page. In some cases we need to hide master page’s controls, in particular header and footer.

image

To demonstrate the ideas and story I have created a simple asp.net 4.0 web application in visual studio, the solution explorer components is given above as screen shot, nothing special just taken after creating the project.

“Site.Master” the site layout html is given bellow:

<body>
<form runat="server">
<div class="page">
<uc1:Header ID="Header1" runat="server" />
<div class="main">
<asp:ContentPlaceHolder ID="MainContent" runat="server" />
</div>
<div class="clear">
</div>
</div>
<uc2:Footer ID="Footer1" runat="server" />
</form>
</body>

Looks pretty innocent right, infect most of our web site template has header,main-content,footer generic style. Now then the requirement is to hide the header and footer in one of the content page, in fact in couple of pages, why those page are some kind of report page and its not necessary to show header and footer as those page can be printed.


Most easy way out


Most easy way out is just use find control method in page.master object and then simply hide them. we can also cast them to custom control and then set properties, this will work in 99% case and really simple. This can be found in net with one google only, and in first result will do the job. Bellow the code is given of the strait forward way.


public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
var masterPage = Master;
if (masterPage != null)
{
masterPage.FindControl("Header1").Visible = false;
masterPage.FindControl("Footer1").Visible = false;
}
}
}

Yes just like that and our site’s header and footer will open the rules of visibility. Now, we are here because we have a high performance web and it has not view state, no session, what so ever. All login and security measure depends on cookie and each request.


More over we have output caching enabled on header and footer for “9000”.


What will happen when control has Output Cache defined


I am sure all of you know that you can cache page, user control's  output cache, it’s a default asp.net attribute and can be added in any page and user control to cache output for a object for particular period of time with some parameter or customization. To do so we have to add “ <%@ OutputCache  Duration="9999" VaryByParam="none" %> “ in control or page declaration in html. to know more about it please visit http://msdn.microsoft.com/en-us/library/hdxfb6cy(v=vs.71).aspx.


What happen to the above code when we run the application in debug mode? The page works fine for the first time it works fine great!. what would happen if it try to access it again?, just hit inter in browser or refresh the  browser page, crap! its not working, showing server error and it says master page does not have this control eventually throws server error.


image



If you check if the control exists or not, first time it will return yes its exist second time it will say it does not exists. Its normal and its happening because the controls that we are trying to modify is cached, hence can’t be  access like that.


What is the solution then?


Solution is we have to find the cached control and then work on that control finally add it to the control again so that, what ever we have changed reflected on the page final output. Bellow the code segment is given for this. This time we have modified the code and kept it in master page, and just invoked a method from content page.


Master page’s code


using System;
using System.Web.UI;
using MasterPageControlExample.Controls;

namespace MasterPageControlExample
{
public partial class SiteMaster : MasterPage
{
protected void Page_Load(object sender, EventArgs e)
{

}

public void DisplayHeader(bool value)
{
if(Header1!=null)
Header1.Visible = value;
else
{
var cachedHeader = (PartialCachingControl) Page.LoadControl(@"Controls\Header.ascx");
Page.Controls.Add(cachedHeader);
if(cachedHeader.CachedControl !=null)
{
var header = cachedHeader.CachedControl as Header;
if (header != null) header.Visible = value;
}
}
}

public void DisplayFooter(bool value)
{
if (Footer1 != null)
Footer1.Visible = value;
else
{
var cachedFooter = (PartialCachingControl)LoadControl(@"Controls\Footer.ascx");
Page.Controls.Add(cachedFooter);
if (cachedFooter.CachedControl != null)
{
var footer = cachedFooter.CachedControl as Footer;
if (footer != null) footer.Visible = value;
}
}
}
}
}


Content page’s code 


using System;

namespace MasterPageControlExample
{
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
var masterPage = Master;
if (masterPage != null)
{
var siteMaster = (masterPage as SiteMaster);
if (siteMaster != null) siteMaster.DisplayHeader(false);
}
}
}
}


In above master page’s code we fist checked if the control is exists or not by simply checking null, for the first time it wont be null and can directly assign the properties, for the second and subsequent times until the control is been created once again when the cache expires the else block of the code will be executed.


In else block of DisplayHeader or DisplayFooter method we have Loaded the control, this time this Page.LoadControl method will return PartialCachingControl object. It have to be again added to Page.Controls to be able to access from CachedControl property of PartialCachingControl object. Finally added the required properties value.


Now this code will work on 100% case as we have over came the problem with output cache as well.


A good suggestion


Even if you are a beginner you probably know it but still sharing as some of us might not implemented it. I am talking about PageBase or ControlBase objects for asp.net site. The idea is just to reuse some repeating code and some other cross cutting concern if we have any in our page life cycle. Here I suggest that you create a BasePage.cs class where you will encapsulate the codes like display header and footer, and in content page you will just call this methods, in that case your code will in one place.


Bellow the code for BasePage.cs is given.


BasePage’s Code


namespace MasterPageControlExample.Objects
{
public class BasePage:System.Web.UI.Page
{
protected void DisplayHeader(bool value)
{
var masterPage = Master;
if (masterPage != null)
{
var siteMaster = (masterPage as SiteMaster);
if (siteMaster != null) siteMaster.DisplayHeader(value);
}
}

protected void DisplayFooter(bool value)
{
var masterPage = Master;
if (masterPage != null)
{
var siteMaster = (masterPage as SiteMaster);
if (siteMaster != null) siteMaster.DisplayFooter(value);
}
}
}
}

Content Page’s Code


using System;
using MasterPageControlExample.Objects;

namespace MasterPageControlExample
{
public partial class _Default : BasePage
{
protected void Page_Load(object sender, EventArgs e)
{
DisplayHeader(false);
}
}
}

This looks compact and organized now, when we manipulate some cached control it tend to create some inherent problems, some of the problems are discussed bellow.


problem: Adding control back in page.controls create server error


We can’t add the cached control in Page.Controls Object collection, since there is a good chance that the controls such as header or footer will have some tags that has server controls and that’s going to create problem while adding those controls in page.


Result of adding header back to Page.controls


image


Then what is the solution? we have to add in a placeholder where for this master page markup need to change so that header and footer will be declared declaratively in side a place holder.


Modified Master Page Code


<%@ Master Language="C#" AutoEventWireup="true" CodeBehind="Site.master.cs" 
Inherits="MasterPageControlExample.SiteMaster" %>


<%@ Register Src="Controls/Header.ascx" TagName="Header" TagPrefix="uc1" %>
<%@ Register Src="Controls/Footer.ascx" TagName="Footer" TagPrefix="uc2" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head runat="server">
<title></title>
<link href="~/Styles/Site.css" rel="stylesheet" type="text/css" />
<asp:ContentPlaceHolder ID="HeadContent" runat="server">
</asp:ContentPlaceHolder>
</head>
<body>
<form runat="server">
<div class="page">
<asp:PlaceHolder ID="PlaceHolderHeader" runat="server">
<uc1:Header ID="Header1" runat="server" />
</asp:PlaceHolder>
<div>
<h2>
<a href="Default.aspx">Default.aspx</a><br />
<a href="About.aspx">About.aspx</a><br />
<a href="Report.aspx">Report.aspx</a><br />
</h2>
</div>
<div class="main">
<asp:ContentPlaceHolder ID="MainContent" runat="server" />
</div>
<div class="clear">
</div>
</div>
<asp:PlaceHolder ID="PlaceHolderFooter" runat="server">
<uc2:Footer ID="Footer1" runat="server" />
</asp:PlaceHolder>
</form>
</body>
</html>


Note that in above code added two place holder to hold header and footer, and the header and footer which is user control added inside the place holder, now then if our intention is just to modify the visibility status there is a very easy way out again.


Here is the situation we have three content page



  1. Default page [where we want to display both header and footer]

  2. About page [where we want to display only header and hide footer]

  3. Report page [where we want to hide both header and footer]

Content page’s code in this scenario


//first page
public partial class _Default : BasePage
{
protected void Page_Load(object sender, EventArgs e)
{
DisplayHeader(true);
DisplayFooter(true);
}
}
//second page
public partial class About : BasePage
{
protected void Page_Load(object sender, EventArgs e)
{
DisplayHeader(true);
DisplayFooter(false);
}
}
//third page
public partial class Report : BasePage
{
protected void Page_Load(object sender, EventArgs e)
{
DisplayHeader(false);
DisplayFooter(false);
}
}

Master page’s code


public void DisplayHeader(bool value)
{
if(Header1!=null)
Header1.Visible = value;
else
{
Page.LoadControl(@"Controls\Header.ascx");
var cachingControl = PlaceHolderHeader.Controls[0] as StaticPartialCachingControl;
if (cachingControl != null) cachingControl.Visible = value;
}
}

public void DisplayFooter(bool value)
{
if (Footer1 != null)
Footer1.Visible = value;
else
{
LoadControl(@"Controls\Footer.ascx");
var cachingControl = PlaceHolderFooter.Controls[0] as StaticPartialCachingControl;
if (cachingControl != null) cachingControl.Visible = value;
}
}


Note that in this case I have cast the control[0] as the place holder as we have only one control inside the place holder,also note that you can’t set the custom properties here. As it’s a StaticPartialCachingControl.


problem: Setting other properties of the control other than visibility


Well this is the final part of the article in this section we want to set other properties of the cached control, unfortunately its not that much easy and there is not easy way out for setting properties in a cached control rather we have to load control and then add it back in control collection, but before change the desired property.


The intention is to change site title in About.aspx page. I am going to skip the rest of the other detail and list the code for master page. That will be self explanatory.


Master page’s code for Setting Site Title


public void SetSiteTitle(string siteTitle)
{
if (Header1 != null)
Header1.SiteTitle = siteTitle;
else
{
var cachedHeader = (PartialCachingControl)LoadControl(@"Controls\Header.ascx");
PlaceHolderHeader.Controls.Clear();
PlaceHolderHeader.Controls.Add(cachedHeader);
if (cachedHeader.CachedControl != null)
{
var header = cachedHeader.CachedControl as Header;
if (header != null) header.SiteTitle = siteTitle;
}
}
}


There are lots of thing that I want to list about this tiny little article but keeping some thing for the future. I hope I would get good feedback about this article.


Conclusion


In this short article we have seen a particular problem’s most easy way out, followed by what will happen when cached is enabled for a control, finally some tips and trick to make it perfect. The knowledge is available in web and can be found easily with single search in any search engine, however for beginners it’s a panic situation, and I have tried to organized the ideas sequentially so that it make sense in first read for a absolute beginner.


references