Category Archives: ASP.NET Tips

new to deploying

I created a simple web page to load onto a remote site using Visual Web Developer Express 2005. All it contained was the word "Hello". I hit Build Website and then I used the aspnet_compiler and then ftp to transfer the compiled files to the remote server. When I tried to access the page, all it showed was:

"This is a marker file generated by the precompilation tool, and should not be deleted!"

What am I doing wrong?

Read More

Very Strange Data Conversion (?) Error

 Using SQL Server 2005, I hve encountered a very strange error which I cannot figure out.  The simplified stored proc below basically does a select and sorts the records based on the column name given in the @SortCol parameter.  When I enter the field names bapk, jhpk, etc everything works fine.  The records are returned sorted by the field name entered into the parameter.  The first eight variables are  field names and types

 When I enter the field name 'descr' into the @SortCol variable/parameter, I receive the error:

 Msg 295, Level 16, State 3, Procedure CMSCheck2, Line 28
Conversion failed when converting character string to smalldatetime data type.

I don't see where this is coming from at all.  The problem is in the  stored proc lines beginning with 'CASE @SortCol'

If I take out the lines and just use  OVER (Order By descr) as RowNum   — everything is fine

If I delete the line  WHEN 'descr' THEN descr  — everything is fine, it just falls through to the default.

 What is the problem?  Where is a conversion to smalldatetime coming from?   I've been working on this one for a while, and cannot figure it out.  It must be something simple.

 Thanks,

Mike Thomas
 

Below is the stored proc and a testing script

 

TESTING SCRIPT

USE biz03
GO

DECLARE
  @bapk int,
  @jhpk int,
  @transdate smalldatetime,
  @number smallint,
  @descr nvarchar(50),
  @debit decimal(9,2),
  @credit decimal(9,2),
  @cmonth tinyint,
  @StartRowIndex int,
  @MaxRows int,
  @AlphaChar varchar(1),
  @SortCol varchar(20)

SET @MaxRows = 10
SET @StartRowIndex = 0
SET @SortCol = 'descr'
SET @AlphaChar = ''

EXEC [dbo].[CMSCheck2]
  @bapk,
  @jhpk,
  @transdate,
  @number,
  @descr,
  @debit,
  @credit,
  @cmonth,
  @StartRowIndex,
  @MaxRows,
  @AlphaChar,
  @SortCol

 

STORED PROC 

 

 ALTER PROCEDURE [dbo].[CMSCheck2]
  @bapk int,
  @jhpk int,
  @transdate smalldatetime,
  @number smallint,
  @descr nvarchar(50),
  @debit decimal(9,2),
  @credit decimal(9,2),
  @cmonth tinyint,
  @StartRowIndex int,
  @MaxRows int,
  @AlphaChar varchar(1) = null,
  @SortCol varchar(20) = null

AS
BEGIN

SET NOCOUNT ON

DECLARE @lPaging bit
IF @AlphaChar is null
  SET @lPaging = 0
ELSE
  SET @lPaging = 1;

WITH BankListTemp AS
  (SELECT   bapk, jhpk, transdate, number,
    descr, debit, credit, cmonth, ROW_NUMBER()
    OVER (ORDER BY
    CASE @SortCol
       WHEN 'bapk' THEN bapk
       WHEN 'jhpk' THEN jhpk
       WHEN 'transdate' THEN transdate
       WHEN 'number' THEN number
       WHEN 'descr' THEN descr  — problem here   —
       WHEN 'debit' THEN debit
       WHEN 'credit' THEN credit
       WHEN 'cmonth' THEN cmonth
       ELSE bapk
    END) as RowNum
  FROM bank)

SELECT TOP (@MaxRows)    bapk, jhpk, transdate, number,
    descr, debit, credit, cmonth, Rownum
FROM
 ( SELECT BankListTemp.*,
    (SELECT COUNT(*) FROM BankListTemp) AS RecCount
      FROM BankListtemp) Bank

END

 

Read More

Interfaces

I have recently fallen in love with interfaces – they make it so easy to distribute uniform changes across many objects… that is, until you want to add a member who's signature changes depending on which class inherits it

For example, I have two classes, Customers, and Events.  Both inherit my "CustomCollection" interface.  I want the interface to force the implementation of an Add method, but inevitably their arguments are different:  Add(Customer cust) , Add(Event ev). Is there a way to tell the interface that the parameters can change depending on the class?

 

 

 

Read More

RegisterClientScriptInclude in masterpage

Hi,

I’m trying to include and use a javascript file in my masterpage… niftycube actually. Anyways, trying to add this javascript and call the function is proving to be quite difficult. I’ve looked over most of the solutions on this forum already, but none seem to work for me. Here’s what I have so far on the Page_Load.

String csname = "niftycube";
ClientScriptManager cs = Page.ClientScript;
String csurl = "niftycube.js";
Type cstype = this.GetType();

// Check to see if the include script exists already.
if (!cs.IsClientScriptIncludeRegistered(cstype, csname))
{
     cs.RegisterClientScriptInclude(cstype, csname, ResolveUrl(csurl));
}

So I’ve actually tried a variety of different ways to get the javascript file properly included. I’ve used different values for ‘csurl’ include “~/niftycube.js”, “niftcube.js”, “~/scripts/niftycube.js” (after moving it there of course), and so on. No matter what I do, I’m getting a Javascript error saying “Syntax error, Line 4, Char 1”.

When I look at the source code actually generated, it actually APPEARS to be correct! But I’m still getting the syntax error warning. As soon as I removed the “RegisterClientScriptInclude” line of code, the syntax error warning goes away, not to mention the calls to the javascript functions by adding RegisterClientScriptBlock are also failing.

<script src="/CentralProject/niftycube.js" type="text/javascript"></script>

Pbm with framework 3.5 and VS 2008…

i was working on an application in VS2008, and when i went to properties of the website, i changed the setting of framework from 3.5 to 2.00, all the pages of my site had totally changed!! i didn't recognised it! it was horrible. months of working n it! on my PC i think i've both, framework 3.5 and 2.00 installed. Somebody can help me?
THANK YOU;

Read More

ASP.NET MVC Source Refresh Preview

We recently opened up a new ASP.NET CodePlex Project that we will be using to provide previews (with buildable source code) for several upcoming ASP.NET features and releases.

Last month we used it to publish the first drop of the ASP.NET MVC source code.  This first drop included the source for the ASP.NET MVC Preview 2 release that we shipped at MIX, along with Visual Studio project files to enable you to patch and build it yourself.

A few hours ago we published a refresh of the ASP.NET MVC source code on the site.  This source refresh is not an official new ASP.NET MVC preview release – instead it is an interim drop that provides a look at the current state of the source tree.  We will ship the official "ASP.NET MVC Preview 3" release in a few weeks after we finish up some more work (more features and tweaks to existing ones, better VS tool integration, VS express edition support, documentation, etc).  If you are someone who wants a hassle-free installation of ASP.NET MVC to use that ships with documentation and full tool support you’ll probably want to wait for this official preview release.  If you are someone who wants a chance to see an early "preview of the preview" and have the opportunity to start using and giving feedback on some of the features immediately, today’s source refresh is probably interesting to look at.

Improvements with this ASP.NET MVC Source Refresh

This week’s update (which you can download here) includes a number of improvements to ASP.NET MVC.  Some of these include:

  • In addition to posting the source code for the ASP.NET MVC framework, we are also posting the source code for the unit tests that we use to test it.  These tests are implemented using MSTest and the open source Moq mocking framework.  A VS 2008 project file for the unit tests is included to make it easy to build and run them locally within your VS 2008 IDE.

  • Significantly easier support for testing Controller classes.  You can now unit test common Controller scenarios without having to mock any objects (more details on how this works below).

  • Several nice feature additions and usability improvements to the URL routing system (more details below).

Creating a New ASP.NET MVC Project

You can build your own copy of the ASP.NET MVC assemblies by downloading the MVC source and compiling it locally, or alternatively you can download a VS Template package to get a pre-built version of them along with a Visual Studio project template that you can use to quickly build a new ASP.NET MVC Project that uses the latest bits.

After you install the ASP.NET MVC source refresh .VSI template, a new "ASP.NET MVC Application" project template will show up under the "My Templates" section of your "New Project" dialog:

This new "My Templates" version of the MVC project template lives side-by-side with the previous ASP.NET MVC Preview 2 release (which you can see above it in the main project templates section of the dialog).  This allows you to safely create new projects and and use both the latest source version and the last official preview version on the same machine.

When you create a new project using this updated ASP.NET MVC Project template you’ll by default get a project that looks like below:

This new project solution contains one Controller ("HomeController") under the "\Controllers" directory and two View templates ("About" and "Index") under the "\Views\Home" sub-directory.  Both view templates are based on a common master page for the site ("Site.master"), all of whose styles are defined within a "Site.css" file under the "\Content" directory.

When you run the application the built-in web-server will automatically start up and you’ll see the site’s "Home" content:

Clicking the "About us" tab will then display the "About" content:

The "HomeController" class in the project is responsible for handling both of the URLs above and has two action methods like below:

The default "Site.master" template looks for a "Title" value in the ViewData collection and uses it to render the <title> element of the HTML page.  The default "Index" view template looks for a "Message" value and uses it to render the home page’s welcome message.  You can obviously go in and customize these files however you want.

Controller Changes with this ASP.NET MVC Drop

If you were reading the above code closely you might have noticed a few changes with how Controller classes are by default implemented using this new ASP.NET MVC source refresh drop. 

With the ASP.NET MVC Preview 2 release the above HomeController action methods would have instead been implemented like below:

The MVC feature team is experimenting with a few ideas in this week’s drop and are trying out some new ideas:

  1. Action methods on Controllers now by default return an "ActionResult" object (instead of void).  This ActionResult object indicates the result from an action (a view to render, a URL to redirect to, another action/route to execute, etc). 

  2. The RenderView(), RedirectToAction(), and Redirect() helper methods on the Controller base class now return typed ActionResult objects (which you can further manipulate or return back from action methods).

  3. The RenderView() helper method can now be called without having to explicitly pass in the name of the view template to render.  When you omit the template name the RenderView() method will by default use the name of the action method as the name of the view template to render.  So calling "RenderView()" with no parameters inside the "About()" action method is now the same as explicitly writing "RenderView(‘About’)".

It is pretty easy to update existing Controller classes built with Preview 2 to use this new pattern (just change void to ActionResult and add a return statement in front of any RenderView or RedirectToAction helper method calls).

Returning ActionResult Objects from Action Methods

So why change Controller action methods to return ActionResult objects by default instead of returning void?  A number of other popular Web-MVC frameworks use the return object approach (including Django, Tapestry and others), and we found for ASP.NET MVC that it brought a few nice benefits:

  1. It enables much cleaner and easier unit testing support for Controllers.  You no longer have to mock out methods on the Response object or ViewEngine objects in order to unit test the response behavior of action methods.  Instead, you can simply assert conditions using the ActionResult object returned from calling the Action method within your unit test (see next section below).

  2. It can make Controller logic flow intentions a little clearer and more explicit in scenarios where there might be two different outcomes depending on some condition (for example: redirect if condition A is true, otherwise render a view template it is false).  This can make non-trivial controller action method code easier to read and follow.

  3. It enables some nice composition scenarios where a FilterActionAttribute can take the result of an action method and modify/transform it before executing it.  For example: a "Browse" action on a ProductCatalog controller might return an RenderActionResult that indicates it wants to render a "List" view of products.  A FilterActionAttribute declaratively set on the controller class could then have a chance to customize the specific "List" view template rendered to be either List-html.aspx or List-xml.aspx depending on the preferred MIME type of the client.  Multiple FilterActionAttributes can also optionally be chained together to flow the results from one to another.

  4. It provides a nice extensibility mechanism for people (including ourselves) to add additional features in the future.  New ActionResult types can be easily created by sub-classing the ActionResult base class and overriding the "ExecuteResult" method.  It would be easy to create a "RenderFile()" helper method, for example, that a developer writing an action could call to return a new "FileActionResult" object.

  5. It will enable some nice Asynchronous execution scenarios in the future.  Action methods will be able to return an AsyncActionResult object which indicates that they are waiting on a network operation and want to yield back the worker thread so that ASP.NET can use it to execute another request until the network call completes.  This will enable developers to avoid blocking threads on a server, and support very efficient and scalable code.

One of the goals with this interim preview is to give people a chance to play around with this new approach and do real-world app-building and learning with it.

We will also post an alternative Controller base class sample that you can use if you still prefer the previous "void" action return approach.  We deliberately didn’t include this alternative Controller base class in this source refresh drop, though, because we want to encourage folks to give the "ActionResult" return approach a try and send us their app-building feedback on it.

How To Unit Test Controller Action Methods

I mentioned above that the new ActionResult approach can make unit testing controllers much easier (and avoid the need to use mocking for common scenarios).  Let’s walk through an example of this in action.

Consider the simple NumberController class below:

This Controller class has an "IsEvenNumber" action method that takes a number as a URL argument.  The IsEvenNumber action method first checks whether the number is negative – in which case it redirects the user to an error page.  If it is a positive number it determines whether the number is even or odd, and renders a view template that displays an appropriate message:

Writing unit tests for our "IsEvenNumber" action method is pretty easy thanks to the new ActionResult approach.

Below is an example unit test that verifies that the correct Http redirect occurs when a negative number is supplied (for example: /Number/IsEvenNumber/-1):

Notice above how we did not need to mock any objects to test our action method.  Instead we simply instantiated the NumberController class and called the action method directly (passing in a negative number) and assigned the return value to a local "result" variable.  I used the C# "as type" syntax above to cast the "result" variable as a strongly typed "HttpRedirectResult" type.

What is nice about the C# "as" keyword is that it will assign the value as null instead of throwing an exception if the cast fails (for example: if the action method returned a RenderViewResult instead).  This means I can easily add an assertion check in my test to verify that the result is not null in order to verify that an Http redirect happened.  I can then add a second assertion check to verify that the correct redirect URL was specified.

Testing the scenarios where non-zero numbers are passed in is also easy.  To do this we’ll create two test methods – one testing even numbers and one testing odd numbers.  In both tests we’ll assert that a RenderViewResult was returned, and then verify that the correct "Message" string was passed within the ViewData associated with the view:

We can then right click on our NumberControllerTest class inside VS 2008 and choose the "Run Tests" menu item:

This will execute our three unit tests in-memory (no web-server required) and report back on whether our NumberController.IsEvenNumber() action method is performing the right behavior:

Note: with this week’s source drop you still need to use mocking to test the TempData property on Controllers.  Our plan is to not require mocking to test this with the ASP.NET MVC Preview 3 drop in a few weeks.

MapRoute Helper Method

URL routing rules within ASP.NET MVC applications are typically declared within the "RegisterRoutes" method of the Global.asax class.

With ASP.NET MVC Previews 1 and 2 routes were added to the routes collection by instantiating a Route object directly, wiring it up to a MvcRouteHandler class, and then by setting the appropriate properties on it to declare the route rules:

The above code will continue to work going forward.  However, you can also now take advantage of the new "MapRoute" helper method which provides a much simpler syntax to-do the same thing.  Below is the convention-based URL route configured by default when you create a new ASP.NET MVC project (which replaces the code above):

The MapRoute() helper method is overloaded and takes two, three or four parameters (route name, URL syntax, URL parameter default, and URL parameter regular expression constraints). 

You can call MapRoute() as many times as you want to register multiple named routes in the system.  For example, in addition to the default convention rule, we could add a "Products-Browse" named routing rule like below:

We can then refer to this "Products-Browse" rule explicitly within our Controllers and Views when we want to generate a URL to it.  For example, we could use the Html.RouteLink view helper to indicate that we want to link to our "Products-Browse" route and pass it a "Food" category parameter using code in our view template like below:

This view helper would then access the routing system and output an appropriate HTML hyperlink URL like below (note: how it did automatic parameter substitution of the category parameter into the URL using the route rule):

Note: with this week’s source drop you need to pass-in the controller and action parameters (in addition to the Category param) to the Html.RouteLink() helper to resolve the correct route URL to generate.  The ASP.NET MVC Preview 3 drop in a few weeks will not require this, and allow you to use the Html.RouteLink call exactly as I’ve written it above to resolve the route.

Other URL Route Mapping Features

This week’s MVC source drop also supports a bunch of new URL route mapping features.  You can now include "-", ".", ";" or any other characters you want as part of your route rules.

For example, using a "-" separator you can now parse the language and locale values from your URLs separately using a rule like below:

This would pass appropriate "language", "locale", and "category" parameters to the ProductsController.Browse action method when invoked:

URL Route Rule Example URL Parameters Passed to Action method
{language}-{locale}/products/browse/{category} /en-us/products/browse/food language=en, locale=us, category=food
  /en-uk/products/browse/food language=en, locale=uk, category=food

Or you can use the "." file extension type at the end of a URL to determine whether to render back the result in either a XML or HTML format:

This would pass both "category" and a "format" parameters to the ProductsController.Browse action method when invoked:

URL Route Rule Example URL Parameters Passed to Action method
products/browse/{category}.{format} /products/browse/food.xml category=food, format=xml
  /products/browse/food.html category=food, format=html

ASP.NET MVC Preview 2 introduced wildcard route rules.  For example, you can indicate in a rule to pass all remaining URI content on as a named parameter to an action method:

This would pass a "contentUrl" parameter to the WikiController.DisplayPage action method when invoked:

URL Route Rule Example URL Parameters Passed to Action method
Wiki/Pages/{*contentUrl} /Wiki/Pages/People/Scott contentUrl="People/Scott"
  /Wiki/Pages/Countries/UK contentUrl="Countries/UK"

These wildcard routes continue to work fine with this week’s preview – and are very useful to look at if you are building a blogging, wiki, cms or other content based system.

Note that in addition to using the new routing system for ASP.NET MVC scenarios, we are also now using the same routing system within ASP.NET Dynamic Data (which uses ASP.NET Web Forms).

Summary

Hopefully the above post provides a quick update on some of the new features and changes exposed with this week’s ASP.NET MVC source update drop. 

You can download it here if you want to start using it immediately.  Alternatively, you can wait a few weeks for the official ASP.NET MVC Preview 3 drop – which will have some more features (and incorporate feedback people provide on this week’s drop), deliver a more seamless installer, provide nice VS integration, and deliver up to date documentation.

For any questions/issues with this week’s drop of ASP.NET MVC, make sure to also check out the ASP.NET MVC forum on www.asp.net.

Hope this helps,

Scott


Read More

“this” keyword error now when it was working fine

I have a problem that was not a problem before.

I have a sight that was working. I started a website project and I think I selected asp.net site. In this project I had some code in a aspx page.

                 <script language="JavaScript" src="~/Scripts/menu.js" type="text/javascript">
           
                function lefthide() {
                var fr = parent.document.getElementById("sbCont");
                    if(fr.style.display==""){
                        fr.style.display="none";
                  change('outlookside', 'outlookBarExpand')
                    }
                    else{
                        fr.style.display="";
                  change('outlookside', 'outlookBarcollapse')
                    }

                }
                function change(id, newClass) {

                identity=document.getElementById(id);

                identity.className=newClass;

                }
          </script>

 

Then this later in the page.

<td align="center" background="images/collapse_side_bg.gif" style="width: 6px;
                        height: 91%; background-color: #e7ebf0" valign="middle">
                        <img id="outlookside" class="~/Styles/Collapse.css" height="45" onclick="lefthide(this);"
                            src="images/slidbtn.JPG" style="cursor: pointer" width="5" /></td>

Now I created a new site asp.net with Ajax support. Now the onclick="lefthide(this) causes an error "Object required" What is wrong.

 

Thanks,

 

Ty

Read More

please help with searching

i have to make the following but i have no clue any help will be appreciated

i have to search through three tables based on user preferences.

the tablkes are author name, book name and topics.

now i want to the user to select thr option from the drop down menu. The problem is how do i ascertain(dynamically) which table to search based on the action selected by  the user. Thanks

 

Read More

Unit Testing with Silverlight

One of the important capabilities we shipped with the Beta1 release of Silverlight 2 was a unit test harness that enables you to perform both API-level and UI-level unit testing.  This testing harness is cross browser and cross platform, and can be used to quickly run and verify automated unit tests:

In addition to shipping this unit test harness for Silverlight, we also shipped the source to ~2,000 unit tests built with it that provide automated coverage for the Silverlight control source that we also shipped under a permissive license (you can take the control source, modify it, run the unit tests to verify the behavior, then re-ship the controls however you want).

Learning How to Unit Test Silverlight

Jeff Wilcox (who developed the Silverlight unit test framework and harness) has a great blog post that talks about how to add a Silverlight Unit Test project to a solution here. You can download the chat application that he shows testing from this expression blend blog post tutorial I did last month.  You can also watch this cool video post that Jeff created where he walks through the unit test framework and test cases we’ve shipped.

As Jeff shows in his post, you can now add a "Silverlight Test Project" to your Visual Studio solution which encapsulates unit tests for an application you are working on:

You can then add unit test classes to the test project that test APIs or simulate UI action within the Silverlight controls (simulate button clicks, etc).

You can then run the test project and execute the tests within it to verify and report their status.

Jeff’s test framework automatically provides a browser based test harness and reporting system (which means you can run it on any browser/OS combination that Silverlight runs on):

Jeff’s test framework supports quickly re-setting controls after each test (and avoids needing to re-launch a new browser instance for each test cases – which makes it really fast).

You can quickly rip through hundreds or thousands of automated tests in seconds:

Green results mean the tests passed.  Red results flag that a test case failed and log the assertion failure and/or runtime exceptions that occurred.

Summary

If you’ve ever struggled to try and come up with a strategy for doing automated unit testing or TDD with AJAX applications, I think you’ll find Silverlight provides some much nicer test options.  Using Visual Studio you can also separate your tests into a separate project in your solution, and you do not need to embed the tests within your Silverlight application in order for them to run.

In addition to supporting the above unit test harness and framework, we are also going to support UI automation APIs with the final release of Silverlight 2.  These will enable accessibility scenarios (allowing screen readers to work with Silverlight and enable Section 508 compliance of Silverlight applications).  These UI automation APIs will also enable UI testing scenarios where you can build end to end browser UI automation that simulates real mouse and keyboard interactions and enables automated end to end experience testing.  The combination should enable you to build much more solid and maintainable RIA solutions.

Hope this helps,

Scott

P.S. For more tutorial posts and links on Silverlight 2, check out my new "Silverlight Tips, Tricks, Tutorials and Links" page.


Read More

April 11th Links: ASP.NET, ASP.NET AJAX, ASP.NET MVC, Visual Studio, Silverlight

Here is the latest in my link-listing series.  Also check out my ASP.NET Tips, Tricks and Tutorials page and Silverlight Tutorials page for links to popular articles I’ve done myself in the past.

ASP.NET

  • 50 Useful CSS Tips and Tricks: A useful page that provides a nice listing of various CSS tips, tricks and tools you can use for common web scenarios.

ASP.NET AJAX

  • Accessible UpdatePanel: Bertrand Le Roy from the ASP.NET team has an article that describes how to make the ASP.NET AJAX’s UpdatePanel control accessible for screen-readers.

  • Building ASP.NET AJAX Components: Mike Ormond has written an excellent 8-part series that covers building re-usable ASP.NET AJAX components that work on both the client and server.

ASP.NET MVC

  • ASP.NET MVC: Membership Starter Kit: Troy Goode has a built an awesome membership starter kit for ASP.NET MVC that provides registration and login pages for users to authenticate on your site, as well as a set of administration functionality that allows admins to create/manage users and roles.  Download it here.

  • How to Enable Pretty URLs with ASP.NET MVC and IIS6: James Geurts posts a useful article that describes how to enable extension-less URLs with ASP.NET MVC on IIS6 (note: you do not need to configure anything special with ASP.NET MVC on IIS7 to enable extension-less URL support).

Visual Studio

Silverlight

  • Dave Campbell’s Excellent Silverlight Link Series: Dave Campbell posts a regular series of links to new Silverlight articles and content on the web.  I highly recommend subscribing to his blog if you want to stay current with all the latest Silverlight articles and posts.

  • Silverlight 2 Map / DataGrid Tutorial: Jason Zander has a great two-part Silverlight tutorial that demonstrates how to build a nice data-driven application that integrates a map control with a datagrid to filter and analyze data.

Hope this helps,

Scott


Read More