Capitalize with C# and ASP.NET

ASP.NET, C# No Comments »

It may be surprising for some, but the .NET framework has capitalization built in:

using System.Globalization;
class Test
{
public static void Main ()
{
string s =
CultureInfo.CurrentCulture.TextInfo.ToTitleCase (”i want this capitalized or capitalised if possible.”);
Console.WriteLine (s);
}
}

It’s even easier with VB.NET:

StrConv(yourTextvalue, VbStrConv.ProperCase)

Still not as elegant as capitalize(str) in Rails ActiveSupport, but the approach via globalize might be more maintainable in the long run. Some dislike though, so your mileage may vary.

[Slashdot] [Digg] [Reddit] [del.icio.us] [Facebook] [Technorati] [Google] [StumbleUpon]

The value for the property "Settings Property Name" is not valid for the current language.

ASP.NET, Linq, Visual Studio No Comments »

You might also get a related error when building your ASP.NET project with a Linq to SQL class:

Build failed due to validation errors in myfile.dbml.  Open the file and resolve the issues in the Error List, then try rebuilding the project.

This issue can be resolved by removing all dots from the connection string key in web.config, see here, so

<connectionStrings>
        <add name=”MyApp.Properties.Settings.MyConnectionString” connectionString=”blah”/>
    </connectionStrings>

becomes

      <connectionStrings>
      
 <add name=”MyConnectionString” connectionString=”blah”/>
    </connectionStrings>

Then the build should succeed. If you then reset the connection string key to the one with dots and it will still build but you’ll get this message

The connection property in the web.config file is missing or incorrect. The connection string from the .dbml file has been used in its place.

upon opening the dbml file and the “dotless” connection string will be added to your web.config.

So Linq to SQL doesn’t like the dotted connection string key for some reason.

[Slashdot] [Digg] [Reddit] [del.icio.us] [Facebook] [Technorati] [Google] [StumbleUpon]

Google Map API - Mouse Wheel Zooming while Preventing Page Scroll

ASP.NET, Google Map API, Ruby on Rails No Comments »

Since version 2.78 the Google Map API exposes mouse wheel scroll zooming straight out of the box, obviating the need for hacks and custom programming to get this essential user experience to fly.

Mouse wheel zooming is enable by simply adding

map.enableScrollWheelZoom();

after the code that creates your map.

However, the API code will not disable the scrolling of the page so scrolling / zooming inside the map will also scroll the page up or down. This is detrimental to the user experience for all maps that are on a page that does not fit the browser window.

Esa has created the most solid workaround I’ve found, and this solution is also suggested by Google.

Here are implementations of Esa’s solution for two of the leading web development environments.

ASP.NET

For almost a year now I’ve used Reimers’ Google Maps .NET control that can be used with ASP.NET, wrapping most of the JavaScript classes and greatly simplifying inserting maps into ASP.NET pages.

Note: I use an older version of the control so the below code might not work with newer versions (it should though)

Code to prevent the page from scrolling, implementing Esa’s code with Reimer’s Google Maps .NET control:

 

bool preventPageScroll = true;
if (preventPageScroll)

            {

            System.Text.StringBuilder sb = new System.Text.StringBuilder();

            sb.Append (@”function preventPageScroll(e){if (!e){e = window.event}if (e.preventDefault){e.preventDefault()}e.returnValue = false;};);

                //Firefox et al.

            sb.Append(String.Format(GEvent.addDomListener(document.getElementById(\”{0}\”), \”DOMMouseScroll\”, preventPageScroll);, GoogleMap1.ClientID));

            sb.Append(System.Environment.NewLine);

                //IE

            sb.Append(String.Format({0}.onmousewheel = preventPageScroll;, GoogleMap1.ClientID));

            GoogleMap1.PostRenderScript += sb.ToString();

            }

document.getElementById looks redundant here but I couldn’t get it to work any other way.

Ruby on Rails

If you’re planning to use the Google Map API from Ruby on Rails you can’t pass by the fantastic ym4r_gm plugin by Guilhem Vellut.

Be sure to also walk through the Google Maps / Yahoo Traffic mash-up. The plugin supports mouse wheel zooming directly. You can enable it by simply adding

@map.interface_init (:scroll_wheel_zoom => true)

in the controller like so (line 7):

 

 1 class TrafficController < ApplicationController

 2 

 3   def index

 4     @map = GMap.new(map_div)

 5     @map.control_init(:large_map => true,:map_type => true)

 6     @map.center_zoom_init([38.134557,-95.537109],4)

 7     @map.interface_init(:continuous_zoom => true, :scroll_wheel_zoom => true, :prevent_pagescroll => true)

 8     @map.icon_global_init(GIcon.new(:image => /images/icon_incident.png, :icon_size => GSize.new(15,15),:icon_anchor => GPoint.new(7,7),:info_window_anchor => GPoint.new(9,2)),icon_incident)

 9     @map.icon_global_init(GIcon.new(:image => /images/icon_construction.png, :icon_size => GSize.new(15,15),:icon_anchor => GPoint.new(7,7),:info_window_anchor => GPoint.new(9,2)),icon_construction)

10 

11   end

You can prevent the page from scrolling when using the mouse wheel zooming taking these two simple steps (using Esa’s code):

1. Add the following function to the public>javascripts>ym4r-gm.js JavaScript file:

 

function preventPageScroll(e)

{

if (!e){

e = window.event

}

if (e.preventDefault){

e.preventDefault()

}

e.returnValue = false;

}

2. Add the following code to the interface_init method in vendor>plugins>ym4r_gm>lib>gm_plugin>map.rb

 

if !interface[:prevent_pagescroll].nil?

          if interface[:prevent_pagescroll]

            @init << #{@container}.onmousewheel = preventPageScroll;

            @init << GEvent.addDomListener(#{@container}, \”DOMMouseScroll\”,preventPageScroll);n”

          end

        end

Now simply set :prevent_pagescroll => true in the controller as in the sample code above. I’m quite new to Ruby and Rails and there certainly might be a better way to implement this but the code works. Hope it helps.

Update: Due to a WordPress bug the backslashes to escape the double-quotes around “DOMMouseScroll” in and before the newline (n) are not visible in the above code snippets. You will have to add them manually before I upgrade my Wordpress install.

[Slashdot] [Digg] [Reddit] [del.icio.us] [Facebook] [Technorati] [Google] [StumbleUpon]

Working with Nested Repeaters in ASP.NET

ASP.NET, Programming No Comments »

Sometimes I miss the option that you have in classic ASP, PHP or Ruby on Rails to just put a nested loop into the html page (view, presentation layer) to display nested data. Of course this is, strictly speaking, against ASP.NET best practices where you’re supposed to use web controls for everything. Then again one could make the argument that the loop actually belongs in the view. This would be .aspx page, and not in the controller or the model (code behind file in ASP.NET).

The task at hand is to iterate through parent categories and child items. The technique suggested by Microsoft is outlined here, and this article uses a nested repeater with a self-join. Starting point is the following DataSet with two related tables and a repeater in the page:

DataSet myDS = new DataSet("NestedRepeaterDemo"); … //fill the dataset myDS.Tables[0].TableName = "ParentCategories"; myDS.Tables[1].TableName = "ChildItems"; DataRelation relation = new DataRelation("myRelation", myDS.Tables["ParentCategories"].Columns["CatID"], myDS.Tables["ChildItems"].Columns["CatID"], true); relation.Nested = true; myDS.Relations.Add(relation); parentRepeater.DataSource = myDS; parentRepeater.DataBind();

So why not bind the child repeater in the page, just for the heck of it:

<table> <asp:Repeater id="parentRepeater" runat="server"> <itemtemplate> <tr class="categoryInTable"> <td colspan="2"> <%# DataBinder.Eval(Container.DataItem, "CategoryName") %> </td> </tr> <asp:Repeater ID="childRepeater" runat="server" datasource=’<%# ((DataRowView)Container.DataItem).Row.GetChildRows("myRelation") %>‘ > <ItemTemplate> <tr><td> <%# Eval("ItemName")%> </td> <td> <%# Eval("ItemDescription")%> </td> </tr> </ItemTemplate> </asp:Repeater> </itemtemplate> </asp:Repeater> </table>

 

Sure enough with this code you will run into a DataBinding: ‘System.Data.DataRow’ does not contain a property with the name x error. 

As a quick explanation for this error the following might suffice:

When the nested repeater binds to its datasource calling the GetChildRows command of the parent DataRowView.Row object the latter returns an array of DataRows (the “child rows”, an object of type DataRow[]) which each repeater Item will be bound to now. However, Eval with the above syntax will only bind to named fields of a DataView object that exposes a name property for each field. The DataRow returned by GetChildRows is merely a row in a table without the name properties so that each field can be accessed only with an indexer (DataRow["ItemName"]).

This is why you can either change the binding expressions above like so:

 

<td> <%# Eval("[\"ItemName\"]")%> </td> <td> <%# Eval("[\"ItemDescription\"]")%> </td>

or you can change the datasource to use the CreateChildView of the DataRowView directly like this:

<asp:Repeater ID=”childRepeater” runat=”server” datasource=’<%# ((DataRowView)Container.DataItem).CreateChildView(”myRelation”) %>’ >

and use old data binding syntax <%# Eval (”ItemName”) %> because now you have a DataView again (just like in the parentRepeater) which supports binding to the data field by name. Of course you have the option to do all the databinding in the code-behind file (usually the ItemDataBound event of each repeater) which gives you better debugging support than the approach above.

I find this “nested data” stuff overly complicated in ASP.NET, especially compared with how easy it is with Ruby on Rails. The plethora of objects which each behave differently is difficult to work with and the Repeater itself is limited in its built-in functionality and designer-support.

Sure enough I also ran into the

Compiler Error Message: CS0246: The type or namespace
name ‘DataRowView’ could not be found (are you missing a
using directive or an assembly reference?)

which IMHO is clearly a bug in ASP.NET as a reference to System.Data exists in the code-behind file that the .aspx web form inherits from. This issue can be fixed by either having an <%@ Import Namespace=”System.Data” %> tag in your aspx file or declaring DataRowView with the full namespace System.Data.DataRowView in the page each time.

For an in-depth view of the binding issues see this article. You might also find this post helpful.

[Slashdot] [Digg] [Reddit] [del.icio.us] [Facebook] [Technorati] [Google] [StumbleUpon]

Microsoft Going to REST

ASP.NET No Comments »

MS is firing on all cylinders to copy emulate Ruby on Rails’ developer friendly features. Among the deluge of new stuff released upon developers over the past few months I hadn’t yet realized there was a MS project named Astoria.

Quote:

The goal of Microsoft Codename Astoria is to enable applications to expose data as a data service that can be consumed by web clients within a corporate network and across the Internet. The data service is reachable over HTTP, and URIs are used to identify the various pieces of information available through the service. Interactions with the data service happens in terms of HTTP verbs such as GET, POST, PUT and DELETE, and the data exchanged in those interactions is represented in simple formats such as XML and JSON.

Yes, not on the site but in the pertinent documents they admit it’s RESTful, overcoming the fear of having theirs mouths washed with SOAP.
 This puts REST firmly into the essential learning category for web developers together with JavaScript, CSS and HTML. Here’s a good introduction into REST. SubSonic, the hottest “catching up with Rails” project, will have it built in real soon now.

[Slashdot] [Digg] [Reddit] [del.icio.us] [Facebook] [Technorati] [Google] [StumbleUpon]
WP Theme & Icons by N.Design Studio
Entries RSS Comments RSS Log in