ASP.NET 4.0 Hosting & ASP.NET 4.5 Hosting BLOG

BLOG about ASP.NET 4.5 Hosting, ASP.NET 4.0 Hosting and .NET 4.5 Framework and its Capabilities

.NET 4.5 Hosting :: .NET 4.5 Framework Developer Preview

clock September 19, 2011 11:03 by author Administrator

 

[This documentation is for preview only, and is subject to change in later releases. Blank topics are included as placeholders.]

This topic contains information about key features and improvements in the .NET Framework 4.5 Developer Preview. This topic does not provide comprehensive information and is subject to change.

New features and improvements are described in the following sections:

- .NET for Metro style apps
- Core New Features and Improvements
- Web
- Networking
- Windows Presentation Foundation (WPF)
- Windows Communication Foundation (WCF)
- Windows Workflow Foundation (WF)

.NET for Metro style apps

Metro style apps are designed for specific form factors and leverage the power of the Windows operating system. A subset of the .NET Framework is available for building Metro style apps for Windows using C# or Visual Basic. This subset is called .NET APIs for Metro style apps.

Core New Features and Improvements

The following features and improvements were added to the common language runtime and to .NET Framework classes:

- Ability to limit how long the regular expression engine will attempt to resolve a regular expression before it times out.
- Ability to define the culture for an application domain.
- Console support for Unicode (UTF-16) encoding.
- Support for versioning of cultural string ordering and comparison data.
- Better performance when retrieving resources.
- Zip compression improvements to reduce the size of a compressed file.
- Ability to customize a reflection context to override default reflection behavior through the CustomReflectionContext class.

Managed Extensibility Framework (MEF)

The Managed Extensibility Framework (MEF) provides the following new features:
- Support for generic types.
- Convention-based programming model that enables you to create parts based on naming conventions rather than attributes.
- Multiple scopes.

Asynchronous File Operations

In the .NET Framework 4.5 Developer Preview, new asynchronous features were added to the C# and Visual Basic languages. These features add a task-based model for performing asynchronous operations. To use this new model, use the asynchronous methods in the I/O classes.

Web

ASP.NET 4.5 Developer Preview includes the following new features:

- Support for new HTML5 form types.
- Support for model binders in Web Forms. These let you bind data controls directly to data-access methods, and automatically convert user input to and from .NET Framework data types.
- Support for unobtrusive JavaScript in client-side validation scripts.
- Improved handling of client script through bundling and minification for improved page performance.
- Integrated encoding routines from the AntiXSS library (previously an external library) to protect from cross-site scripting attacks.
- Support for WebSockets protocol.
- Support for reading and writing HTTP requests and responses asynchronously.
- Support for asynchronous modules and handlers.
- Support for content distribution network (CDN) fallback in the ScriptManager control.

Networking

The .NET Framework 4.5 Developer Preview provides a new programming interface for HTTP applications. For more information, see the new System.Net.Http and System.Net.Http.Headers namespaces.

Also, the following networking improvements are included in the System.Net, System.Net.Mail, and related namespaces:

- Improved internationalization and IPv6 support.
- RFC-compliant URI support.
- Support for Internationalized Domain Name (IDN) parsing.
- Support for Email Address Internationalization (EAI).

Windows Presentation Foundation (WPF)

In the .NET Framework 4.5 Developer Preview, Windows Presentation Foundation (WPF) contains changes and improvements in the following areas:

- The new Ribbon control, which enables you to implement a ribbon user interface that hosts a Quick Access Toolbar, Application Menu, and tabs.
- The new INotifyDataErrorInfo interface, which supports synchronous and asynchronous data validation.
- New features for the VirtualizingPanel and Dispatcher classes.
- Improved performance when displaying large sets of grouped data, and by accessing collections on non-UI threads.
- Data binding to static properties, data binding to custom types that implement the ICustomTypeProvider interface, and retrieval of data binding information from a binding expression.
- Repositioning of data as the values change (live shaping).
- Better integration between WPF and Win32 user interface components.
- Ability to check whether the data context for an item container is disconnected.
- Ability to set the amount of time that should elapse between property changes and data source updates.
- Improved support for implementing weak event patterns. Also, events can now accept markup extensions.

Windows Communication Foundation (WCF)

In the .NET Framework 4.5 Developer Preview, the following features have been added to make it simpler to write and maintain Windows Communication Foundation (WCF) applications:

- Simplification of generated configuration files.
- Support for contract-first development.
- Ability to configure ASP.NET compatibility mode more easily.
- Changes in default transport property values to reduce the likelihood that you will have to set them.
- Updates to the XmlDictionaryReaderQuotas class to reduce the likelihood that you will have to manually configure quotas for XML dictionary readers.
- Validation of WCF configuration files by Visual Studio as part of the build process, so you can detect configuration errors before you run your application.
- New asynchronous streaming support.
- New HTTPS protocol mapping to make it easier to expose an endpoint over HTTPS with Internet Information Services (IIS).
- Ability to generate metadata in a single WSDL document by appending ?singleWSDL to the service URL.
- Websockets support to enable true bidirectional communication over ports 80 and 443 with performance characteristics similar to the TCP transport.
- Support for configuring services in code.
- XML Editor tooltips.
- ChannelFactory caching support.
- Binary encoder compression support.

Windows Workflow Foundation (WF)

Several new features have been added to Windows Workflow Foundation (WF) in the .NET Framework 4.5 Developer Preview. These new features include:

- Ability to create state machine workflows.
- Enhanced Workflow Designer features such as the following:
    - Enhanced workflow search capabilities in Visual Studio, including Quick Find and Find in Files.
    - Ability to automatically create a Sequence activity when a second child activity is added to a container activity, and to include both activities in the Sequence activity.
    - Panning support, which enables the visible portion of a workflow to be changed without using the scroll bars.
    - A new Document Outline view that shows the components of a workflow in a tree-style outline view and lets you select a component in the Document Outline view.
    - Ability to add annotations to activities.
    - Ability to define and consume activity delegates by using the workflow designer.
    - Auto-connect and auto-insert for activities and transitions in state machine and flowchart workflows.
- Storage of the view state information for a workflow in a single element in the XAML file, so you can easily locate and edit the view state information.
- A NoPersistScope container activity to prevent child activities from persisting.
- Support for C# expressions:
    - Workflow projects that use Visual Basic will use Visual Basic expressions, and C# workflow projects will use C# expressions.
    - C# workflow projects that were created in Visual Studio 2010 and that have Visual Basic expressions are compatible with C# workflow projects that use C# expressions.
- Versioning enhancements:
    - The new WorkflowIdentity class, which provides a mapping between a persisted workflow instance and its workflow definition.
    - Side-by-side execution of multiple workflow versions in the same host, including WorkflowServiceHost.
    - In Dynamic Update, the ability to modify the definition of a persisted workflow instance.
- Contract-first workflow service development, which provides support for automatically generating activities to match an existing service contract


This article is sourced from http://msdn.microsoft.com/en-us/library/ms171868(v=VS.110).aspx as it is correct as per 19th Sept 2011.

 



Silverlight (and WPF) Hosting: How to make items stretch horizontally in a ListBox

clock September 16, 2011 07:46 by author Administrator

 

Sometimes we need to use controls like TextBox, TextBlock etc (that set their width automatically depending on content) in a ListBox’s ItemTemplate. If we need to draw Borders or assign Background colors to each such controls then we may end up having non-equal rows. Here’s a sample markup:


 

Here’s the output for the above XAML:

 

A quick thought would be to assign HorizontalContentAlignment property to Stretch for the TextBox but this wont work. We need to specify this property for the ListBoxItem that encapsulates our DataTemplate. Here’s a quick syntax for doing this using a style:

And here’s the output:

This should be fine in most case but sometimes we also need to wrap the text as highlighted using red arrows in the above image. Now setting TextWrapping property will have no effect as the TextBox thinks it can take all the horizontal space. This can be solved by disabling the horizontal scroll bar for the ListBox:

Here’s the final output:
    

 



ASP.NET Hosting :: Things to AVOID in JSON serialization

clock September 13, 2011 06:59 by author Administrator

If you’ve spent much time working with the .NET platform, ASP.NET’s simple, convention-based approach to exposing JSON endpoints seems just about too good to be true. After years of fiddling with manual settings in XML configuration files, it’s understandable to assume that working with JSON in ASP.NET would require a similar rigmarole, yet it does not.

Unfortunately, this unexpected ease-of-use isn’t obvious if you don’t already know about it, which has led some developers to build needlessly complicated solutions to problems that don’t actually exist. In this post, I want to point out a few ways not to approach JSON in ASP.NET and then show you a couple examples of leveraging the frame work to do it “right”.

A couple examples of what NOT to do

To show you exactly what I’m talking about, let’s start by looking at a few concrete examples of ways that you should not handle sending and receiving JSON in your ASP.NET services.

For all the examples, we’re going to be trying to send and/or receive instances of this Person class:

public class Person
{
  public string FirstName { get; set; }
  public string LastName { get; set; }
}

Once you progress beyond simple scalar types, sending objects (and collections of them) back and forth is a pretty logical next step, and that’s also the point where this manual serialization trouble seems to begin. So, working with this simple Person class should serve as a realistic example, without being overly complex.

Manual serialization, using JavaScriptSerializer

The most common variant of this mistake that I’ve seen is using JavaScriptSerializer to manually build a JSON string and then returning that string as the result of a service method. For example, if you didn’t know better, you might do this to return an instance of the Person class:

[ScriptService]
public class PersonService : WebService
{
  [WebMethod]
  public string GetDave()
  {
    Person dave = new Person();
 
    dave.FirstName = Dave;
    dave.LastName = Ward;
 
    JavaScriptSerializer jss = new JavaScriptSerializer();
 
    // Results in {"FirstName":"Dave","LastName":"Ward"}
    string json = jss.Serialize<Person>(dave);
 
    return json;
  }
}

This may look sensible enough on the surface. After all, the json variable does end up containing a nicely serialized JSON string, which seems to be what we want. However, you should not do this.

What actually happens

Part of the beauty of using ASP.NET’s JSON-enabled services is that you rarely have to think much about the translation between JSON on the client-side and .NET objects on the server-side. When requested with the proper incantations, ASP.NET automatically JSON serializes your service methods’ responses, even if their result is an object or collection of objects.

Unfortunately, that automatic translation also makes it easy to end up with doubly-serialized responses if you aren’t aware that ASP.NET is already handling the serialization for you, which is exactly what would happen in the preceding example. The end result is that the Person object is serialized twice before it gets back to the browser – once as part of the method’s imperative code and then a second time by convention.

In other words, it’s understandable to expect the previous code example would return this response:

{"FirstName":"Dave","LastName":"Ward"}

But, what it actually returns is this:

// All the quotes in the manually generated JSON must be escaped in 
//  the second pass, hence all the backslashes.
{"d":"{\"FirstName\":\"Dave\",\"LastName\":\"Ward\"}"}

What a mess. That’s probably not what you had in mind, is it?

Using DataContractJsonSerializer or Json.NET is no better

This may seem obvious, but I want to point out that using a different manual serialization tool, like WCF’s DataContractJsonSerializer or Json.NET, in place of JavaScriptSerializer above does not remedy the underlying problem. I only mention it because I’ve seen those variations of the mistake floating around too.

If anything, in the case of DataContractJsonSerializer, it’s even worse. DCJS’ handling of Dictionary collections and Enums makes life unnecessarily tedious at times, and the code to manually invoke it is even more verbose than that for JavaScriptSerializer.

The impact this mistake has on the client-side

If it weren’t bad enough to add extra computational overhead on the server-side, cruft up the response with escaping backslashes, and increase the size of the JSON payload over the wire, this mistake carries a penalty on the client-side too.

Most JavaScript frameworks automatically deserialize JSON responses, but (rightfully) only expect one level of JSON serialization. That means that the standard functionality provided by most libraries will only unwrap one level of the doubly serialized stack of JSON produced by the previous example.

So, even after the response comes back and your framework has deserialized it once, you’ll still need to deserialize it a second time to finally extract a usable JavaScript object if you’ve made the mistake of manually serializing. For example, this is code you might see to mitigate that in jQuery:

$.ajax({
  type: 'POST',
  dataType: 'json',
  contentType: 'application/json',
  url: 'PersonService.asmx/GetDave',
  data: '{}',
  success: function(response) {
    // At this point, response is a *string* containing the
    //  manually generated JSON, and must be deserialized again.
 
    var person;
 
    // This is a very common way of handling
    //  the second round of JSON deserialization:
    person = eval('(' + response + ')');
 
    // You'll also see this approach, which
    //  uses browser-native JSON handling:
    person = JSON.parse(response);
 
    // Using a framework's built-in helper 
    //  method is another common fix:
    person = $.parseJSON(person);
  }
});

Regardless of which approach is used, if you see code like this running after the framework has already processed a response, it’s a pretty good indication that something is wrong. Not only is this more complicated and verbose than it needs to be, but it adds additional overhead on the client-side for absolutely no valid reason.

Flipping the script (and the JSON)

Redundant JSON serialization on responses is definitely one of the most common variations of this problem I’ve seen, but the inverse of that mistake also seems to be an alluring pitfall. Far too often, I’ve seen service methods that accept a single JSON string as their input parameter and then manually parse several intended inputs from that.

Something like this to accept a Person object form the client-side and save it on the server-side, for example:

[ScriptService]
public class PersonService : WebService
{
  [WebMethod]
  public void SavePerson(string PersonToSave)
  {
    JavaScriptSerializer jss = new JavaScriptSerializer();
 
    Person p = jss.Deserialize<Person>(PersonToSave);
 
    p.Save();
  }
}

Just as ASP.NET automatically JSON serializes responses on its JSON-friendly services, it also expects that the input parameters will be in JSON format and automatically deserializes those on the way in. So, in reverse order, the approach above makes a mistake similar to the ones shown earlier.

To make this work, we’d need to pass in JSON that looks something like this, obfuscating the actually desired input parameters inside a single, doubly-serialized string parameter.

{"PersonToSave":"{\"FirstName\":\"Dave\",\"LastName\":\"Ward\"}"}

Through the convenience of JSON.stringify(), it’s not even terribly hard to stumble onto a process for cobbling that double-JSON structure together on the client-side and making this approach work. I strongly recommend against it though. Even if the double-JSON didn’t carry extra overhead in several aspects, having a single input parameter of type string on this method is misleading. A year from now, will anyone realize what type of parameter that method accepts without looking down into the manual parsing code? Probably not.

Doing it right

Briefly, here are what I suggest as better ways to handle passing our Person object in and out of ASP.NET services.

Returning an object

Returning a .NET object from ASP.NET services is incredibly easy. If you let go and just trust the service to handle JSON translation for you, “it just works”:

[ScriptService]
public class PersonService : WebService
{
  [WebMethod]
  public Person GetDave()
  {
    Person dave = new Person();
 
    dave.FirstName = Dave;
    dave.LastName = Ward;
 
    // So easy!
    return dave;
  }
}

As long as you call that service method through a ScriptManager’s service proxy or using the correct parameters when using a library like jQuery, ASP.NET will automatically serialize the Person object and return it as raw, unencumbered JSON.

Accepting an object from the client-side

Accepting a Person object from the client-side works identically, in reverse. ASP.NET does a great job of matching JSON-serialized request parameters to .NET’s types, collections, and even your own custom objects.

For example this is how you could accept a Person object, which would even then allow you to call that object’s custom methods:

[ScriptService]
public class PersonService : WebService
{
  [WebMethod]
  public void SavePerson(Person PersonToSave)
  {
    // No, really, that's it (assuming Person has a Save() method).
    PersonToSave.Save();
  }
}

 



RIA Service Hosting :: How to send complex types to the Client

clock September 13, 2011 06:38 by author Administrator

 

Entity Framework 4 allows us to create complex types. Typically, such types are used to get the result of a stored procedure. However, when we try to send such a complex type using a WCF RIA Domain Service, the following error is encountered.



What to do? Adding attributes to EF designer generated classes is a bad idea; Also, we cannot use partial classes to add attributes to an already defined property. However, luckily, WCF RIA Services uses metadata classes in conjunction with the entity model classes and hence we can always create a meta data class for our complex type and decorate one of the fields with a
[Key] attribute. E.g., If our stored procedure is returning StoredProcedure_Result, then we may just need to add the following in our DomainService.metadata.cs file:



ASP.NET 4 Hosting :: Main Differences of Custom Control and User Control

clock August 23, 2011 07:57 by author Administrator

If you are thinking to build a control and apply the same to more than one place, you can take two kinds of approaches. Either you can create an User control inheriting from UserControl and adding a XAML for your control or use CustomControl to write yourself. Either one of them you choose they have their own pros and cons. Here in this post I will define what are the differences between the two approaches so that you can choose either one of them based on your requirement.

Before we start lets define both the terms:

UserControl : A usercontrolis a reusable chunk of user interface that is built up as a composition of other UIElement in the same style the main UI is built. In other words, a user control is just like a normal application block that can be used as Reusable component, and can be defined both using XAML and code together. It gives you a fresh UI canvas where you can define your custom reusable component that can be used widely in the application. In WPF, UserControl acts as a base class for any reusable component, but if you are looking for inheriting some other base, you can look into this.

Limitation of UserControl :

1. Appearance of an UserControl cannot be changed using a Template. Even though it has a property for Template, but it is of no use, as you cannot change the appearance of UserControl through this property.

2. UserControl is derived from ContentControl, thus if you change the Content of an usercontrol the entire UI will be replaced with that content.

3. As UserControl has both XAML and code behind. But as XAML can be used only once for entire inheritance hierarchy, you cannot use XAML for any class that inherits from your userControl. This is actually because Application.LoadComponent loads up the XAML once and is incompatible with inheritance. Thus when loading the XAML, the IComponentConnector interface is used to hook events and fields from XAML, hence you cannot replace XAML from your base class.

Custom Control: A customcontrol is a User interface element that has a distinct behaviour. A CustomControl is just a class that has one default appearance defined in Generic.xaml style which can be replaced by Template and Style at runtime but the behaviour you define for the control remains the same. So choose a CustomControl only when you need a certain kind of behaviour which is not there with the existing controls you have.

Note: Please don’t create a new custom control just to change the UI appearance as you can do this with any control available using custom Template

Limitation :

1. You have to define each behaviour for your control using Code. So it is hard way of achieving a behaviour.

2. Generic style is needed to be defined with your custom control to ensure that your control has a default look and feel.

Hence, based on your own requirement, if you are looking for a new behaviour which is different from existing userinterfaces available with WPF, you go for a Custom Control. A customControl can be styled and templated and best suited for a situation when you are building a Control Library.

On the contrary, a UserControl gives you an easy way to define reusable chunk of XAML which can be reused widely in your application and when you don’t need to use it as a Control Library.

I hope this gives you a brief idea on the differences between the two.

Happy Coding.



BlogEngine 2.5 Hosting with ASPHostCentral.com

clock July 13, 2011 07:10 by author Administrator

Blogengine.Net 2.5 has just been released and the following are some the features you can find on this new blogging tool:

- Upgraded to .NET 4.0
- Multiple Blogs in Single Installation
- Razor Theme support (Razor theme included, "Garland-Revisited")
- Converted Admin pages to Razor (Dashboard, Extensions, Themes)
- Install Themes from the BlogEngine.NET Gallery while in the BlogEngine.NET control panel.
- New language resource files for Estonian and Polish, and other translations updated.
- Upgraded to jQuery 1.5.2.
- Upgraded to latest version of tinyMCE WYSIWYG editor, v3.4.3.1.
- Numerous fixes and improvements.

If you want to test-drive this new version, the release candidate can be downloaded here final version can be downloaded here.

Looks promising, so yesterday I downloaded the latest branch to get a little preview, and what did I see?

My very own Facebook thingy into action! It was a nice feeling to see it there, but I wished I could contribute more. See I've been working in my top secret underground lab to add Facebook comments to Blogengine.net, and while just hacking it in there is relatively easy to do, making it so that others can easily use the code for themselves is a second. Partially because Facebook's API is kind of...dodgy. In the way that it requires some XML namespaces added to the html tag, which is in the theme.

That sounds like a nightmare to me, because it would mean every user needs to change his or hers theme manually. "Luckily" it seems it also works with some Javascript, and I want to test that a bit more and see if I can get it worked out into a extension or even added to the build. But it seems with all my assignments I won't make that for the 2.5 release but oh well...there will be other releases.

In the meantime I hope Facebook finds out a way of doing things that is both clean and html 5 compliant.



Silverlight WCF Hosting :: Cross-Origin Resource Sharing (CORS) and WCF

clock July 5, 2011 08:45 by author Administrator

Yesterday I encountered the following question in the MSDN forums about calling a cross-domain WCF RESTful service from Chrome.

The problem with doing the above is because there is a cross-domain call to a WCF service. When you are using Chrome, the browser tries to find out if it can do the call by sending a cross-origin resource sharing (CORS) request, as explained in this article. In IE, you will most likely get a cross-domain exception.

After searching the web a bit, I found that the immediate solution is to change the supported HTTP method of the operation to “*”, and to add the special cross-origin headers to the outputted response, like so:

WebOperationContext.Current.OutgoingResponse.Headers.Add(
  "Access-Control-Allow-Origin", "*"); WebOperationContext.Current.OutgoingResponse.Headers.Add(   "Access-Control-Allow-Methods", "POST"); WebOperationContext.Current.OutgoingResponse.Headers.Add(
  "Access-Control-Allow-Headers", "Content-Type, Accept");

There are two problems with this solution:

You need to repeat these lines in each of your service methods.
The service method is called twice, once for the “preflight” request (the request with the OPTIONS HTTP verb), and a second time for the invocation itself.

So I took the time and written a special endpoint behavior that can be attached to any webHttpBinding based endpoint.

The code does the following:

1. Every response message gets the “Access-Control-Allow-Origin” header with the value of “*”, to tell the client that the service allowed the request from the client.

2. If the client sends a request to the service with the verb OPTIONS (this is referred to as a “preflight” request), the service will automatically return a 200 (ok) response with the required headers: “Access-Control-Allow-Headers” and “Access-Control-Allow-Methods” (in addition to the allow-origin header). Clients that look for the “allow” headers in the response will then send the original required request to the service.

The benefits of using this behavior is:

The code that returns the message with the headers is located in the behavior itself – no need to place it in each service method.

The behavior catches the OPTIONS request, and does not require running the service method twice.

You do not need to change any part of your service contract or service implementation. The behavior is only needed to be applied using configuration.

To implement this behavior I used a message inspector that checks the request and changes the response, and an operation invoker that wraps the unhandled operation invoker. The custom operation invoker handles the OPTIONS message requests, which otherwise would have caused the service to return an error message (because no method is set to handle “Options” requests).

The endpoint behavior can be attached to the endpoint through configuration, like so:

<behaviors>
  <endpointBehaviors>
    <behavior name="webSupport">
      <webHttp />
      <CorsSupport />
    </behavior>
  </endpointBehaviors>
</behaviors>

<extensions>
  <behaviorExtensions>
    <add name="CorsSupport" type="WebHttpCors.CorsSupportBehaviorElement, WebHttpCors, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" />
  </behaviorExtensions>
</extensions>
<services>
  <service name="Service.JSonService">
    <endpoint address="http://localhost:8080" behaviorConfiguration="webSupport” binding="webHttpBinding" contract="Service.IJSonService" />
  </service>
</services>

Or, if you are using IIS to host your services, I also created a service host factory that creates a WebServiceHost and adds the behavior to every webHttpBinding based endpoint created by the host. To use it in your .svc file, just write something like this:

<%@ ServiceHost Language="C#" Debug="true" Service="Service.JSonService, Service" Factory="WebHttpCors.CorsWebServiceHostFactory, WebHttpCors" %>

To test the two hosts, open the webform1.aspx and change the target URL to access the IIS/self-hosted service.

Enjoy!



ASP.NET 4 Hosting :: How to Register HTTP Module at Runtime without Editing web.config?

clock July 4, 2011 08:35 by author Administrator

The ASP.NET pipeline allows HTTP modules to be plugged-in to a request and intercept or modify each individual request. Modules can be used for processes like caching, authentication etc. However a basic requirement for an HTTP module to function, is that it must be registered in your config file. This leads to editing the Web.Config whenever you have to add/remove modules. I hate fudging with my config file too often!

Not known to many developers, ASP.NET 4.0 provides the PreApplicationStartMethodAttribute which allows you to run code even before any app_start event gets fired or any dynamic compilation occurs (App_code).

So how do I register an HTTP Module at Runtime using PreApplicationStartMethodAttribute and DynamicModuleUtility.RegisterModule?

It’s a simple 3 process step!

Step 1: Implement your Module. In the code shown below, we are implementing the IModule interface and subscribing to the BeginRequest event of the HttpApplication object. The OnBeginRequest method hooks up to the BeginRequest event.



Step 2: Register the Module dynamically using the DynamicModuleUtility.RegisterModule method. Write this code in the same class you created above



Step 3: The final step is to use the PreApplicationStartMethod attribute. Just add this  attribute at the assembly level in the AssemblyInfo file or as shown below:

There you go! You have just registered an HTTP module into the ASP.NET pipeline without making any changes to web.config file.

 

 

 

 



WebMatrix Hosting :: How To Produce a CSHTML with TweetMeme Helper

clock May 17, 2011 06:39 by author Administrator

Microsoft has recently introduced the first beta of its new stack for building great web sites – WebMatrix. One of the key components of WebMatrix is the ASP.Net Web Pages “Razor” Syntax (or simply: CSHTML) that lets you write C# code inside the HTML markup.



Helpers in WebMatrix

Among the new possibilities and simplicity that this approach brings to people who build web sites, there is also the notion of Helper. Helpers are a way to use a single line of code for a common task that originally had taken several lines of code to do. Such helpers can be:

- Sending mails
- Displaying a WebGrid for presenting tabular data
- Adding the Facebook button
- Querying the database
- Displaying a Twitter profile
- Embedding rich media (Silverlight, Flash, WMV)

In this post I will show how to create a custom helper to use in your ASP.Net Web Pages with Razor Syntax inside WebMatrix. For the demo I will build a TweetMeme helper that embeds the familiar TweetMeme button.

There are 2 ways of creating helpers to use in WebMatrix:

1. Create the helper as a Class Library.
2. Create it as a class and distribute the code.

Create CSHTML Helper for WebMatrix as a Class Library in Visual Studio 2010

1. Open Visual Studio 2010, and create a new Class Library that targets .Net Framework 4 called TweetMeme.Helpers.
2. Add a reference to System.Web.dll.
3. Rename the default file (Class1.cs) to a more meaningful name, such as TweetMeme.cs.
4. Rename the class name in that file to TweetMeme, and remove the namespace declaration. You better off without a namespace when using helpers.

In order to implement a custom helper, you should create a method that will render to required HTML for the helper. This method should be public and static method and should return IHtmlString as the following code:

public static IHtmlString Button(... parameters ... )
{
    // Generate the HTML
    string html = ...
    return new HtmlString(html);
}

5. Implement the TweetMeme button method:

public static IHtmlString Button(string Url,
    string  Twitter = null,
    bool    Compact = false,
    string  UrlShortenerService = "bit.ly",
    string  UrlShortenerAPIKey = null)
{
    // Generate the HTML
    string html = GeneratedCode(Url, Twitter, Compact, UrlShortenerService, UrlShortenerAPIKey);
    return new HtmlString(html);
}

6. Implement the GenerateCode method, that generates the HTML for TweetMeme:

private static string GeneratedCode(string url, string twitterName = null, bool isCompact = false, string UrlShortenerService = "bit.ly", string UrlShortenerAPIKey = null)
{
    if (string.IsNullOrEmpty(url))
        throw new ArgumentException("Url cannot be null or empty", url);

    StringBuilder builder = new StringBuilder();
    builder.Append("<script type=\"text/javascript\"> ");
    if (isCompact)
        builder.Append("tweetmeme_style = 'compact'; ");
    builder.Append(string.Format("tweetmeme_url = '{0}'; ", url));
     if (!String.IsNullOrEmpty(twitterName))
        builder.Append(string.Format("tweetmeme_source = '{0}'; ", twitterName));
    if (!String.IsNullOrEmpty(UrlShortenerService))
    {
        builder.Append(string.Format("tweetmeme_service = '{0}'; ", UrlShortenerService));
        if (!String.IsNullOrEmpty(UrlShortenerAPIKey))
            builder.Append(string.Format("tweetmeme_service_api = '{0}'; ", UrlShortenerAPIKey));
    }
    builder.Append("</script> ");
    builder.Append("<script type=\"text/javascript\" src=\"http://tweetmeme.com/i/scripts/button.js\"></script>");
    return builder.ToString();}

7. That’s it. The helper is ready to use.

Using a Custom Helper in WebMatrix

To use a custom helper in WebMatrix that is delivered as an assembly, you simply have to copy that .dll into a bin folder in your site.

1. In WebMatrix, add a bin folder to the root of your site.
2. Copy the output assembly of the helper (from the bin\debug\ folder of the class library you have just created) to the bin folder of the site.
3. In your code, simply call the Helper:

@TweetMeme.Button(url: Request.Url.AbsoluteUri,                  
twitter: "bursteg", // replace with your twitter name                 
 compact: false)

Notice: If you now run your site locally, you with receive a TweetMeme button with a question mark in it. This is just because the url that it points to is a localhost address and not something that can be reached from the outside.

Create CSHTML Helper as a Class file inside WebMatrix

The second approach for creating helpers for WebMatrix is just adding a C# file with the helper class.

1. Inside WebMatrix, add a folder called App_Code to your web site.
2. Into the App_Code folder, add a new C# class to your web site.


3. Create the helper in this file using the same code as above


4. Use the helper in your code as shown above.

Conclusion

There are 2 approaches for creating Helpers for CSHTML. Creating helpers in class libraries are probably the better way of doing this in the eyes of professional developers, but my guess is that people who build web sites will prefer copying and pasting code samples for helpers to use in the project, and we will have a great community of helpers around the web.

Enjoy!

 

 

 

 



WPF Hosting :: Working with WPF Syntax Highlight

clock May 11, 2011 08:45 by author Administrator

If you are writing code for a while now then by now you must have a lot of code snippets which you will be using in your application development, and you use them because they save a lot of development time. At this moment we have now a huge collection of code snippets which includes functions, classes, extension methods and functions that we have extracted from different open source applications.

As we were progressing towards building an application in WPF which helps us managing all our code, a thought ran into our mind that it would be good if we could use syntax highlighting in the code. As usual we began my search to find a control in WPF which supports syntax highlighting and what we found, We were and we are at present satisfied. The control called AvalonEdit is a part of the free IDE called SharpDevelop for C# and VB.NET and Boo projects.

Languages support by the control:
- ASP/XHTML
- HTML
- JavaScript
- XML
- XMLDoc
- VB.NET
- C#
- C++
- Coco
- Java
- PHP
- Patch
- Boo
- TeX
- Custom Highlighting



After adding the reference in your project, add below XAML code on the window where you have your code window.



At line 4, we will use custom mapping (because it is a third-party control) so we can use the control in our project. At line 7, I have used TextEditor class of the AvalonEdit namespace. The font name and size is the same as of the source code text editor in Visual Studio 2010.

To get the control working with least configuration set some namespaces on the top, and two lines of code on window load for syntax highlighting and to show line numbers respectively.

Namespaces:


Window_Loaded:



If you wish to change the language, then just change the name of the language which is passed as a parameter in the GetDefinition method. The code in the Window_Loaded method will allow you to set syntax highlighting specifically for C#, pretty simple but not very useful. Check out the other way where the text editor will load the file and by reading the file extension, it will set the syntax highlighting. Above method will be useful if the user wants to set syntax highlighting of his choice. But if you want to detect the language and get the syntax highlighting automatically, then use the below code.



 The first line of code will Load the file and the second file will first get the extension of the file loaded, set the instance of the HighlightingManager class and in the end set the syntax highlighting. This is what we got in the end (We are using the second way to load the file). 

 


Note: To make sure that the second method work, you need to make sure that the file should have a language extension like .cs for C#, cpp for C++, xml for XML files etc. AvalonEdit is an open source code, so you can play around with it and can have your own customizations. There are lots of in-built configurations that you can do to set up your syntax highlighting control. I strongly recommend you to download the below files and take a look at the sample application.

 

 



ASP.NET 4.0 & ASP.NET 4.5 Hosting

 

ASPHostCentral is a premier web hosting company where you will find low cost and reliable web hosting. We have supported the latest ASP.NET 4.5 hosting and ASP.NET MVC 4 hosting. We have supported the latest SQL Server 2012 Hosting and Windows Server 2012 Hosting too!

 

Calendar

<<  May 2024  >>
MoTuWeThFrSaSu
293012345
6789101112
13141516171819
20212223242526
272829303112
3456789

View posts in large calendar

Sign in