jump to navigation

Repeaters and Lost Data After Postback (Viewstate) October 8, 2009

Posted by codinglifestyle in ASP.NET.
Tags: , ,
add a comment

Test question: I have a form which binds data to a Repeater on PageLoad.  The Repeater’s ItemTemplate contains a TextBox and Checkbox.  On postback the data is lost.  What’s wrong?

You may have found this page if you have been googling the following:

  • repeater postback lost data
  • dynamic control postback viewstate
  • data lost on postback

The problem is the Repeater is a dynamic control.  If you are binding in the codebehind, which we typically are, you have to realize that the textbox and checkboxes do not existuntil you DataBind().  Keeping that in mind, we should ask ourselves what is the order of execution of ViewState.  I think we can start to formulate our answer to the question above by realizing where I DataBind() and create my controls in relation to the workings of ViewState is why our data is lost on postback.

So, the answer: PageLoad is the wrong place to bind a Repeater or setup a dynamic control.  It is too late.  ViewState has already tried to resync your controls but they weren’t created yet.

What about the answer you want?  Stop toying with me and tell me the answer I hear you say.  Try OnInit().  If you bind there you’re controls will exist in time for ViewState to operate normally.

protected override void OnInit(EventArgs e)

I would have also accepted Repeaters are the evil frogspawn of Satan and should never be used unless you find peeling off your fingernails with rusty pliers appealing.

ref: http://weblogs.asp.net/ngur/archive/2004/05/17/133340.aspx, http://aspnet.4guysfromrolla.com/articles/092904-1.aspx

A day with The Gu! MVC 2, VS2010 and ASP.NET v4.0 September 29, 2009

Posted by codinglifestyle in ASP.NET, C#, Visual Studio 2010, jQuery, linq.
Tags: , , ,
2 comments

Yesterday I went to Dublin to attend a talk by Scott Guthrie. I knew from reputation Scott was a good speaker so it was great to see him in action. I think most of the Microsoft development world is familiar with Scott’s blog. I’ve exchanged emails with him in the past and he has always done a great job following up. He is a very down to earth guy, very at ease at the podium, and very comfortable the material.

We started the talk with a beginner’s look at MVC 2 and then looked at .NET v4 and VS 2010. Some of this information was a recap of TechEd (see my earlier post), but there was plenty of new information which I’ll recap here.

MVC 2

Scott’s talk was about some of the improvements of the next version of MVC which will be baked in to VS2010. But thankfully, he covered the whole concept in a very demonstration-oriented way. He built upon each concept in a way that left me with a good grasp of the basics.

First, he reiterated that webforms is not going away. MVC is just an alternative presentation layer built upon the same core .NET libraries we know and love. Because there is no designer, no .NET controls, and no code behind (as such) you are much more in control of the generated HTML.

What MVC offers is that control, URL mapping, js integration, and testability. If you’ve ever worked on a messy web app and wished for more structure MVC may be for you. It offers a clean separation of your data layer (model), your html (view), and your business logic (controller).

Right, enough of this verbose carrying-on, time for bullet points!

· MVC 1 was an extra for VS2008 built on ASP.NET v3.5. MVC2 will be baked in to VS2010 and built on ASP.NET v4.0. It will be backwards compatible with MVC1 apps so upgrades should be a snap.

· Controller

o URL Mapping – this is not just a cool feature but fundamental to MVC

§ http://localhost/galway maps to a controller class called galway

· .index is the default action method

§ http://localhost/galway/hooker maps to an action method inside controller Galway

§ http://localhost/galway/hooker/beer maps to the action method hooker and passes the string parameter “beer”. Note this is an alternative to query string parameters.

· These parameters can be strongly typed to string, int, even classes

§ Routing rules go in to gloal.asax.cs

· Operates like an HTTPHandler but is baked in to ASP.NET

· Order routing rules as you see fit. One falls through to another and ultimately to a default

· Can use regular expressions and constraints in your rules

o We can start playing with a controller without a View or Model and directly return some html from controller (think webservice)

o Controller action methods can return an action result type to return a View, redirect, etc.

o To communicate with View we can

§ store information in a ViewData[“key”] dictionary to pass to View

§ store information in a Model and pass this class to View

o Action Filters decorator attributes can be specified on the controller class or an action method to specify which roles / authorization required to use

o Tip: Use a service layer to keep direct data layer queries out of controller

· View

o Offers separation of UI from business logic and just renders the UI

o Remember, no designer or ASP.NET controls. Just you, html, and <%inline code%>.

o HTML. Helper with many built-in templates to generate common controls like checkboxes and textboxes with validation

§ Create your own View templates to have custom scaffolding like a table for a DB list

o Html.EditorFor gives Linq type intellisense to meaning we aren’t binding to a “string” in our model

§ Smart in that Booleans render as checkboxes, etc.

§ EditorTemplates can be used to custom render anything can be shared across entire site or used for just one View

o Html.DisplayFor gives read-only view of data

· Model

o A data entity with logic.

§ Can be LinetoSQL, ADO.NET, your own entity class, whatever

o Can decorate properties with attributes to specify common validators

§ Required, range, etc.

§ Very powerful, dynamic, should greatly ease pain of validating form data

§ Automatically adds a CSS class you can customize to get a red background, whatever

§ Can have server and client side validation

· Client side requires an extra js plug-in but worked seamlessly in demo

· Unit testing is crucial component of MVC and a test project is automatically created for you with every MVC website

o Use AAA method

§ Arrange

· Create a controller

§ Act

· Get the result of (controller.Index(0) as ViewResult)

§ Assert

· Assert if result.IsNotNull

o Dependency injection

§ In the constructor pass DB service layer or fake data. Use an interface for flexibility.

VS2010 & .NET v4.0

· Beta 2 out shortly

· IDE improvements

o Ctrl-, – quick nav via types

o Highlight all references

o Tip: Download CodeRush Xpress for these features in VS2008)

· Better intellisense support

o camel case (i.e. DB matches DataBind)

o Matching (i.e. bind matches DataBind)

o Consume first mode for TDD (test driven development)

§ Ctrl + Alt + Space to toggle

o Much improved javascript support

§ XML documentation (place under function()) for better intellisense for your own libraries

· Debug History and dumping a crash covered again (see previous post)

· .NET 4 is a new CLR unlike 3.0 and 3.5

o In IIS you will see v4.0 as a selectable framework

· Upgrading to VS2010 hopefully just changes solution file (like VS2005 > VS2008) so painless enough to upgrade

· Multi-target support from .NET v2.0 on up

· Lots of project templates including a new online template gallery (web starter kits?)

· Controls to have ClientIDMode property

o Static – is what it is. Call it “bob” and you are guaranteed to get document.getElementByid(“bob”)

o Predictable – new default… no more ctrl001_ prefixing

o Auto – current

o Inherit

· CSS rendering support

o Big upgrades including alternatives to tables for .NET controls

· ViewState – off by default. Force developers to think when we really need it.

· URL routing like MVC for WebForms (connotical)

· SEO (Search Engine Optimization)

o Page.Description and Page.Keywords to generate <meta> tags

§ Idea: Place in master page, tie-in to DB, allow client to change as required

o New SEO plug-in for II7 will crawl site and indentify issues that reduce search relevancy

§ Can increase search traffic 30-40%

· ScriptManager support CDN allowing you to specify URL for AJAX and jQuery direct from http://ajax.microsoft.com. Will actually phantom redirect to very local source but browser histories across many site will use standard Microsoft url meaning high probability of being cached

· New controls

o QueryExtender search control – search a grid

o Chart control

· Validation like MVC for GridView, FormView, ListView

o Auto reflect on class for validation decorator attributes and dynamically render validators with client and server-side validation

· Output/object cache providers (aka customizable I’m sure)

· Pre-start application

o Keep your application up, cached, and ready vs. IIS default behavior which shuts down when not in use

· Performance monitoring

· <%: Html encoded string %>

· Deployment (see previous post)

 

Well that wraps it up.  Please see my earlier post from Tech-Ed and download my PowerPoint presentation which covers a lot of the upcoming features in VS2010.

Change Background Color of Invalid Controls (ASP.NET Validator) September 16, 2009

Posted by codinglifestyle in ASP.NET.
Tags: , , , ,
3 comments

I was working with a customer who has invested a lot in redoing the validation in their web application.  I accedentially suggested wouldn’t it be nice if we could change the background or border of the field in question.  The customer loved this idea which meant I’d just created more work for myself.  After searching about I wasn’t finding this done for me, so I actually had to write some code instead of cutting and pasting.

If you set a breakpoint on WebForm_OnSubmit and step in you can check out the .NET validator script.  Key thing here is a global array called Page_Validators.  From here it is fairly trivial to test and change something about the control in question.

function fnOnUpdateValidators()

{

    for (var i = 0; i < Page_Validators.length; i++)

    {

        var val = Page_Validators[i];

        var ctrl = document.getElementById(val.controltovalidate);

        if (ctrl != null && ctrl.style != null)

        {

          if (!val.isvalid)

              ctrl.style.background=“#FFAAAA”;

          else

              ctrl.style.backgroundColor = “”;

        }

    }

}                           

 

Of course, one problem is if the control already had a background color, it would be lost.  This can be circumvented by storing the old value in an attribute or elsewhere.  Also, custom validators are a special case so you will need to add the appropriate changes for fields validated in a custom way.

To make sure my function is called I use the deprecated Page.RegisterOnSubmitStatement(“val”, “fnOnUpdateValidators();”).  This will call my function after the validators have fired so the isvalid is up to date.

IE Google.IE Accelerator (Search Provider) August 31, 2009

Posted by codinglifestyle in IE.
Tags: , ,
add a comment

This was starting to really annoy me and was very quick to fix once I spent 5 minutes to solve it.  The problem is, the default Google search provider for IE kept bringing me to google.co.uk.  Say I’m shopping and find an ebay listing.  Since I’m on google.co.uk I get taken to ebay.co.uk.  I really wanted to stick with google.ie and the Irish-centric listings it returns.  The problem is there is no way to edit the search provider so the best I could do was install a google.com (vs. google.co.uk) provider.

It turns out this is simple to fix with a quick edit to the registry.  The search providers are stored here: HKEY_CURRENT_USER\Software\Microsoft\Internet Explorer\SearchScopes

The GUIDs may differ, mine was {6A1806CD-94D4-4689-BA73-E35EA1EA9990} for the google.com search provider.

Open the URL key and simply change  www.google.com to www.google.ie: http://www.google.ie/search?q={searchTerms}&rls=com.microsoft:{language}:{referrer:source?}&ie={inputEncoding}&oe={outputEncoding}&sourceid=ie7&client=&rlz=1I7GGLL_en

Now when I search (CTRL-E), I get google.ie with all the creamy Irish goodness I expect.

OnClientClick Breaks Validation August 20, 2009

Posted by codinglifestyle in ASP.NET, Javascript.
add a comment

It’s a horrible sinking feeling when you make a sizable change and everything goes tits up.  I was updating an ASP.NET form the other day which had a lot of HTML controls on it.  I decided to update these to ASP.NET controls and replaced a number of buttons.  While doing this I cleaned up the onclick code, which I placed in OnClientClick.  Unwittingly I managed to break validation for the entire page, as just about every button used this attribute.  I won’t bore you with the details, but suffice it to say I had a few red herrings and couldn’t understand why my page’s validators suddenly stopped working.  I spent all night fretting about it, but this morning the first thing I did was drop a new button on the page, load it up, and click it.  Presto, validation worked for that button but not the other buttons on the page.  What’s going on?

<asp:Button runat=”server” ID=”Save” OnClientClick=”return confirm(‘Are you sure?’);” /> 

 It becomes crystal clear when you view the source of the page.  We will see something like this:

onclick=”return confirm(‘Are you sure?’);WebForm_DoPostBackWithOptions(…)”

It is now clear that we are returning before the validator’s script has a chance to run.  I will pause now for an, “Ohhhhhhh….  <slap to head>”.

Typically, we want to stop execution if our called function returns false but continue if it returns true.  Solving this problem requires just a small change to our script.  Take a look below:

onclick=”if (!confirm(‘Are you sure?’)) return false; WebForm_DoPostBackWithOptions(…)”

Now we will only return false if our script returns false.  If our script returns true, the browser will continue to call WebForm_DoPostBackWithOptions(…) which will execute our validators.

ref: http://vaultofthoughts.net/OnClientClickBreaksValidation.aspx

Composite Controls: Dude, where’s my data? June 25, 2009

Posted by codinglifestyle in ASP.NET, C#.
Tags: , , , , , , , , ,
1 comment so far

I started my .NET career writing WebParts for SharePoint 2003.  You would think this would make me a bit of a server control expert, as WebParts are essentially gussied up server controls.  Yet, I’ve officially wasted 2 days on an age old composite control problem which typically involves these kinds of google searches:

  • server control postback missing data
  • postback server control child control missing
  • composite control event not firing
  • webcontrol createchildcontrol postback control
  • viewstate webcontrol data missing empty blank

Sound familiar?  I understand your pain and hope I can help.  Composite controls can be tricky, if they aren’t set up just right even the most basic example won’t work properly. 

First, keep in mind there are two types of custom controls developers typically write.  There are user controls (.ascx) and server controls (.cs).   We will focus on a server control.  One gotcha for a composite control is using the right base class*.  We want to use the CompositeControl base class, not WebControl or Control.  This will tell ASP.NET to ensure the IDs of our child controls are unique (via INamingContainer).  This is simple but very important, in order for ASP.NET to wire up events and serialize ViewState the ID of a control needs to be identical at all times.  So only assign a literal string to your child control and let .NET worry about making it unique.

Now there are two cases to consider, the first is where our composite server control creates a static set of controls.  This is a straightforward case, because we can create the controls at any time.  The most important function in a server control is CreateChildControls().   This is where you can create and assign your controls to member variables.  We can have properties and get and set values straight to our member controls.   In every property just call EnsureChildControls() in each get and set

private TextBox _TextBox;

[Bindable(true), Category("TextBoxEx"), DefaultValue(""), Localizable(true)]

public string Text

{

get

{

EnsureChildControls();

return _TextBox.Text;

}

set

{

EnsureChildControls();

_TextBox.Text = value;

}

}

 

 protected override void CreateChildControls()

 {

_TextBox = new TextBox();

_TextBox.ID = “_Text”;

 

Controls.Add(_TextBox);

}

 

In reality we may have properties or logic which determine which controls are created or how our control behaves.  This is a complicated scenario, because we cannot create the controls before the logic has been initialized (otherwise our logic will not know which controls to dynamically create)!  In this case, we want our control’s own properties independent of the child controls and we’ll store this information in ViewState, not a control.  We want to avoid calling EnsureChildControls() and delay calling CreateChildControls() prematurely.  This allows the control to be initialized first so that when CreateChildControls() is called our logic will know which controls to create.  First let’s see how to store a property in ViewState.

 

        private const string STR_CreateTextBox       = “CreateTextBox”;

 

        public bool CreateTextBox

        {

            get

            {

                if (ViewState[STR_CreateTextBox] == null)

                    return false;

                else return (bool)ViewState[STR_CreateTextBox];

            }

            set

            {

                ViewState[STR_CreateTextBox] = value;

            }

        }

If you were wondering if ViewState was the right place to store properties the answer is maybe.  For a bound property it is overkill as it will be set back to its original value every postback.  In that case we simply need a property with a backing store (or in C# 3.0+ a simple get; set; will do).  But when our logic needs to be stored ViewState is the place to persist it.  Just remember that the dynamically created controls don’t need ViewState of their own so we’ll be sure to turn that off when we create them.  The right place to create and add our dynamic controls is in CreateChildControls().  Let’s create a TextBox based on some logic stored in the composite control’s ViewState.

        protected override void CreateChildControls()

        {

if (CreateTextBox)

{

            _TextBox = new TextBox();

            _TextBox.ID = “_Text”;

            _TextBox.EnableViewState = false;

            _TextBox.TextChanged += new EventHandler(Text_TextChanged);

 

            Controls.Add(_TextBox);

}

        }

 

        void Text_TextChanged(object sender, EventArgs e)

        {

          string sText = ((TextBox)sender).Text;

        }

Lets take a look at what we’re doing here.  We are dynamically creating our TextBox control in CreateChildControls().  We are setting the ID to a literal string, ASP.NET will make sure our name is unique because we inherit from CompositeControl.  We are setting EnableViewState to false because, as discussed, our composite control is already taking care of ViewState.  We are adding an event as an example as this is the right place to setup any events you might need.

Now here is the interesting bit:  How do we get the user’s value back from a dynamic TextBox?  Take another look at the property Text above and note that the getter calls CreateChildControls().  This will ensure our textbox is recreated and the form will syncronize the user’s form data back in to the textbox.  We could also capture the value using the TextBox’s text changed event to do some processing or whatever.  With this event, when we postback, our Text_TextChanged event will fire before a OK button’s click event on the page due its place in the control hierarchy.  This allows our event to manipulate the TextBox’s text value before our OK button’s click event occurs.

I’ll just note that you may be reading some advice on forum’s to override OnInit.  Contrary to that advice, CreateChildControls() is the right place to dynamically create your controls and events.  OnPreRender() is a great place for initialization as it is called after all properties are set.  And, of course, Render() gives you complete control on how your control will be drawn.

* Now I have to mention Repeater.  Repeater may cause a lot of pain with your server controls.  You may see your control working properly outside a repeater and suddenly all go pearshaped when used with one.  After a lot of trial and error I discovered this had to do with the ID assigned to the dynamic controls.  We know ASP.NET depends on the ID being identical at all points for events and serialization with the form and viewstate to take place.    Sad to say when our composite control is inside a Repeater we can not trust our IDs to .NET.  So we do not want to inherit from CompositeControl or INamingContainer.  Instead, assign a unique id yourself.  Being that it is a repeater, this can not be a literal string because no 2 controls can have the same ID.  Instead try _TextBox.ID = this.ID + “_Text”;

So although there are several points and gotchas to consider, think about using a custom control to lend some OO design to your UI.  Be sure to unit test on a simple website to make development of the control easier.  Good luck!

Start a WinForm Hidden June 18, 2009

Posted by codinglifestyle in Winform.
Tags: , , , ,
add a comment

This is a short one, there may be better ways but this was fast and simple.  Works for me!

The case here is I have a WinForm application and want the Main window to start hidden.  From the designer, you can’t set Visisble = false.  Also, setting this.Visible=false in the constructor or Load event has no effect.  Sure you can set it later (like in Paint) but the last thing you want is your window to flash and disappear every time your application starts.

So, here is all you have to do:

  1. In the designer, set your window Opacity to 0%
  2. In the constructor, pass in a boolean to indicate if the window is displayed.
  3. In the function body, add this line:
    Opacity = bVisible ? 100 : 0;

Simple, fast, done… moving on to other things in life. 

  


  

Well okay… I’m not really one for leaving well enough alone.  The fact is, there is a better way but you’re not going to like it!  I imagine your main form is doing something like sitting in the notification tray and/or monitoring something like a windows service.  That functionality, whatever it is your application does, should be abstracted out of the form altogether.  You’re really not going to like what’s next.  This object, the meat of your program, can then exist in a worker thread and provide the relevant events to your UI so it may update itself if the main form is shown. 

It’s not as bad as it sounds.  Go on, you know separating the logic from the UI layer is the right design!  We’ll abstract all our real functionality into a class called MyFunctionality.  We have BackgroundWorker in our .NET toolbox MyFunctionality will inherit from.  Then override OnDoWork where we’ll put the code we originally had in the main form’s constructor or Load event.  We will handle the case of exiting the thread in case the user logs off.  Last, we just need optional events for the UI to receive an update from our functionality object.  An example of this is below, with our DisplayChanged event and DoDisplayChanged function.  Use a custom event to pass more information.

    class MyFunctionality : System.ComponentModel.BackgroundWorker

    {

        public event EventHandler DisplayChanged = null;

 

        protected override void OnDoWork(DoWorkEventArgs e)

        {

            //The meat of my program…

 

            Microsoft.Win32.SystemEvents.SessionEnded += new Microsoft.Win32.SessionEndedEventHandler(SystemEvents_SessionEnded);

                       

            base.OnDoWork(e);

        }

 

        void SystemEvents_SessionEnded(object sender, Microsoft.Win32.SessionEndedEventArgs e)

        {

            this.CancelAsync();

        }

 

        void DoDisplayChanged()

        {

            if (DisplayChanged != null)

                DisplayChanged.Invoke(this, EventArgs.Empty);

        }

    }

 

Your form will create the thread and add the relevant events, in this case DisplayChanged.

  

        private void Main_Load(object sender, EventArgs e)

        {

            MyFunctionality func = new MyFunctionality();

            func.DisplayChanged += new EventHandler(Func_DisplayChanged);

            func.RunWorkerAsync();

        }

  

Lastly, we just need to make a small change in Program.cs to either (A) instantiate our main form, which in turn launches the thread hosting our functionality, or (B) directly instantiate the thread without ever using our main form.

 

         if (bDisplay)

            Application.Run(new Main());

        else

        {

            MyFunctionality func = new MyFunctionality ();

            func.RunWorkerAsync();

            Application.Run();

        }

 See, I told you you weren’t going to like it!

 

ref: http://www.interact-sw.co.uk/iangblog/2004/11/30/nomainform

VS Solution Explorer – Collapse All May 15, 2009

Posted by codinglifestyle in Visual Studio.
Tags: , , , , ,
1 comment so far

I never knew I needed this until I saw it was a feature in a ReShaper demo.  After a quick search and I found a macro that has been around for years.  Slap to the head!  The amount of time I spend collapsing all my solution folders and this existed the whole time!

I never use macros, but even I was able to quickly get this working.

  1. Open Tools->Macros->Macro Explorer (Alt-F8)
  2. Right click MyMacros
  3. Select New Module
  4. Select default template and name to VSMacros
  5. Right-click VSMacros and click New Macro
  6. Copy and paste this over the opened macro file

    Imports System

    Imports EnvDTE

    Imports EnvDTE80

    Imports EnvDTE90

    Imports System.Diagnostics

     

    Public Module VSMacros

        Sub SolutionCollapseAll()

     

            ‘ Get the the Solution Explorer tree

            Dim solutionExplorer As UIHierarchy

            solutionExplorer = DTE.Windows.Item(Constants.vsext_wk_SProjectWindow).Object()

     

            ‘ Check if there is any open solution

            If (solutionExplorer.UIHierarchyItems.Count = 0) Then

                Return

            End If

     

            ‘ Get the top node (the name of the solution)

            Dim rootNode As UIHierarchyItem = solutionExplorer.UIHierarchyItems.Item(1)

            rootNode.DTE.SuppressUI = True

     

            ‘Find selected node

            Dim selectedNode As UIHierarchyItem = FindSelectedNode(rootNode, solutionExplorer)

     

            ‘ Collapse each node

            Collapse(selectedNode, solutionExplorer)

     

            ‘ Select the selceted node

            selectedNode.Select(vsUISelectionType.vsUISelectionTypeSelect)

            rootNode.DTE.SuppressUI = False

     

        End Sub

     

        Private Sub Collapse(ByVal item As UIHierarchyItem, ByRef solutionExplorer As UIHierarchy)

     

            For Each innerItem As UIHierarchyItem In item.UIHierarchyItems

                If innerItem.UIHierarchyItems.Count > 0 Then

     

                    If innerItem.UIHierarchyItems.Expanded Then

                        ‘ Re-cursive call

                        Collapse(innerItem, solutionExplorer)

                    End If

     

                    ‘ Collapse

                    If innerItem.UIHierarchyItems.Expanded Then

                        innerItem.UIHierarchyItems.Expanded = False

                        If innerItem.UIHierarchyItems.Expanded = True Then

                            ‘ Bug in VS 2005

                            innerItem.Select(vsUISelectionType.vsUISelectionTypeSelect)

                            solutionExplorer.DoDefaultAction()

                        End If

                    End If

     

                End If

            Next

     

        End Sub

     

        Private Function FindSelectedNode(ByVal item As UIHierarchyItem, ByRef solutionExplorer As UIHierarchy) As UIHierarchyItem

     

            If item.IsSelected Then

                Return item

            End If

            For Each innerItem As UIHierarchyItem In item.UIHierarchyItems

                If innerItem.UIHierarchyItems.Count > 0 Then

     

                    If innerItem.UIHierarchyItems.Expanded Then

                        ‘ Re-cursive call

                        Dim result As UIHierarchyItem

                        result = FindSelectedNode(innerItem, solutionExplorer)

                        If Not result Is Nothing Then

                            Return result

                        End If

                    End If

     

                    If innerItem.IsSelected Then

                        Return innerItem

                    End If

     

                End If

            Next

            Return Nothing

     

        End Function

     

    End Module

     

  7. You may now execute the macro via the Macro Explorer.  Click the folder you wish to collapse (or the Solution root to collapse everything).  Right click and run the macro.  To set a shortcut continue on with the steps below…
  8. Click Tools->Options->Environment->Keyboard
  9. Search for your macro in the Show commands containing textbox
  10. Select your macro, keep scope global, and in the assign macro keys textbox enter your preferred shortcut (I used “ALT-CTRL-\”)
  11. Click ASSIGN and then OK
  12. To use, select a node and then ALT-CTRL-\.  To collapse the entire solution, select the root of the solution.

Reference: http://www.codeproject.com/KB/macros/collapseall.aspx?df=100&forumid=7565&exp=0&select=396167

Set IE7 Compatibility Flag for IE8 in IIS May 11, 2009

Posted by codinglifestyle in IIS.
add a comment

Now that IE8 has officially been pushed out via Windows Update it’s time to get serious about testing your web site compatibility.  As you probably know, one of the big changes in IE8 is complying to standards for increased interoperability.  In other words, Microsoft won’t be going it’s own way with standards anymore.  Out of the box, IE8 complies with standards that many pages developed with IE6 or IE7 in mind won’t adhere to.  This means customers may have serious layout and style issues when their customers start browsing with IE8.

There is a meta flag that can be set set to tell IE8 to automatically switch to compatiblity view, which will render the page the same as IE7.  This is fine if you have a masterpage, but in an older app with many pages this is not ideal.  Luckily, there is a dead easy way of setting a custom HTTP header which will tell IE8 the same thing.

IE7Compat

 

  1. Open iismgr
  2. Open website properties
  3. Click HTTP Headers tab
  4. Click Add
  5. For customer header name enter X-UA-Compatible
  6. For custom header value enter IE=EmulateIE7
  7. Click OK

Done!  From now on IE8 browsers will default to compatibility mode and won’t even offer the user the option of viewing the side with compatibility mode off.

Code Snippets – List of C# snippets in VS2008 May 6, 2009

Posted by codinglifestyle in C#, Visual Studio, Visual Studio 2010.
Tags: , , ,
add a comment

In VS2010 we are told to expect a lot more code snippets.  To be honest, I don’t use them much but watching the demo I told myself it was time to give them another look.  Sometimes I get a great feeling of productivity in hammering out for loop templates and properties and tell myself who needs snippets?  But there is a lot of power there, and its going even further in VS2010.

My problems is I can never remember which code snippets are there.  I occassionaly see them in Intellisense, but there is so much there it’s hard to pick them out.  More than once I’ve carefully gone through the intellisense list trying to pound the useful ones in to my brain. 

I decided to do a quick search for a list of code snippets in VS2008 for C#.  Surely I can’t be the first who just wants a simple list, right?  I came across Francesco’s blog who posted the code to iterate through your snippets and output them.  A quick change to update it for VS2008, C#, and to output a comma delimited line per snippet, then a paste in to Word, and Convert Text to Table (by comma) and voila! 

List of Code Snippets in VS2008 for C#

#if Code snippet for #if
#region Code snippet for #region
attribute Code snippet for attribute using recommended pattern
checked Code snippet for checked block
class Code snippet for class
ctor Code snippet for constructor
~ Code snippet for destructor
cw Code snippet for Console.WriteLine
do Code snippet for do…while loop
else Code snippet for else statement
enum Code snippet for enum
equals Code snippet for implementing Equals() according to guidelines
exception Code snippet for exception
for Code snippet for ‘for’ loop
foreach Code snippet for foreach statement
forr Code snippet for reverse ‘for’ loop
if Code snippet for if statement
indexer Code snippet for indexer
interface Code snippet for interface
invoke Code snippet for safely invoking an event
iterator Code snippet for a simple iterator
iterindex Code snippet for ‘named’ iterator/indexer pair using a nested class
lock Code snippet for lock statement
mbox Code snippet for MessageBox.Show
namespace Code snippet for namespace
prop Code snippet for an automatically implemented property
propg Code snippet for an automatically implemented property with a ‘get’ access or and a private ’set’ accessor
sim Code snippet for int Main()
struct Code snippet for struct
svm Code snippet for ‘void Main’ method
switch Code snippet for switch statement
try Code snippet for try catch
tryf Code snippet for try finally
unchecked Code snippet for unchecked block
unsafe Code snippet for unsafe statement
using Code snippet for using statement
while Code snippet for while loop

You can see snippet’s keyword typically matches the operator.  So next time you type for or while or try remember to hit TAB-TAB to expand the snippet.  Next time we’ll look at making your own code snippets.