LINQ to SQL dynamically set order by

by Cliff 16. January 2010

Often I find the need to dynamically specify the order by for a LINQ to SQL query.  I came across a very nice example of this here

I needed to use this technique with a CSLA class, so I needed to call it in a sligthly different manner than the way explained in the article.  I was grouping information and needed to then dynamically set the order by and finally place the results into a CSLA read only list.

I accomplished this as follows:

  1. First I specified my LINQ query and selected the results into an annonymous type and placed into a variable (var data = ...)

  2. Next, called my OrderBy extension method on the LINQ query created in #1

    var ordered = data.OrderBy(criteria.OrderByProperty, criteria.OrderByDesc);


    The criteria object is the typical pattern used in CSLA to pass data to your data access methods such as fetch.

  3. Finally, I selected the data elements into my CSLA list item, and add to the parent list object

    var selected = ordered.Select(a => MyCslaListItem.GetMyCslaListItem(a.Id, a.Name, a.Email, ...));
    this.AddRange(selected);

I understand I could do this in fewer steps, but am leaving as it to explicitly outline the approach taken.

 

 

ASP.NET MVC strongly typed view error Could not load type

by Cliff 5. December 2009

I have been doing some work on a asp.net webforms website that has been "upgraded" to also include the mvc bits.  One issue I ran into was an error when trying to create a strongly typed view.  I was receiving the below exception:

Parser Error Message: Could not load type 'System.Web.Mvc.ViewPage<MyViewModel>'.

I also was not getting intellisense in my View page when trying to access the Model property.

It sounds like this relates to dll references, and I found the solution at the below link.  

What I did to resolve was to create a new MVC project and then copy the web.config from the Views directory to my older webforms website.  That did the trick...

http://forums.asp.net/p/1378448/2908692.aspx

jQuery with ASP.NET selected index changed

by Cliff 18. July 2009

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

by Cliff 30. June 2009

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

by Cliff 23. May 2009

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

 

LINQ to SQL Connection Strings

by Cliff 17. May 2009

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.

Using a Rich Text Editor with Dynamic Data

by Cliff 21. February 2009

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

ASP.NET error a control with id could not be located or a different control is assigned to the same ID after postback

by Cliff 23. December 2008

Recently I came across an error in an asp.net page that took a fair amount of troubleshooting to resolve.  I had an asp.net page that was using a master page and within the aspx page, I had a grid view.  On the aspx page, I also had a drop down list that posted back to the server when the selected index changed.  On post back, I received the below error: 

An error has occurred because a control with id 'ctl00$ContentPlaceHolder1$gvFiles$ctl05$ctl00' could not be located or a different control is assigned to the same ID after postback. If the ID is not assigned, explicitly set the ID property of controls that raise postback events to avoid this error.

System.Web.UI.Page.ProcessPostData

After some digging, I determined the error was due to multiple asp:ButtonField controls being placed in the GridView.  Since you can not assign an ID to these controls the above error was being raised.  I did not find out exactly why, but at a higher level, the issue was due to my master page having view state disabled.  Once I changed this so my master page had ViewStateEnabled="true" (I had previously set it to false) the error went away.  If you have viewstate turned off at the page or gridview level you may also encounter this issue.

Styling AJAX Control Toolkit Tab Control

by Cliff 30. November 2008

If you have a need to apply custom styles to the AJAX Control Toolkit tab control you should take a look at Matt Berseth's post that includes examples.  You can also create your own styles....to do this, you can take a look at Matt's style sheets and then create your own from his. 

 In order to override the default styles, you will need to define the styles and then when you add the tab control, use the CssClass property to set the css style to use:

<ajaxToolkit:TabContainer runat="server" ID="Tabs" ActiveTabIndex="0" CssClass="ajax__tab_mycustom-theme">

Integrate Disqus into your site using JavaScript

by cliff 15. October 2008

Recently I added Disqus, a hosted comment system, to a site and wanted to point out a couple of things that were not too clear from the documentation on the Disqus site.  It may have been updated, but as of this post, I was not able to find too much info on the JavaScript implementaion of Disqus. 

Basically the JavaScript implementation will work with any web site technology, for example php, ASP.NET, etc.  In order to get it to work, you first need to sign up for an account.  Once you do this, they will provide you with the "code" that you need to add to your site.  Once you add this code, all of the necessary HTML and comment data will appear on your page. 

When you create an account, you provide your site URL. It is important to understand that if you are developing or testing your site on a server other than the one registered with your domain name, the Disqus comment section will not appear.  So if you are setting things up on your local machine and testing, you will not see the full comment section.  Once you push your code to production, you will then see the full Disqus comment section

That is it...it is very easy to set up and use...

Cliff Gray's Info

Cliff Gray
Developer/Founder GrayTechnology.com.

E-mail me Send mail

Authors

Calendar

<<  March 2010  >>
MoTuWeThFrSaSu
22232425262728
1234567
891011121314
15161718192021
22232425262728
2930311234

View posts in large calendar

Blogroll

Download BlogEngine.NET

Download at CodePlex

Disclaimer

The opinions expressed herein are my own personal opinions and do not represent my employer's view in anyway.

© Copyright 2010

Subscribe