LINQ Sequence contains more than one element

Recently I ran into an issue with the contains method in LINQ in conjunction with the SingleOrDefault method.

My query was similar to:

var data = (from i in ctx.DataContext.orders
where order.Contains(i.Name)
select i).SingleOrDefault();

and this was throwing the error:

System.InvalidOperationException: Sequence contains more than one element

Turns out the Contains translated to a LIKE '%...%' and was returning multiple records.  By changing this to i.Name == order, then I got back the single result I was expecting.

jQuery with ASP.NET selected index changed

Recently I had the need to handle the selected index changed event in an ASP.NET page.  I did not want to post back to the server as I just wanted to hide/show an HTML element, so jQuery was the perfect fit.

Below is the code.  Basically, within the jQuery document ready funciton, I wire a function to each dropdown list ('select') change event.  You will probably want to refine this to a single id or class.  Each time the dropdown selected index changes, I want to check the text value, and if it contains some text, either show or hide an HTML element.  I also set a checkbox control to checked using the client id within a script tag.

<script type="text/javascript">

$(function() {

$('select').change(function(e) {

if (this[this.selectedIndex].text.indexOf("SomeText") > 0) { $('#emailActivity').fadeIn("slow");

// Ensure checkbox initially checked

$('#<%=cbSendEmail.ClientID %>').attr('checked', true);

}

else {$('#emailActivity').fadeOut();

}

});

});

</script>

Delete not working with LinqDataSource

Recently I was working on a custom page in a Dynamic Data project and the "Delete" link was not working on a GridView that had a LinqDataSource as its data source.  Below are the steps I followed to resolve:

First, I was getting an error when clicking delete for a record in the GridView

LinqDataSource 'GridDataSource' does not support the Delete operation unless EnableDelete is true.' when calling method

This was fixed easily by setting EnableDelete="true" on the LinqDataSource.

Next up, I needed to set the DataKeyNames on the GridView.  This basically indicates what the where condition will be for the delete operation.  I set the GridView DataKeyNames equal to the name of the primary key column in my table.

That will probabaly resolve for most people, but for me, it did not.  I had also set the Select property on the LinqDataSource and this was preventing the delete from occuring.  Once I REMOVED the value for this propery, all worked.

The below article was helpful in diagnosing:

http://msdn.microsoft.com/en-us/library/bb514963.aspx

 

ASP.NET how to prevent sending emails while developing

There are times when developing that I want to be able to see what the contents will be for emails generated from my application, but I do not want the emails to actually go to the reciepients.  In addition I may not have my local development machine set up to relay mail.

Sometime, updating the development system email addresses to a generic address makes sense.  Other times, I do not or cannot do this, so instead, I opt for the following technique.

With this approach, you add a configuration setting to your config file, and the result is that the email will be placed in a directory of your choosing, but will not actually be sent.

To accomplish this, add the below setting to your config file:

 <system.net>
    <mailSettings>
      <smtp deliveryMethod='SpecifiedPickupDirectory'>
        <specifiedPickupDirectory pickupDirectoryLocation="C:\All\Maildrop" />
      </smtp>
    </mailSettings>    
  </system.net>

 Now, when you send your email using code similar to below, the email will appear in the directory you specified.

 MailMessage message = new MailMessage();
 message.From = new MailAddress(...

... other code to set to, body goes here

SmtpClient smtpClient = new SmtpClient();
smtpClient.Send(message);

 

Debugging a Windows Service

If you are using Visual Studio and you want to debug a windows service, you may recieve the following message:

Cannot start service from the command line or a debugger.  A Windows Service must first be installed (using installutil.exe) ...

There are ways to avoid this message and this site provides a good approach http://www.worldofasp.net/tut/WindowsService/Creating_Windows_Services_in_NET_99.aspx

I have also found that in Visual Studio if you have a break point set within your service and you run the service in debug mode you can just leave the message pop up in place.  Basically, if you get the pop up, but do not click out of it, just leave things as they are and wait for the first "tick" in your service, it will then run and hit your break point.  This seems to be a work around and hopefully if you are in a pinch and need a quick way to debug a service, this will work for you.

LINQ to SQL Connection Strings

When using the LINQ to SQL designer surface in Visual Studio, each time you add an object (table, procedure, etc), you will end up adding connection string information to your config file.  This can be confusing as the names used for the connection string may be different then what you want to use and you may end up with multiple connection strings, especially if you have multiple developers working on the same project.

To address this issue, you can:

  1. Create a partial class for your data context and create a parameter-less constructor as follows

    public partial class LinqAppDataContext
        {
            public LinqAppDataContext()
                : base(ConfigurationManager.ConnectionStrings["AppConnectionString"].ToString())
            {

            }
        }

    In this example, I already have a LinqAppDataContext class, and I am creating a partial class that calls the constructor on the base class that takes a connection string.  I then pull this connection string from the config file.

  2. Step 1 is a one time setup.  The remaining steps need to be followed each time you add a new object to the designer surface

  3. Add a new object to the designer surface (for example, drag a table from the Server Explorer)

  4. Click on an empty section of the designer surface (dbml file)

  5. In the properties window, go to Connection, then clear the information from the Connection String property and then set the Application Settings property to false.  By doing this, the parameter-less constructor from step 1 above will kick in and pull the connection string from your config file.

  6. Verify that no extra connection strings have been added to your projects settings or config files
Hopefully this will help you in clearly knowing which connection string will be used with your LINQ to SQL context classes.

Feed.Us Content Management for the rest of us

Feed.us provides an innovative solution to a common need; Content Management for your web site.  Often when you have a web site you have a need to modify the content of your site on a regular basis.  In the past this was accomplished with rather involved approches that require a fair amount of setup and custom development.

Feed.us provides content management in the "cloud".  To start using this service all you need to do is add a small snippet of text to your site and then you use the Feed.us site to manage your content.  For example, if you have a home page that you want to schedule content updates, you can easily go to the Feed.us site, enter the content you want to appear on your site, schedule it, and then have it appear.  You also have total control over adding images, videos, and styling the content to appear as you like.

They are currently updating their site and offerings, including being able to email content as well as post content to your site using Google Docs and Microsoft Word.  This means you can create content in an editor you are familiar with and with a couple of clicks, publish the content to your site.

One of the best parts of Feed.us is that it allows you to focus on your business...you do not need to spend time learning a particular technology or tool, Feed.us abstracts away those complexities freeing you to concentrate on improving your business.

Check out their site and how it works

Using a Rich Text Editor with Dynamic Data

In the following post I will outline how to use the FCKeditor in a Dynamic Data project.  Using the FCKeditor is straight forward especially if you use the .NET FCKeditor control.

Steps:

  1. Read the liscensing and terms of use for the FCKeditor
  2. Download the FCKeditor .Net control, dll, and add a reference
  3. Download the FCKeditor fckeditor dir and all sub dirs/files...place these in the root dir of your Dyanamic Data project
  4. In your dynamic data project, in the Field Templates directory, Add new item -> Dynamic Data Field
  5. Delete the FCkEditor.ascx as we will only be using the control for editing
  6. In FCKeditor_Edit.ascx, remove all of the controls, then add

    <%@ Register Assembly="FredCK.FCKeditorV2" Namespace="FredCK.FCKeditorV2" TagPrefix="FCKeditorV2" %>
    <FCKeditorV2:FCKeditor ID="TextBox1" Value='<%# FieldValueEditString %>' runat="server"></FCKeditorV2:FCKeditor>
  7. In the code behind, you want to end up with the below (you will want to modify to add your own trickery...)

    protected void Page_Load(object sender, EventArgs e) {

    }

    protected override void ExtractValues(IOrderedDictionary dictionary) {

         dictionary[Column.Name] = ConvertEditedValue(TextBox1.Value);

    }

    public override Control DataControl {

         get { 

              return TextBox1;

         }

    }

  8. Now, create a partial class in the same namespace as your dbml (LINQ) classes...I will be using the FCKeditor for text areas for my LINQ class "AttempPending"

    *Important thing to note is that the UIHint needs to be the name of your user control (minus the _Edit)...for this example, my user control is named "FCKeditor_Edit.ascx"

    [MetadataType(typeof(AttemptPending_Meta))]

    partial class AttemptPending {

         public class AttemptPending_Meta {           

              [UIHint(
    "FCKeditor")]
             
    public object DescriptionLong { get; set; }
         }
    }

    The net result of the above is that when you use a DynamicData field that binds to the Property DescriptionLong, it will render with the FCKeditor

  9. In the page that you would like the FCKeditor, you would add the following (In my case, this is within a DeatilsView)

    <asp:DynamicField DataField="DescriptionLong" HeaderText="Description Long" />  

    And that should result in the FCKeditor appear on your page...

Install apache and php on Windows

The following instructions are for installing apache and php on Windows XP:

  1. Download the apache msi from the apache website
  2. Run the msi, you can use localhost for the Domain and Server.  The admin email can be what you like
  3. If you choose the default install dir, the files will be placed at C:\Program Files\Apache Software Foundation\Apache2.2
  4. By defualt the "home" directory is htdocs
  5. If you are running IIS on the same server, it will be using port 80, so you need to change apache to use another port to do this edit the conf\httpd.conf file:

    Listen 8000

    ServerName localhost:8000

  6. Restart apache, then you should be able to browse to http://localhost:8000
  7. If you want to change the home directory edit httpd.conf:

    DocumentRoot "C:\All\htdocs"

    and change the <Directory...> to
    <Directory "C:/All/htdocs">

  8. Next for the php install, download the latest php zip file (I downloaded php-5.2.8)
  9. Unzip to program files\php-5.2.8
  10. Copy php.ini.dist to C:\Windows and rename to php.ini
  11. Now we configure apache to run php
  12. Copy php5ts.dll to the bin dir under your apache install directory
  13. Edit http.conf to include:

    LoadModule php5_module "C:/Program Files/php-5.2.8/php5apache2_2.dll"
    AddType application/x-httpd-php .php
    AddType application/x-httpd-php-source .phps

  14. Restart apache
  15. Create a file in your home dir (by default htpdocs) called info.php and add:

    <? phpinfo(); ?>
  16. Browse to http://localhost:8000/info.php and you should see your system info

Ruby on Rails Mysql::Error: Unknown system variable 'NAMES': SET NAMES 'utf8'

If you receive the following error message Mysql::Error: Unknown system variable 'NAMES': SET NAMES 'utf8' when trying to run MySQL with ruby on rails it may be due to the version of MySQL you are running.  I was receiving this error when running a basic ROR app as well as when trying to run a migration rake db:migrate.

Turns out I was using MySQL version 4.0.12-nt which is not supported with the most recent version of rails. 

 I had MySQL 5.1 running on a different port, so I also needed to update the database.yml file to specify the port.  If you need to specify a MySQL port with rails, you need to add port: to the yml file...mine ended up looking like: 

  host: localhost
  port: 3307

 With those changes in place, I was then able to run my rails app and migrations.