Saturday, February 04, 2012

There is already an open DataReader error and how to fix it

When trying to execute SaveChanges on a Entitiy Framework datacontext, I was getting the following error:

There is already an open DataReader associated with this Command which must be closed first

The problem was caused by the location of the SaveChanges call. The code called the method inside a ForEach loop that iterates through a result returned from a query. Because of the iteration the datacontext’s connection was on read mode and thus did not allow me to call the update. To fix it I moved the SaveChanges call outside the ForEach loop (when the read was completed:

var records = EFDataRepository.GetAll().Where(r => r.CreatedOn < cutoff_date);
foreach (var record in records)
{
	workflow.WorkAndUpdate(record);
	//repo.SaveChanges(); //do not put it here, you are still iterating over the results in read mode
}
repo.SaveChanges();

Thursday, November 03, 2011

Attachment does not show in Outlook when sent from Cognos Report Server

If you use Cognos ReportServer and have a scheduled report that is sent by email, you may get into a peculiar problem when sending the report to recipients in an Exchange 2007: the attachment will not show if the recipient sees the email in his Outlook client. For some reason it will be displayed in any other email client they might use (smartphone, webmail, etc) but not in the Outlook installed in their desktop.

A solution to this problem is to make sure the scheduled report contains text in both the subject and the body of the email being sent. You can do that from the email options in the Cognos when scheduling the report. You need to make sure the subject and the body is populated even if it is just a word.

A clue to what causes this problem is found in the following link:

http://www.eggheadcafe.com/microsoft/Exchange-Admin/31852947/exchange-2007-hidden-attachments.aspx

Saturday, October 15, 2011

Friends Guess is now available in the Marketplace

My new Windows Phone 7 game, Friends Guess was recently approved in the Zune marketplace. It is now available to Windows Phones.

To play Friends Guess you are given the name of one of your Facebook friends and then you have to match the name to one of six profile pictures in the screen. It is a fun way of keeping up to date with your friend’s profile pictures. You will be surprise at the pictures your friends choose for their profiles; I sometimes ask myself, “is that their profile picture now? no way…” when playing the game. The idea of the game came from wife, while we were driving back from our vacation in Virginia.

There is a web based version of the game at http://friendsguess.appspot.com if you don’t have a Windows Phone. This web version should work on the iPhone too and possible Android phones (depending on your OS version). The web version has a slightly different scheme for scoring, but the mechanics are as fun as the Windows Phone version.

From a programming perspective, it was a lot of fun to learn the Facebook Graph API, which is incredibly well designed to work with pretty much any programming language that can do web requests. For the Mango version of the game, however, I was able to take advantage of the Facebook integration on Windows Phone 7 and pulled friend’s Facebook profile picture straight from the phone contacts. Something like this:

public void GetPics()
{

	Contacts cons = new Contacts();

	//Identify the method that runs after the asynchronous search completes.
	cons.SearchCompleted += new EventHandler<ContactsSearchEventArgs>(Contacts_SearchCompleted_One);

	//Start the asynchronous search.
	cons.SearchAsync(String.Empty, FilterKind.None, "My app");
}

void Contacts_SearchCompleted_One(object sender, ContactsSearchEventArgs e)
{
	LinkedList<FacebookPicturePair>  friends = new LinkedList<FacebookPicturePair>();
	try
	{
		foreach (Contact con in e.Results)
		{
			if (con.Accounts.Any(a => a.Kind == StorageKind.Facebook))
			{
                        BitmapImage img = new BitmapImage();
                        img.SetSource(con.GetPicture());
                        friends.AddLast(new FacebookFriend() { Picture = img, Name = con.DisplayName });
			}
		}
	}
	catch (Exception)
	{
		//We can't get a picture of the contact.
		//.. error handling here
	}
	return  friends;
}

Friday, July 08, 2011

Idea: Separate non-violent inmates from violent inmates

Why do we put in the same jail violent criminals with non-violent criminals? As far as i know (please correct me if i am wrong), the current system sends non-violent offenders to the same place as violent offenders. Would it not be better to put nonviolent criminals to forced labor to repay their debts to society? I am thinking of large working camps, where they would be forced to labor 6 days a week on hard-work or dangerous places where manual labor is hard to find. These working camps would allow them to sleep in tents or some sort of cabins. Security could be minimal since there would be only non-violent offenders. Would any non-violent offender prefer to go to such a “working camp” than to go to a jail full of gangs and murderers? I would think they would love to have that choice.

Separating violent from non-violent criminals would allow the Government to make penitentiaries across the nation less “cozy”. Let the violent criminals live in one cell (one per cell) and never allow them to get out of the cell (for their own protection and the other inmates). Meals would be distributed to the cells and cells would have plenty of room for inmates to stretch. Isolating them from the external world and other inmates could help society break down the gangs that are controlled from inside jails. Showers would be administered by a hose spraying through the cell bars. Health care to those inmates could be reduced to the bare minimum, no more $30,000 surgeries paid by the Government; why would a violent criminal get a free surgery when many honest people can’t afford one? All of these suggestions may make jails cheaper to run. Would that be too much torture for an inmate? if you see them as violent criminals who were found guilty by a jury of their peers, the answer is no; it is exactly what they deserve for daring to attack another human being.

If you agree with me (at least somewhat), please make sure your public servants who are in charge of the penal system know your opinion about it. And although it will be nice if you add your comment in this blog or Facebook, it won’t do too much if you don’t express your sentiment with the Government.

Tuesday, June 14, 2011

Using lambdas to wrap model validations in C#

In .NET, I have found the following method useful when wrapping validation around any CRUD operation:

private IEnumerable<ValidationResult> PerformWithModelValidation(object model, Action code_to_execute)
        {
            var results = new List<ValidationResult>();
            ValidationContext context = new ValidationContext(model, null, null);
            bool valid = Validator.TryValidateObject(model, context, results, true);
            if (valid)
            {
                code_to_execute();
            }
            return results;
        }

//How to use the method above:

PerformWithModelValidation(new_product, () =>
{
	MyRepository.Add(new_product);
	MyRepository.SaveChanges();
}
);

Saturday, April 09, 2011

Powershell script for converting JPG to TIFF

The following Powershell script will convert a batch of JPEG files to TIFF format:

#This Code is released under MIT license

[System.Reflection.Assembly]::LoadWithPartialName("System.Drawing")  
 
$files_folder = 'C:\path-where-your-jpg-files-are\'

$pdfs = get-childitem $files_folder -recurse | where {$_.Extension -match "jpg"}

foreach($pdf in $pdfs)
{
    $picture = [System.Drawing.Bitmap]::FromFile( $pdf.FullName )
    $tiff = $pdf.FullName.replace('.PDF','').replace('.pdf','').replace('.jpg','').replace('.JPG','') + '.tiff'
    $picture.Save($tiff)
}

Wednesday, February 02, 2011

Powershell script to list the binary paths of SQL Instances

You can use Powershell with WMI to find out the paths where the binary files of SQL instances reside. The following code will display the path to the binaries for each instance installed in a server (replace yourservername with your server name):

SQL Server 2005:

Get-WmiObject -ComputerName  YOURSERVERNAME -namespace 'root\Microsoft\SqlServer\ComputerManagement' -query "SELECT ServiceName, BinaryPath FROM SqlService WHERE SQLServiceType = 1 and ServiceName like '%SQL%'" | ft -property ServiceName, BinaryPath

SQL Server 2008 or SQL Server 2008 R2:

Get-WmiObject -ComputerName  YOURSERVERNAME -namespace 'root\Microsoft\SqlServer\ComputerManagement10' -query "SELECT ServiceName, BinaryPath FROM SqlService WHERE SQLServiceType = 1 and ServiceName like '%SQL%'" | ft -property ServiceName, BinaryPath