Skip to content

Select Into A Dictionary With LINQ

June 9, 2014
tags: , ,

This is neat, instead of doing it the long way, if you need to pull your data into a dictionary, you can do it like this:

 

Dictionary<string, int> facilityNpis = db.Facilities.Where(c => c.NPI.Trim().Length > 0).Select(a => new { a.NPI, a.ID }).AsEnumerable().ToDictionary(b => b.NPI, b => b.ID);

Sort a Bound DropDown In WPF

June 9, 2014
tags: ,

This came up a while back and had me a bit flustered for a bit.  You’re getting some data that you don’t have a ton of control over that you’re binding right into a ddl in WPF and you want to sort it because well, sorting is important.

It isn’t too late!  You can do the following in your constructor and it’ll look fine.

ddlAssignTo.Items.SortDescriptions.Add(new SortDescription(“Username”, ListSortDirection.Ascending));

Rebuild All Indexes On A Database In One Call

June 9, 2014
tags:

Normally I’d leave this sort of thing to a DB to deal with but I stumbled on this a few months back and thought it was rather clever.

USE MyDbName
GO
EXEC sp_MSforeachtable @command1=”print ‘?'”, @command2=”ALTER INDEX ALL ON ? REBUILD WITH (ONLINE=OFF)”
GO
SELECT * FROM sys.Dm_db_index_physical_stats(Db_id(‘MyDbName’),NULL,NULL,NULL,NULL) — This bit just tells you the results

Add a Primary Key To Your SQL DB

June 9, 2014
tags:

It comes up from time to time where you have a DB you need to work with and you notice that some bastard didn’t put a PK on it.

Heres a quick way to wedge that in without too much fuss.

ALTER TABLE Accounts ADD ID int identity(1,1) not null
GO
ALTER TABLE Accounts ADD CONSTRAINT pk_Accounts_ID primary key(ID)
GO

Keeping a Change History With LinqToSQL

June 9, 2014
tags: ,

So in a lot of applications you want to keep track of what your users are doing to your precious data.  What was it and what did they change it to?  I remember setting up entities with a bunch of isDirty flags or adding to a list in set methods which are all fine but if you’re using LinqToSQL, you’re already covered.

Just before you do a submit changes all you have to do is call GetModifiedMembers on your table object.  Like so:

var foo = currentView.db.Accounts.GetModifiedMembers(currentView.EditAccount);

Then you can loop through any and all results to get .Member.Name, or .OriginalValue or .CurrentValue

PS.  I realize that you can just do this invisibly by overriding OnChanging classes but if you need to be selective the above is a solid method.

LinqToSql With NOLOCK

June 9, 2014
tags: ,

This has been something I’ve been meaning to figure out how to do for ages, luckily I stumbled on a great solution by a smart guy named Omar Al Zabir.  You can find his full write up here:

http://msmvps.com/blogs/omar/archive/2009/03/07/linq-to-sql-solve-transaction-deadlock-and-query-timeout-problem-using-uncommitted-reads.aspx

Sometimes you just want a cheap call to populate some info pages, you know it’s a heavy call and you don’t want to lag anything up.  You can do it like this:

using (DeniedDataContext db = new DeniedDataContext())

{

db.ExecuteCommand(“SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED;”); // The important line.

 

You’ll also need to extend your data context like so or you could start leaking connections.

public class DeniedDataContext : DCDBDataContext, IDisposable

{

public new void Dispose()

{

if (base.Connection != null)

if (base.Connection.State != System.Data.ConnectionState.Closed)

{

base.Connection.Close();

base.Connection.Dispose();

}

base.Dispose();

}

}

 

 

Goodbye BackgroundWorker Hello Tasks

June 9, 2014
tags:

So after years of using BackgroundWorkers to properly multi-thread long running operations and not lock up the UI, it is time to go another way and utilize Tasks.  I know this is a bit late but better than never right?  This method also allows for using a different way communicate with the GUI thread for updating progress bars or labels with status messages.  The Progress class is a nice addition and better performing than invoking on controls.

 

Progress<string> prog = new Progress<string>();

prog.ProgressChanged += (a, b) => { lblStatus.Text = b; };

Task<string>.Factory.StartNew(() =>

{

IProgress<string> pro = prog;

pro.Report(“Reporting Something”);

return “Done”;

}).ContinueWith(a =>

{

lblStatus.Text = a.Result;

}, TaskScheduler.FromCurrentSynchronizationContext());

 

The continue with is important because  if you put code under the full block it would get executed at the same time the task is running in the background.  So we do what we want in the ContinueWith so that it happens in the correct order and we use the TaskScheduler.FromCurrentSynchronizatoinContext to ensure that what happens there, happens on the GUI thread.