Skip to main content

Posts

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();

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

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 perspect...

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 ...

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(); } );

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) }

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

C# code to parse an x9.37 file

The following C# code will parse an X937 file (Image Cash Letter) and get the amounts of each check // BigEndianBitConverter class taken from http://www.yoda.arachsys.com/csharp/miscutil/ // ConvertEBCDICtoASCII method taken from http://kseesharp.blogspot.com/2007/12/convert-ebcdic-to-ascii.html static void Main(string[] args) { var input = new BinaryReader(new FileStream("YourICLFile.icl",FileMode.Open)); byte[] amount_bytes, record_type_bytes; byte[] record_lenght_bytes = input.ReadBytes(4); var converter = new BigEndianBitConverter(); int record_lenght = converter.ToInt32(record_lenght_bytes,0); string record_type, amount_str; //Totals long check_items= 0, total_amount = 0; try { while (true) { //Get record type record_type_bytes = inpu...

How to extract data from MS Word dropdown fields

When converting a Word form to a web form, I was looking for a way to extract the items of the dropdown fields found in the Word document to avoid typing them manually in my web app. I found that you can access the field definitions from C# by using the Word  Interop COM library. The following is a program that extracts each item in the dropdown boxes and prints them to the screen: using System; using System.Collections.Generic; using System.Linq; using System.Text; using Microsoft.Office.Interop.Word; namespace WordDataExtractTest { class Program { static void Main(string[] args) { Application wordapp = new Application(); var strDocName = "doc_file_with_form.doc"; var doc = wordapp.Documents.Open(strDocName); foreach( FormField form_field in doc.FormFields) { if (form_field.Type == WdFieldType.wdFieldFormDropDown) { Ad...

How to get the raw data posted to a Java Servlet

While working in porting GeneCMS to Google App Engine and Silverlight , I stumble at one annoying problem: how to get the raw data that was sent by the browser via a POST. In this GeneCMS port, the silverlight client actually generates all the HTML that the server used to generate. The raw generated HTML is then sent to the GAE application, with some metadata about the generated pages. The GAE servlet then reads the posted data as a string and extract the individual generated pages. Each generated page is then saved into the GAE database to allow the CMS to server the pages. After tweking around in the wrong places, I finally found out that HttpServletRequest’s getInputStream method is an input stream to the raw data posted. So I modified my servlet to get the POST data into a string like this: String posted_data = ""; BufferedReader in = new BufferedReader(new InputStreamReader( request.getInputStream())); String line = in.readLine(); while (line != null) { posted...

How to watch for a file in a folder in VBS and handle locked files

The following Visual Basic Script allows you to  monitor a folder for new files. The script will try to process the file if the file is still locked by the application that created the file, an error will occur and the script will handle it by waiting a growing amount of time and then retrying to use the file. The script will also send an email alert about the error raised: strComputer = "." strPathToWatch = "C:\backups\" Sub SendMailMessage(to_address, subject, msg) dim sch, cdoConfig, cdoMessage sch = "http://schemas.microsoft.com/cdo/configuration/" Set cdoConfig = CreateObject("CDO.Configuration") With cdoConfig.Fields .Item(sch & "sendusing") = 2 ' cdoSendUsingPort .Item(sch & "smtpserver") = "yoursmtpserver" .update End With Set cdoMessage = CreateObject("CDO.Message") With cdoMessage Set .Configuration = cdoConfig ...

Class to get Live Photo and Album Information in .NET

Thanks to the Windows Live Spaces Photo Album plugin project at CodePlex, I was able to abstract the code to get Album and Pictures information from a Live Spaces account. This class serves as a helper when generating javascript code for slideshows containing photos stored at Live Spaces. using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Xml; using HtmlAgilityPack; using System.Web; namespace LivePhotoDataProvider { public class AlbumInfo { public string URL { get; set; } public string Name { get; set; } } public class PhotoInfo { public string FullSizeURL { get; set; } } public class LivePhotoData { public List<AlbumInfo> GetAlbums(string live_spaces_link) { List<AlbumInfo> albums = new List<AlbumInfo>(); XmlDocument doc = new XmlDocument(); try { doc.Load(live_spaces_link); ...

Using SQL Server’s XML features as a fast ORM

When you need load POCO objects from a SQL Server database in a faster way than LinqToSQL, you may consider using  SQL Server’s XML features.  The FOR XML PATH command can be a really powerful tool to convert your relational data into XML that C# can de-serialize into C# plain objects. The key is to find how C# serializes objects to XML. In order to do that, I did a small test: public class Store { public string Name { get; set; } public int Sales { get; set; } public List<StoreContact> StoreContact { get; set; } } public class StoreContact { public int ContactId { get; set; } public int ContactTypeID { get; set; } } public static void TestSaveToXML(string path) { XmlSerializer serializer = new XmlSerializer(typeof(List<Store>)); TextWriter writer = new StreamWriter(path); List<Store> stores = new List...

Model Generator Helper Released

Model Generator Helper is a small program that will allow you to easily create view models from your logic models by copying the logic model's properties and the properties' attributes. The original purpose of the program was to copy the validation annotations to my view models so that I would not have to copy and paste them. The program can also read the ColumnAttribute of Linq2SQL generated classes and create DataAnnotation attributes for them (e.g.: Requires attribute and the StringLength attribute). Sometimes you want to pass to your views a class different from your raw classes generated from the database. For example, lets say we have this logical model classes: class Payment { [Max(1200)] public int Amount {get; set;} public int PersonID {get; set;} } class Person { [ StringLength (50)] public string Name {get; set;} public int PersonID {get; set;} } And you need a View model for your view that allows the user to edit the name of the pe...

Send Email from C# using Outlook's COM late binding

The following sample code shows how to send emails from Outlook and Exchange using C#. This code works with any version of Outlook because it uses Late Binding to automate Outlook. Parts of the code where taken from other websites. using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Reflection; using System.Threading; namespace LateBindingTest { class OutlookEmailerLateBinding { private object oApp; private object oNameSpace; private object oOutboxFolder; public OutlookEmailerLateBinding() { Type outlook_app_type; object[] parameter = new object[1]; //Get the excel object outlook_app_type = Type.GetTypeFromProgID("Outlook.Application"); //Create instance of excel oApp = Activator.CreateInstance(outlook_app_type); //Set the parameter which u want to set parameter[0] = "MAPI...

Batch file to encrypt connection string section

Many times I have to use SQL Authentication instead of Windows Aunthentication when developing ASP.NET web apps. To encrypt the connection string used you can use the following batch file to encrypt the connection string sections of any asp.net web app: echo Please enter folder where webconfig is: :input set INPUT= set /P INPUT=Type input: %=% if "%INPUT%"=="" goto input echo Folder where webconfig is: %INPUT% aspnet_regiis.exe -pef connectionStrings %INPUT% pause Make sure you have aspnet_regiis.exe's folder in your PATH environment variable.

Sending/Receiving Faxes as Emails in Windows

Most Fax server software allows you to send/receive faxes through email. While looking at the alternatives, I could not find any free, Windows based solution that suited my needs. Most of the software I looked at requires you to have a dedicated smtp server or DNS settings in your local network. I developed Email-to-Fax Server to work with an already established SMTP and POP server (it requires an email account) and decided to make it open sourced at CodePlex . Email-to-Fax Server’s foundation is the excellent Fax .NET library . The program is developed in C# and uses the internal Windows's Fax services as its foundation. Email-to-Fax Server is a windows application that does the following: Sends email attachments as faxes. Sends faxes received as email attachments to a specified address or addresses. It obtains emails from a POP email account and sends the emails' attachments as faxes to the fax number specified in the subject line. It uses a SMTP account to ...

How to enter multiple users into ActiveDirectory 2008 from a CSV

To create multiple users into ActiveDirectory 2008 Server from one single CSV file containing the users login information, you can use the following wsf file: 1: <job id= "main" > 2:   3: <script language= "VBScript" > 4: dim text_out 5: text_out = "" 6: Dim oContainer 'Parent container of new user 7: Dim oUser 'Created user 8: 'Get parentcontainer 9: Set oContainer=GetObject( "LDAP://OU=yourouname, DC=your,DC=domain,DC=local" ) 10: 'Read the file with user information 11: Const ForReading = 1 12: Set objFSO = CreateObject( "Scripting.FileSystemObject" ) 13: Set objTextFile = objFSO.OpenTextFile _ 14: ( "users.txt" , ForReading) 15: D...

How to do control breaks in Excel

One of the problems I find when exporting from RenWeb is that the names of the staff are repeated in every row when exporting to Excel. To make control breaks on the staff name (i.e. show the name only once) in excel you can use the following formula: =IF(B1=B2,"",B2) Change the B to the column that contains the names. The formula will set the cell blank if the contents of the current row in the B column is the same as the one in the previous row.