-
I have run into issues recently with the browsers' implementation of the resize event on the window. Opera, Safari, IE and Firefox all have different behaviors when this event is fired.
- Firefox only fires it when you release the mouse.
- IE fires this event many many times while resizing.
- Safari will fire continusouly while dragging
- Opera fires after the resizing stopped
You can read more about this here.
These differences led me to search for a solution. I quickly wrote this proof of concept function today which may help solve this problem. It is a JQuery add-on called resizeComplete. It works by checking periodically after a resize starts and checks if the size of the object has changed. Once no change is detected it invokes the call back method.
This has not been tested much at all but I think it might be on the right track.
1: jQuery.fn.resizeComplete = function(callback)
2: { 3:
4: var element = this;
5: var height = element.height();
6: var width = element.width();
7: var monitoring = false;
8: var timer;
9:
10: function monitorResizing()
11: { 12: monitoring = true;
13:
14: var newHeight = element.height();
15: var newWidth = element.width();
16:
17: if(newHeight != height || newWidth != width)
18: { 19: height = newHeight;
20: width = newWidth;
21: timer = setTimeout(function() { monitorResizing() },100); 22: }
23: else
24: { 25: monitoring = false;
26: clearTimeout(timer);
27: callback();
28: }
29: }
30:
31: function onResize()
32: { 33: if(monitoring) return;
34: monitorResizing();
35: }
36:
37: element.resize(onResize);
38:
39: }
Here is an example of its usage:
1: $(document).ready(function()
2: { 3: $(window).resizeComplete(function(){ document.write('hi') }); 4: }
5: );
-
I have have been playing around with F# and I decided to create a state monad. This worked out really well since I was able to leverage the F# computation expressions. I then decided to try to extend this and make it more general by creating a parameterized state transformer monad. This is a state monad which encapsulates another monad. What this allow you to do is turn any computation into a statefull one.
This concept exists in Haskell which you can see here. However, my attempts at replicating this in F# failed. Unlike in Haskell, the computation expressions in F# don't share a common interface (or type class). This prevents a computation from being able to generically take another computation as a parameter. The reason is that an operation on the parameterized state transformer monad such as bind will result in a bind called on its encapsulated monad. But since there is no interface for computations there is no bind method to call.
I attempted to fix this by creating my own monad interface but this didn't work:
1: type Monad =
2: abstract Bind : 'm * ('a -> 'm) -> 'm 3: abstract Delay : (unit ->'m) -> 'm
4: abstract Let : 'a * ('a -> 'm) -> 'm 5: abstract Return : 'a -> 'm
6: abstract Zero : unit -> 'm
7: abstract Combine : 'm -> 'm2 -> 'm3
8: abstract Run : (unit ->'m) -> 'm
After playing with that and failing I ended up with a less than ideal solution. Given a Maybe monad like below:
1: // Maybe Monad
2: type MaybeBuilder() =
3: member b.Return(x) = Some x
4: member b.Run(f) = f()
5: member b.Delay(f) = f
6: member b.Let(p,rest) = rest p
7: member b.Zero () = None
8: member b.Combine(m1,dm2) = match m1 with
9: | None -> dm2()
10: | x -> x
11:
12: member b.Bind(p,rest) = match p with
13: | None -> None
14: | Some r -> rest r
I created a state transformer monad which take an argument of type m:MaybeBuilder
1: type StateMBuilder(m:MaybeBuilder) =
2: member b.Return(x) = fun s -> m.Return (x,s)
3: member b.Run(f) = fun inp -> (f inp)()
4: member b.Delay(f) = fun inp -> fun () -> f() inp
5: member b.Let(p,rest) = rest p
6: member b.Zero () = fun s -> m.Zero()
7: member b.Bind(p,rest) = fun s -> m.Bind(p s,fun (v,s2) -> rest v s2)
8: member b.Combine(p1,dp2) = fun s -> m.Combine(p1 s, dp2 s)
9:
10: // State specific functions
11: member b.Update f = fun s -> try m.Return (s, f s) with e -> m.Zero()
12: member b.Read () = b.Update id
13: member b.Set t = b.Update (fun _ -> t)
Now although this type is technically parameterized ;) it isn't really the idea since its not generic, it has to be a MaybeBuilder. To use this with a different monad I would need to change m:MaybeBuild to m:SomeOtherMonad.
I am still going to play with this but this is as far as I have gotten.
After all of that here is how you create a state transformer monad parameterized over the maybe monad:
1: let maybe = MaybeBuilder()
2: let state = StateMBuilder(maybe)
If anyone has an idea how I can make this work I would love to hear it.
-
When writing a generic function I start from left to right (the same way I write most things except when I took Yiddish in college). For example, Lets say I am writing a simple generic method which return the first element of a generic list. I want the signature of this method to be:
private T First<T>(List<T> list)
I start by writing the visibility:
I then need to write the return type so I type T. The problem is that since T is not defined as a generic type parameter yet so intellisense tries to help me out by showing me all types that begin with T:
Now my instinct here (every time) is to press space since I just want to move on to the next word since T is all I want. But space will auto-complete T with ThreadStaticAtrribute. What I need to do is press esc to close the intellisense window and then press space. This may seems like a silly issue, but I seem to never remember that I need to do this.
Visual Studio and intellisense have done nothing wrong here , I just wish intellisense had the ability to read my mind and understand exactly what I am intended to do. It could save me a couple key presses a day!
-
A few days ago I made a post about using SQL CE 3.5 with LINQ to SQL. I described a way to use connection pooling with SQL CE. A gracious blog reader (Mike Brown) pointed out a way I could make my solution much simpler by using the [ThreadStatic] attribute. I never heard of this attribute but it is really nifty. You mark a field with it and then each thread that accesses that field will be accessing a unique instance of it!
Using this attribute my code for connection pooling went from this:
/// <summary>
/// Manages open connections on a per-thread basis
/// </summary>
public class ConnectionPool
{
private Dictionary<int, IDbConnection> threadConnectionMap;
/// <summary>
/// Gets the connection string.
/// </summary>
/// <value>The connection string.</value>
public string ConnectionString
{
get;
private set;
}
/// <summary>
/// Gets a connection.
/// </summary>
/// <returns>An open connection</returns>
public IDbConnection Connection
{
get
{
lock (threadConnectionMap)
{
int threadId = Threading.Thread.CurrentThread.ManagedThreadId;
IDbConnection connection = null;
if (threadConnectionMap.ContainsKey(threadId))
{
connection = threadConnectionMap[threadId];
}
else
{
connection = new SqlCeConnection(ConnectionString);
connection.Open();
threadConnectionMap.Add(threadId, connection);
}
return connection;
}
}
}
/// <summary>
/// Initializes a new instance of the <see cref="ConnectionPool"/> class.
/// </summary>
/// <param name="connectionString">The connection string.</param>
public ConnectionPool(string connectionString)
{
threadConnectionMap = new Dictionary<int, IDbConnection>();
ConnectionString = connectionString;
}
to this:
/// <summary>
/// Manages open connections on a per-thread basis
/// </summary>
public class ConnectionPool
{
[ThreadStatic]
private IDbConnection threadConnection;
/// <summary>
/// Gets the connection string.
/// </summary>
/// <value>The connection string.</value>
public string ConnectionString
{
get;
private set;
}
/// <summary>
/// Gets a connection.
/// </summary>
/// <returns>An open connection</returns>
public IDbConnection Connection
{
get
{
if (threadConnection == null)
{
threadConnection = new SqlCeConnection(ConnectionString);
threadConnection.Open();
}
return threadConnection;
}
}
/// <summary>
/// Initializes a new instance of the <see cref="ConnectionPool"/> class.
/// </summary>
/// <param name="connectionString">The connection string.</param>
public ConnectionPool(string connectionString)
{
ConnectionString = connectionString;
}
}
Very nice and clean.
Thanks Mike!
-
Some History
The Snippet Designer was started as an intern project of mine during the Summer of 2006. The idea was to make snippet files (which were introduced to Visual Studio in 2005) a first class entity. Following this idea I created a Visual Studio plug-in which included an editor for snippet files and a search tool window to find snippets. The plan then was to release it on Codeplex but when my internship ended the project was forgotten about.
Today
Now after two year of sitting there I found the code, cleaned it up a bit and am releasing it on Codeplex as an open source project at http://www.codeplex.com/SnippetDesigner. My goal in releasing it on Codeplex is two fold. First I would like people to try it out, give me feedback and see if we can make it better (it still has plenty of rough edges). Second I would love to turn this into a community developed project where we all can collaborate on it.
Features
The Snippet Designer has two main features:
A Snippet Editor hosted in the IDE which lets you edit the code, make replacements and change snippet properties:
A Snippet Explorer which lets you search for Snippet files on your computer an quickly open and edit them.
In addition to these two features the plug-in adds a context menu item inside of the VB, C# and XML editor that lets you export any highlighted code into the snippet editor:
Getting Started
After installing the Snippet Designer you are ready to create and edit snippets. Either open up any .snippet file or in Visual Studio go to View -> Other Windows -> Snippet Explorer and use the Snippet Explorer to search for snippets.
I look forward to any and all feedback!
-
Using LINQ to SQL with SQL CE 3.5 can be a bit of a challenge. First off, the LINQ to SQL Visual Studio designer doesn't support SQL CE so you need to run sqlmetal from the command line to create the object model (or write it by hand). Once you get past this point then you can use LINQ to SQL the same way you would for SQL Sever BUT there is a catch.
The way LINQ to SQL is built makes it work well with SQL Server and its connection pooling ability. If you look at this FAQ under the "Database Connection: Open How Long?" section it says:
A connection typically remains open until you consume the query results.
Therefore given the following code:
1: using(Northwind db = new Northwind(MyConnectionString))
2: {
3: (from p in db.Products).ToList();
4: (from p in db.Customers).ToList();
5: }
On line 3 and 4 in the above code will open a database connection (which will be pulled from the open connections in connection pool), execute the query, and then close the connection after the operation is completed (which will return the connection to the pool).
This works great with connection pooling but when you move to SQL CE you don't have that luxury. What happens now is that for each query a new SQL CE connection will be opened, the query will be executed and then the connection is closed. Each query is incurring the cost of opening a new connection. To make matters even worse, in SQL CE the first open connection brings the database engine into memory, and once you have no open connections anymore it removes the engine from memory. What this means is that each time we close the only open connection and then re-open we are incurring a HUGE cost.
One way to get around this is to pass into the DataContext an open SQLCeConnection object. LINQ to SQL will only automatically close a connection if it opens it. Therefore, if you pass it an open connection then you won't incur this cost over and over again. This will work fine in a single threaded application but once you move to a mutlithreaded app where you are performing database operations from different threads you encounter a problem: The SQLCeConnection object is not thread safe. You need to have a different connection object per thread in order to make this work. What you want is to be able to request a connection from any thread and get an already opened one for that thread. This sounds a lot like a simple connection pooler, which could look something like this:
/// <summary>
/// Manages open connections on a per-thread basis
/// </summary>
public class ConnectionPool
{
private Dictionary<int, IDbConnection> threadConnectionMap;
/// <summary>
/// Gets the connection string.
/// </summary>
/// <value>The connection string.</value>
public string ConnectionString
{
get;
private set;
}
/// <summary>
/// Gets a connection.
/// </summary>
/// <returns>An open connection</returns>
public IDbConnection Connection
{
get
{
lock (threadConnectionMap)
{
int threadId = Threading.Thread.CurrentThread.ManagedThreadId;
IDbConnection connection = null;
if (threadConnectionMap.ContainsKey(threadId))
{
connection = threadConnectionMap[threadId];
}
else
{
connection = new SqlCeConnection(ConnectionString);
connection.Open();
threadConnectionMap.Add(threadId, connection);
}
return connection;
}
}
}
/// <summary>
/// Initializes a new instance of the <see cref="ConnectionPool"/> class.
/// </summary>
/// <param name="connectionString">The connection string.</param>
public ConnectionPool(string connectionString)
{
threadConnectionMap = new Dictionary<int, IDbConnection>();
ConnectionString = connectionString;
}
With this you create a DataContext like this:
1: // Defined somewhere
2: ConnectionPool connectionPool = new ConnectionPool(MyConnectionString);
3:
4: // ...
5: // ...
6:
7: using(Northwind db = new Northwind(connectionPool.Connection))
8: {
9: (from p in db.Products).ToList();
10: (from p in db.Customers).ToList();
11: }
Now each thread will have its own open connection which will minimize the cost of opening connections.
-
Well, maybe not best friend but its a nice function. When working with bound collections in WPF you often end up dealing with a CollectionView. This is the MSDN documentation description of a CollectionView :
You can think of a collection view as a layer on top of a binding source collection that allows you to navigate and display the collection based on sort, filter, and group queries, all without having to manipulate the underlying source collection itself.
As stated above the main use of the CollectionView is to enable modifying the visible collection without actually changing the underlying data. In the application I am working on I let the user change what a ListBox is sorted by. This is the code I originally had:
1: ICollectionView dataView = CollectionViewSource.GetDefaultView(listBox.ItemsSource);
2: dataView.SortDescriptions.Clear();
3: SortDescription sd = new SortDescription(newField, ListSortDirection.Ascending);
4: dataView.SortDescriptions.Add(sd);
The problem with this code is that it causes the view to refresh twice! The Clear and Add function both trigger a SortDescriptionsChanged event which leads to a Refresh of the view. This problem becomes worse when you are also adding or changing filter in addition to sort descriptions and your collection is very large. This could visibly slow you application.
This is where my friend DeferRefresh comes in. If you change the code above to this:
1: ICollectionView dataView = CollectionViewSource.GetDefaultView(listBox.ItemsSource);
2: using (dataView.DeferRefresh())
3: {
4: dataView.SortDescriptions.Clear();
5: SortDescription sd = new SortDescription(newField, ListSortDirection.Ascending);
6: dataView.SortDescriptions.Add(sd);
7: }
Now the CollectionView will only be refreshed once! All the methods inside the using block will no longer cause a refresh, they will just indicate that a refresh is needed. Then when the code leaves the using block the method EndDefer() is called which just refreshes the CollectionView if needed.
-
I decided to do some Project Euler problems using F#.
So here is my first one, Problem # 31. Nothing in this solution really shows off anything special about F# but you have to start somewhere ;)
1: #light
2:
3: let rec combos amt (denoms:int list) =
4: if amt = 0 then 1
5: elif denoms.IsEmpty || amt < 0 then 0
6: else
7: combos (amt - denoms.Head) denoms +
8: combos amt denoms.Tail
9:
10:
11: printf "\n\nThe Anwer is: %i \n" (combos 200 [200;100;50;20;10;5;2;1])
12:
-
Quick code snippet time!
The following are generic methods for inserting and updating a detached entity into a database using LINQ to SQL.
1: /// <summary>
2: /// Updates the database with item.
3: /// </summary>
4: /// <typeparam name="T">Type of the item</typeparam>
5: /// <param name="item">The item.</param>
6: public static void UpdateDatabaseWithItem<T>(T item) where T : class
7: {
8: var store = GetNewDataContext();
9: var table = store.GetTable<T>();
10: table.Attach(item);
11: store.Refresh(RefreshMode.KeepCurrentValues, item);
12: store.SubmitChanges();
13: }
14:
15:
16: /// <summary>
17: /// Inserts the item into database.
18: /// </summary>
19: /// <typeparam name="T">Type of the item</typeparam>
20: /// <param name="item">The item.</param>
21: public static void InsertItemIntoDatabase<T>(T item) where T : class
22: {
23: var store = GetNewDataContext();
24: var table = store.GetTable<T>();
25: table.InsertOnSubmit(item);
26: store.SubmitChanges();
27: }
GetNewDataContext() is a method (not shown) which does what its name says, returns a data context.
The only part that is not really obvious is on line 11. That line is a "hack" to allow you to attach an entity as modified without using a timestamp or turning off optimistic concurrency or attaching a previous version of the entity. What this means is that this update will throw a fit if there is a concurrency error! However, for my use of this code ( mainly for unit test preparation ) it works great.
-
Take a look at the following code:
1: var sw = new Stopwatch();
2: sw.Start();
3: Enumerable.Range(0, 3).SelectMany((i) => Enumerable.Range(0, 50000)).OrderBy(i => i).ToList();
4: Console.WriteLine(sw.ElapsedMilliseconds);
5:
6: sw.Reset();
7: sw.Start();
8: Enumerable.Range(0, 2).SelectMany((i) => Enumerable.Range(0, 50000)).OrderBy(i => i).ToList();
9: Console.WriteLine(sw.ElapsedMilliseconds);
10: sw.Reset();
Line 3 is saying:
Generate a list which looks like 0,1,2..49999,0,1,2..49999,0,1,2..49999
Then Sort it.
While Line 8 is saying:
Generate a list which looks like 0,1,2..49999,0,1,2..49999
Then Sort it.
If you run this program you will see that line 3 executes ( depending on your machine) in less than a second while line 8 executes in around 30 seconds. This may jump out as really strange at first since you are sorting less numbers in line 3. But that isn't the issue in this scenario. The issue is the sorting algorithm.
Underneath the covers the OrderBy function is using a version of QuickSort. The version of quicksort used always chooses the middle element of the list as the pivot position. Since both left and right lists will always be sorted we hit the worst case of this quicksort algorithm which is O(n^2).
-
I have been working a lot with WPF and I found the following two FREE tools to be extremely helpful.
The first is:
XamlPadX - (http://blogs.msdn.com/llobo/archive/2007/12/19/xamlpadx-v3-0.aspx)
This is an enhanced version of XamlPad which comes with the .NET SDK. This is a light weight tool which parses and renders XAML code visually. It adds (in addition to just rendering XAML) a command interpreter, visual tree explorer, add-in support and much more.
I find this tool very usefull when I want to just play around with XAML and see how things render. It is quicker than firing up VS and using the Cider designer.
