Adding javascript files to your SharePoint 2010 web part.

by Abe Miessler 12. April 2011 07:31

For something so simple, this problem took me quite a while so I wanted to share how I resolved it.  In my situation I wanted to add jQuery and a few jQuery plugin files to be part of my visual web part.  This web part was going to be part of a wsp that would be shipped out to SharePoint environments that I had no control over, so simply including them in the master page was not an option.

 

  1. Right click on your project file and select Add->SharePoint "Layouts" Mapped Folder
  2. In side of the Layouts Mapped folder create the following file structure: YourProjectName/js
  3. Add your js files to the folder you just created in your project
  4. Inside of your ascx file for you visual web part create the ScriptLink tag

             <SharePoint:ScriptLink ID="ScriptLink1" runat="server" Name="YourProjectName/js/jquery.min.js" />

If you have jQuery plugins, place their ScriptLink  tags AFTER the jQuery tag

 

You should now be in business.  If you are havinig problems check the following directory to make sure your scripts are being deployed:

C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\TEMPLATE\LAYOUTS\YourProjectName\js

 

 

Tags: ,

ASP.NET | jQuery | SharePoint

Validating currency input in ASP.NET

by Abe Miessler 13. September 2010 16:02

While doing some input validation for a web application I am working on I attempted to use ASP.NET's CompareValidator to do some pretty basic validation for a currency input.  I was surprised to find that it kept saying my input wasn't valid any time I included the "$" symbol.  Below is an example of how I implemented the control:

<asp:CompareValidator ID="vld_Cash" runat="server"
     ControlToValidate="CashTextBox"
     Type="Currency"
     Operator="DataTypeCheck"
     ValidationGroup="vld_Update"
     ErrorMessage="You must enter a currency for 'Cash'. Example: $500" />

Thinking that this might be some bizzare intended behavior from Microsoft I decided to take a look at the documentation.  According to Microsoft the Currency data type is:

    "A decimal data type that can contain currency symbols."

I did some more poking around and it looks like i'm not the first person to have this problem.  From what I've read the best work around for this is to create a RegularExpressionValidator that will allow input that is formatted as currency.  When creating the regular expression you will be using with your RegularExpressionValidator remember to use JScript compliant regex.  I made the mistake of using .NET regex and when it tried to validate on the client side it threw an exception.  If you create a JScript regex it should work fine on both client and server side.  Below is the RegularExpressionValidator that I ended up using to accomplish what ASP.NET's CompareValidator couldn't:

<asp:RegularExpressionValidator ID="rev_CashTextBox" runat="server"          
        ValidationExpression="^\s*\$?\s*(?!\d{4,},)(\d|\d{1,3},(?=\d{3})(?!\d{4}))*(\.\d{1,2})?\s*$"
        ControlToValidate="tb_Cash"
        ValidationGroup="vld_Edit"
        ErrorMessage="You must enter a currency value for Cash'. Examples: 100.00, $100" />

This allows for a number of different American currency formats to be submitted.

Here is a link to the bug I submitted to Microsoft, hopfully they will find a resolution soon.

Tags:

ASP.NET

.NET String vs StringBuilder

by Abe Miessler 8. December 2009 03:44

A common mistake made by new programmers is to not utilize the StringBuilder class in the .Net framework.  To begin understanding when we should use StringBuilder let's first look at some of the inner workings of strings.

The most important thing to know about strings is that they are immutable.  That is, once you have created a string you can never change it.  It will never get longer, shorter or have any of its characters changed.  This is a difficult concept for many people to understand.  Lets look at the code below:

string Name = "Abe";

Name = Name + "miester";

While it might appear that you are actually just adding "miester" to the end of "Abe" in order to update the existing string what is happening in the background is actually much different.  When you assign the new value to the Name variable two entirely new strings are created.  There are now actually three strings in memory: "Abe", "miester" and "Abemiester".  The strings "miester" and "Abe" are no longer needed and the garbage collector will reclaim their memory at the next collection.

Now that we have an idea of how strings work lets look at a situation that could be improved by the use of the StringBuilder class.  Lets look at the code below:

 

    string letsCount = "Let's count! ";

    for(int i=; i< 100; i++)

    {

         letsCount += i + ", ";

    }

    Console.WriteLine(letsCount);

 

The above code will create a string that counts from 0 to 100.  Unfortunately, since we are using the string class, a new string will be created on the heap every iteration.  To avoid this we can use the StringBuilder class.

The StringBuilder class is provided as a means to dynamically construct a string in an efficient manner.  A StringBuilder object represents a string as an arrary of Char structures, each Char can have it's value changed and the array can be shrunk.  If the string grows beyond the allocated array of characters, StringBuilder automatically creates a new, larger array, copies the contents over, and begins using the new array.  It should be noted that dynamically growing your StringBuilder contents hurts performance so you should do your best to set a good initial capacity.  When you are working with a String who's value changes frequently this is much more efficient.  Lets look at the code below:

    using System.Text;

    StringBuilder letsCount = new StringBuilder("Let's count! ", 150); //Initialize the string to "Let's count!" and set the initial length to 150

    for(int i=; i< 100; i++)

    {

         letsCount..AppendFormat("{0}, ",i);

    }

    Console.WriteLine(letsCount.ToString());

 

This method is much more efficient because we are not creating a new string on every iteration.  In situations where you are dynamically adding to a string you should try to use this method whenever possible.

 

Update:

After talking with some of the folks at StackOverflow.com I found out that the fastest way to do string appends is actually to use the String Join method.  While StringBuilder does offer an improvement, Join performs even better.  Take a look at this post for more details on why.

 

Tags: , , ,

ASP.NET | StringBuilder

ASP.NET MVC "Hello World" tutorial.

by Abe Miessler 6. December 2009 22:12

After listening to one of my coworkers rave about how wonderful MVC was for the last week I decided it was time to cut my teeth with the ASP.NET MVC 1.0 framework and find out for myself if it was really all it was cracked up to be.  Below you will find step by step instructions to creating your first basic ASP.NET MVC “Hello World” application.


To begin you must download the ASP.NET MVC framework which can be found here.


Once this has installed open Visual Studio and create a new ASP.NET MVC Web Application:



Next you will be asked if you would like to create Unit Tests for this application.  Since this is beyond the scope of this tutorial we will select “No” and continue.


We now have our base MVC Project and we will begin adding functionality.  Let’s start by adding a model to the project.  To do this right click on the “Models” folder and select Add->Class and name it “Person.CS”.



In our new class we will create a new string member called “Name”.



Next we will add a controller class called HelloWorldClass.cs.  To do this, right click on the “Controls” folder and click “Add New Item”.  In the Add New Item dialog box select “MVC Controller Class” and name it “HelloWorldController.cs”.  As you continue through this tutorial you will probably notice that this Controller contributes little to the project.  While we could get away without having a Controller for a project that is this simple, I wanted to introduce the concept to illustrate how Models, Views and Controllers interact with one another.



Now we will reference the Person model from the HelloWorldController and add a function called “SayHello”.  When you are done your HelloWorldController should look like this:



The “HelloWorldController” now has a function that will accept a string called “username” and return that to the View.  In order to complete this process we must now create a View that will display what is returned by the “SayHello” function.  To add our view you must first right click on the “Views” folder and add a new folder called “HelloWorld”.  Once created right click the folder and select Add->New Item.  In the “Add New Item” dialog select “MVC View Content Page” and name it “Greet.aspx”.



Next you will be prompted to select a master page.  The default one will work fine for our project so just click ok.



Now we will add some simple code to display a greeting to whatever name is in ViewData[“PersonsName”].  When you are finished your page should look like this:



The last step we need to take is also the step that I found the most confusing.  In the global.asax file we must update the RegisterRoutes method to map to our new page with the appropriate parameters.  For simplicitiy sake I will just provide the code to enter in but if you would like to see Routing explained I have a post that goes into more detail here.


To setup routing for this project we will add the following code BEFORE the default route that is already in the RegisterRoutes method.


            routes.MapRoute(

                "HelloWorld",

                "HelloWorld/{action}/{userName}",

                 new

                 {

                     controller = "HelloWorld",

                     action = "SayHello",

                     userName = "Mystery Man"

                 }

            );


When you done it should look like this.



Now it is time to see the fruits of our labor.  Run your project for the first time.  You should see the following page:



Now you must enter a URL that will be routed to our newly created page.  To do this enter “HelloWorld/Greet/Abe” after the URL above.  When you do you should see the page below:



Congratulations! You have created your first ASP.NET MVC page!

 

Conclusions:

While I had originally setout to find advantages of MVC vs Forms I feel that this tutorial really only served to introduce me to using the MVC framework.  Now that I am familiar with MVC I hope to do another tutorial that demonstrates (or dosn't) the advantages that MVC has over Forms.  Stay tuned...

Tags: , , ,

Blog | ASP.NET | MVC

Powered by BlogEngine.NET 1.6.0.0