scoped_ptr in C#

 

Is there a better way? Or at least a more generic way to leverage the dispose pattern? Well here’s one I thought of tonight

 

   1:      public class ScopeMngr : IDisposable
   2:      {        
   3:          private Action _dispose = null;
   4:   
   5:          public ScopeMngr(Action init, Action dispose)
   6:              : this(dispose)
   7:          {
   8:              init();            
   9:          }
  10:   
  11:          public ScopeMngr(Action dispose)
  12:          {
  13:              _dispose = dispose;
  14:          }
  15:   
  16:          public void Dispose()
  17:          {
  18:              if (_dispose != null)
  19:              {
  20:                  _dispose();
  21:                  _dispose = null;
  22:              }
  23:          }
  24:      }

Sample usage:

   1:      public partial class Form1 : Form
   2:      {
   3:          public Form1()
   4:          {
   5:              InitializeComponent();
   6:          }
   7:   
   8:          private void button1_Click(object sender, EventArgs e)
   9:          {
  10:              using (var sm = new ScopeMngr(() => Cursor = Cursors.WaitCursor, () => Cursor = Cursors.Default))
  11:              {
  12:                  Thread.Sleep(TimeSpan.FromSeconds(10));
  13:              }
  14:   
  15:              bool updating = false;
  16:              using (var sm = new ScopeMngr(() => updating = true, () => updating = false))
  17:              {
  18:                  // updating is true here
  19:                  // update the UX etc.
  20:              }
  21:              // updating is false here
  22:   
  23:          }
  24:      }

 

P.s. I know creating an object to reset a boolean is a bit of overkill, but see my comments and argument for same in my c++ post 


Enjoy.

p.s. you could also just use a try {} finally {}

C++ 11–shared_ptr

To be honest, it’s been a long time since I did any real c++, however I’ve been reading a Java book lately and it’s made me kinda lonesome for C++, the Java book goes into a lot of detail about core language structure, it’s not a book on hibernate, swing etc, just core fundamentals like differences between an internal private class or an internal private interface, static binding of fields etc. I remember when I was at the height of my c++ development career I knew the intricacies about default parameters being statically bound in polymorphic classes, I knew about private inheritance, pitfalls of overriding non virtual functions, thinking back I knew the language quite intimately. Sure in the .net world I know quite a lot of the framework and the libraries toolsets etc (because i’m a greedy little pig and want to know everything) but, I wonder do i know the c# language quite as well as I once knew c++.

As I said at the outset I’ve been away from c++ for a few years now, I think the last time I did any commercial c++ was in 2006 when I was up to my eyeballs in boost/stl/wtl/atl etc, so what’s changed? Well there’s a new standard for one, C++11. Just to keep my finger in I’ve decided to start writing a few little blog posts on the new standard, this is the first one.

In Boost we used to used shared_ptr this class template stored a pointer to a dynamically allocated object, the object pointed to was guaranteed to be deleted when the last shared_ptr pointing to it was destroyed or reset.

e.g.

#include <vector>
#include <set>
#include <iostream>
#include <algorithm>
#include <boost/shared_ptr.hpp>
 
//  The application will produce a series of
//  objects of type Foo which later must be
//  accessed both by occurrence (std::vector)
//  and by ordering relationship (std::set).
 
struct Foo
{ 
  Foo( int _x ) : x(_x) {}
  ~Foo() { std::cout << "Destructing a Foo with x=" << x << "\n"; }
  int x;
  /* ... */
};
 
typedef boost::shared_ptr<Foo> FooPtr;
 
struct FooPtrOps
{
  bool operator()( const FooPtr & a, const FooPtr & b )
    { return a->x > b->x; }
  void operator()( const FooPtr & a )
    { std::cout << a->x << "\n"; }
};
 
int main()
{
  std::vector<FooPtr>         foo_vector;
  std::set<FooPtr,FooPtrOps>  foo_set; // NOT multiset!
 
  FooPtr foo_ptr( new Foo( 2 ) );
  foo_vector.push_back( foo_ptr );
  foo_set.insert( foo_ptr );
 
  foo_ptr.reset( new Foo( 1 ) );
  foo_vector.push_back( foo_ptr );
  foo_set.insert( foo_ptr );
 
  foo_ptr.reset( new Foo( 3 ) );
  foo_vector.push_back( foo_ptr );
  foo_set.insert( foo_ptr );
 
  foo_ptr.reset ( new Foo( 2 ) );
  foo_vector.push_back( foo_ptr );
  foo_set.insert( foo_ptr );
 
  std::cout << "foo_vector:\n";
  std::for_each( foo_vector.begin(), foo_vector.end(), FooPtrOps() );
  
  std::cout << "\nfoo_set:\n"; 
  std::for_each( foo_set.begin(), foo_set.end(), FooPtrOps() );
  std::cout << "\n";
 
//  Expected output:
//
//   foo_vector:
//   2
//   1
//   3
//   2
//   
//   foo_set:
//   3
//   2
//   1
//
//   Destructing a Foo with x=2
//   Destructing a Foo with x=1
//   Destructing a Foo with x=3
//   Destructing a Foo with x=2
   
  return 0;
}

 

In c++ 11 we now get a shared pointer as part of the standard, see my example below.

image

I know there were some overheads to the boost shared pointer, memory footprint etc, (consider 1x106). of these guys in a container!. But in general shared_ptr can help you, because if you do it manually you’ll likely write slower, buggier code (or both).

Tip: Auto Logon with Windows 7 User account.

 

Ok, only you can decide if this is something you want to do, keeping in mind the security concerns.

Here’s how:

  • Press the Windows key + R on your keyboard to launch the “Run” dialog box.
  • Type in control userpasswords2 + ENTER
  • The User Accounts window will display.
  • image
  • Uncheck “Users must enter a user name and password to use this computer”
  • Click OK
  • You will then be prompted to enter the current password and confirm it.
  • After doing so, you will no longer be prompted to enter your password upon login.

MVC Action Filters

 

So what are MVC Filters? To quote Professional ASP.NET MVC2 ISBN 978-0-470-64318-1

”Filters are a declarative attribute-based means of providing cross-cutting behavior to an action method.”

So what are MVC Filters? Sarcastic smile Well lets discuss the M the V and the C, The model is the data we wish to display in, the View, which is how we present the data, the responsibility of the controller is to coordinate the view with the model. But what about orthogonal functionalities, e.g logging, error handling, authentication etc.

In MVC the responsibility for these activities is undertaken by Filters. Out of the box MVC provides the following Filters

  • Authorize
  • HandleError
  • OutputCache
  • RequireHttps
  • ValidateAntiForgeryToken
  • ChildOnlyAction
  • ValidateInput
[HandleError[ExceptionType = typeof(RuntimeException), View='RuntimeError']
public ActionResult Test()
{
    throw new RuntimeException("oops");
}

What happens here is the we get directed towards the RuntimeError view,

The attributes can be added to the Controller or Action.

In MCV3 we get the possibility to add these filters Globally. The advantage of this is you no longer need to decorate every controller or action with an attribute that you wanted executed whenever it ran, now you can register is one place and have it executed across multiple controllers and action.

You add these global filters in your Global.asax as follows

public static void RegisterGlobalFilters(GlobalFilterCollection filters) 
{ 
    filters.Add(new HandleErrorAttribute());         
}

Specifying CSS classes and html attributes with MVC helpers

 

Ok you’ve finally got you MVC controller and models all wired up, you BL is fine, now you want to pretty up those views, so you’ll start to use some css and javascript.


Here’s how you can specify html attributes with your html helpers.

Button sample:

image

 

Form sample:

image

Note @ is used to escape the c# keyword class.

image

Progressive Enhancement with Modernizr

 

If you’ve been to a HTML5 session or lived in the html5 world for any length of time you’ll have come across the term “Progressive Enhancement”. It’s about taking a base application that works on downstream browsers and detecting features and increasing functionality if you have certain features.

Take example local or session storage, in older versions of browsers there was no local storage so there would be more round tripping.

So how do we detect these features? One method is a javascript file called Modernizr that detects feature availability (rather than using a database etc).

Syntax:

   1:  if (Modernizr.localstorage) 
   2:  {    
   3:      // browser supports local storage
   4:  }
   5:  else 
   6:  {    
   7:      // browser doesn't support local storage
   8:  }
   9:   

 Check out modernizer it's got many detection and abstracts you from detection techniques.

You’ll get this script added to your project for free in MVC3.

Ain’t she sweet

 

Nothing, really ground breaking, but don’t it look neat! (if i say so myself). (that facebook link will be going up alongside flicker/twitter when i get around to it.).

Site written in asp mvc3/ jQuery / razor / graphics in photoshop and content owned by the thecamerafly.
Another few hours will have the initial prototype ready to go live, hopefully this w/end as I’m in the land of Java workwise for the next two days at least and that will probably eat into my evenings.

image

Next on my little personal agenda is to create an online expense tracking system, with automatic historic currency conversions, if anyone want’s to lend a hand on this let me know, I’ve one or two ideas on where to get currency rates Smile given permission Smile, also I’m thinking at looking at the OSS option given enough interest.

Charts in MVC3

 

So you want to draw a chart in MVC and don’t know where to start?

Step 1) Create a new MVC3 project

Step 2) Open NuGet and add a library reference to “microsoft-web-helpers”

image

 

image

Step 3) Change your action method to create a new chart and write it to the response stream

 

image

 

Result)

image

Step Additional )

You could return a partial view and even call it from Ajax if you wanted, you could just return Json and use a client side vector graphics library.
Or you would create your own html helpers / function to make life easier. (many ways to skin a cat).

Global MVC Helpers

 

This evening while I was helping an ex colleague of mine, who was venturing onto the web platform for the first time, an interesting thing happened, he taught me a thing or two!

Neil had been researching web forms and MVC, given it was a green field project he choose MVC, WebForms would have sufficed but it is not as elegant and efficient as the next generation of web development tools such as MVC, jQuery and Razor. As part of his research he come across a pluralsite video that mentioned a magic folder for something… naturally this aroused my curiosity, I don’t believe in magic! Surely the presenter was mistaking?

The video

The video is available here it’s Scott Allen giving an intro to MVC. Sure enough he mentions a magic folder.

Q. What is this magic folder?
A. Just the standard App_Code asp folder,

Q. What is so special with in MVC?
A. It allows you to define global MVC helpers

Q. What’s a MVC Helper?
A. Read my other post here

Q. Why is this so magical?
A. Because the dev team ran out of time Smile

Q. How do I know this?
A. Because this months edition of DevProConnections magazine contains an article “Fine-Tune Your ASP.NET MVC Skills” that explains it.

 

From the magazine i’ve learned that according to both the Razor online documentation and Scott Guthrie’s blog, global helpers are supported by placing a page in the ~/Views/Helpers folder. Any helpers that are defined in this folder should be available in any part of the application. However, because of time constraints, this feature wasn’t implemented. The workaround is first to create an App_Code folder and then add to the folder a new helper created as a .cshtml (or .vbhtml). You can then access the the new helper by using <file name>.<helper name> convention.

Q. Did I learn anything else new?
A. Yes while helping him add scripts to a view I discovered MVC3 ajax helpers, I’m not sure if I’m buying into them fully yet as I’ve gotten used to the jQuery syntax on it’s own, but I’ll be doing some more investigation.

So tnx Neil for letting me help you, I learned a lot! Laughing out loudRolling on the floor laughingNyah-Nyah

Microsoft Synchronization Services, WCF OData, Sql Azure, WPF, iPhone

Part1 – Setting up your database

I did some work with an interesting piece of tech lately, Microsoft Syncronization services 4.0 CTP. This post aims to give an overview of where to start, but firstly, let me describe the how all this plugs together and what it buys me.

Overview

The OData + Sync protocol uses the OData format for the data payload that can be consumed by clients that are running on any platform. Clients and the service use the protocol to perform synchronization, where a full synchronization is performed the first time and incremental synchronization is performed subsequent times. The protocol is designed with the goal to make it easy to implement the client-side of the protocol, and most (if not all) of the synchronization logic will be running on the service side. OData + Sync is intended to be used to enable synchronization for a variety of sources including, but not limited to, relational databases and file systems.

Server

The CTP release includes server components that make it easy for you to build a sync Web service that exposes data to be synchronized via the OData + Sync protocol. For example, you can easily expose data in a SQL Server database or a SQL Azure database via a WCF sync endpoint using these server components. In our case our server in sitting in the Azure Cloud providing an OData endpoint, the data is also hosted in the Cloud in Sq1 Azure.

Clients

We have 3 clients, (well 4 actually but our Silverlight version has lagged behind and in not yet publically available).

  1. WP7 – Local data stored in Isolated Storage, DataVisualizationToolkit for charting, SL3
  2. iPhone – Connecting directly to the server via OData/Json
  3. ASP.MVC Ajax – A powerful web interface written using MVC3 and jQuery
  4. Silverlight – Initially used RIA Services to access the server but synchronization model is nearly identical to the WP7 SL3 approach with isolated storage now.

How to create the server.

  1. Create you database schema in SSMS (SqlServer managment studio)
  2. Now that your database has been created you’ll need to provision it, think of this much in the same way that you would provision an existing sql server database for asp membership tables and stored procedures. The syncronization framework will provide you with a tool called SyncSvcUtilHelper.exe this basically is a GUI for the command line version.

image

before provisioning you’ll need to create a Sync configuration, so choose option on, select a filename in step 1 and select your database in step2

image

image

Select the list of tables that you are interested in syncing

image

That’s pretty much it. Now you’ll need to choose option2 to provision the database.
Select the configuration file you created as part of step 1 and choose the provisioning option.

image

That’s all that’s involved, your Database is now ready to be synchronized, of course there are come considerations, unique id’s etc, but you’ll find all this in the documentation.

 

My next post will cover creating the WCF service for exposing the database, after that I’ll run through creating the clients.