Windows 2012 Hosting - MVC 6 and SQL 2014 BLOG

Tutorial and Articles about Windows Hosting, SQL Hosting, MVC Hosting, and Silverlight Hosting

WordPress Hosting – How To Resolve Download Failed for Installing WordPress Plugin or Updates in Windows Server 2012

clock February 1, 2013 12:43 by author andy_yo

After installing WordPress on our Windows Server 2012, we encountered a quite strange behavior. We can’t install new plugins or update our WordPress version, it always ends up with error: 'Download failed: Destination directory for file streaming does not exist or is not writable'. For example when we want to update the WodPress version:

Update WordPress

Downloading update from http://wordpress.org/wordpress-3.5.1-partial-0.zip…

Download failed.: Destination directory for file streaming does not exist or is not writable.

Installation Failed

Eventually, we started to do some research on this issue. In this article, we’ll try to give an overview of this issue, explaining why this occurs on Windows and how to solve this.

About ASPHostPortal.com

ASPHostPortal.com is Microsoft No #1 Recommended Windows and ASP.NET Spotlight Hosting Partner in United States. Microsoft presents this award to ASPHostPortal.com for ability to support the latest Microsoft and ASP.NET technology, such as: WebMatrix, WebDeploy, Visual Studio 2012, ASP.NET 4.5, ASP.NET MVC 4.0, Silverlight 5 and Visual Studio Lightswitch. Click here for more information

We found that the source of the error is WordPress need to access the system’s default temp folder (C:\Windows\temp) before installing a new plugin or update its version, and IIS user doesn’t have the write and read permission to that folder.

So what we need to do is:

1.       Create a temp folder in our site root directory and give IIS user the write and read permission to this folder.

2.       Change the default temp directory WordPress uses by adding this line to your wp-config.php:

         define('WP_TEMP_DIR','/path-to-the-folder-we-just-made');

Now we won’t those errors when we want to install plugin or update our WordPress because it already have the permission to access the temp directory.

 



Plesk Hosting - Parallels Plesk Panel 11 Adds Improved Performance and Security for Web Hosts

clock February 1, 2013 09:47 by author andy_yo

Parallels officially launched Parallels Plesk Panel 11, the latest version of its web hosting control panel software.

 

 

About ASPHostPortal.com

ASPHostPortal.com is Microsoft No #1 Recommended Windows and ASP.NET Spotlight Hosting Partner in United States. Microsoft presents this award to ASPHostPortal.com for ability to support the latest Microsoft and ASP.NET technology, such as: WebMatrix, WebDeploy, Visual Studio 2012, ASP.NET 4.5, ASP.NET MVC 4.0, Silverlight 5 and Visual Studio Lightswitch. Click here for more information

 

Web hosting software provider Parallels announced on Tuesday it officially launched Parallels Plesk Panel 11, the latest version of its web hosting control panel software, which adds many benefits for web hosts including improvements in website performance and security.

 

The move comes a couple months after the latest version of Parallels Automation became generally available, giving its web hosting partners a lot more options when it comes to offering services to small and medium-sized business customers.

The new version of Parallels Plesk Panel features over 80 improvements that were made based on customer feedback and Parallels’ vision for the hosting and cloud industries.

New features include the latest web technologies and faster performance in dedicated and virtualized environments, the addition of enhanced web presence tools, and free priority support for those web hosts who select the premium Plesk Unlimited dedicated license.

Parallels Plesk Panel 11 includes enhancements in key feature areas to help web hosting providers and web designers to simplify their business operations, lower their costs and drive more revenue.

These features include better server performance with NGINX so that Linux users can now reduce their CPU and memory usage by up to 50 percent, through the use of the NGINX server in Parallels Plesk Panel 11.

The NGINX server is installed and configured automatically in Parallels Plesk Panel 11, which accelerates website access and application response times beyond what is available in default Apache Web servers.

Parallels Plesk Panel 11 also includes a new Parallels Web Presence Builder that offers a more intuitive website building tool for small businesses and novice users, enabling web hosts to differentiate itself in a competitive market with self-service design tools for their SMB customers.

Parallels Web Presence Builder includes drag-and-drop modules that let users customize their website content, and automatically update their Facebook pages to mirror the content and aesthetic of their website.

For web designers, Parallels Web Presence Builder can also be sold as an entry-level website building tool, which can later be leveraged to upsell customers to more advanced, custom site designs.

There are also many new free support options that focus on the specific needs of hosting providers and web designers who rely on Parallels Plesk Panel to run their online businesses.

“There is a set of add-on functionality that is going to be shipped with Plesk,” Adam Bogobowicz, senior director of product marketing at Parallels, said in a phone interview. “One of the collections of functions is Powerpack, and it gives you the ability to build mobile websites, provides you with improved security for your server, gives you a set of developer tools. The other is improved performance of the website — both the traditional website and the mobile website. Plesk Panel 11 is going to be the most secure version of Plesk Panel ever released. It’s definitely going to make harden and make the operations of the panel more secure for all web hosts.”

Customers with business-critical needs who purchase an Unlimited dedicated Plesk SKU license will now receive free support by email, while those customers who purchase Unlimited dedicated Plesk SKU with Parallels Plesk Power Pack will receive free premium support.

Parallels has partnered with Unity Mobile to improve the overall performance for mobile websites. Parallels Plesk Panel users can now take existing websites and render them for optimized viewing and browsing from any mobile device.

Parallels Pleask Panel 11 offers improved security over previous versions, including enhanced server security and password storage and encryption to avoid potential vulnerabilities. Additionally, security updates are now highly visible and easier to apply in Parallels Plesk Panel 11.

Many of the new features and enhancements in Parallels Plesk Panel 11 focus on innovation and support for the newest Web technologies, including support the latest operating systems such as openSUSE 12.1, Ubuntu 12.04, and Debian 6, full support for IPv6, both the Linux and Windows Server platforms, and Microsoft’s WebMatrix Web development tool.

The Parallels Plesk Panel 11 user interface is now customizable, and can be simplified or extended based on the needs and the technical responsibilities of the user.

Hosted application support is included through the use of the APS v1.2, allowing APS packaged applications to be easily deployed on Parallels Plesk Panel servers.

A new Software Development Kit is provided to create Parallels Plesk Panel extensions in both Linux and Windows Server, allowing ISVs and Web developers to customize and extend the functionality of Parallels Plesk Panel 11.

Parallels has partnered with over 60 web hosting providers to offer Parallels Plesk Panel 11 including 123-Reg, Cirrus Hosing, Go Daddy, Host Gator, HostDime, LeaseWeb, Media Temple, PacHosting, SoftLayer, Superb Internet, and Webfusion.

In March, Parallels product manager Blake Tyra recently gave a demo of the Parallels Plesk Panel, where he showcased some of its functions for hosting providers, server administrators and small business operators.

 

 



Cloud Hosting - Cloud Computing Advantages

clock January 30, 2013 09:39 by author andy_yo

Cloud computing is a disruptive technology that is changing the way enterprises look to meet their IT hardware and software requirements. Cloud computing is a mix of the latest ideas, technology and delivery models including Infrastructure as a Service (IaaS), Platform as a Service (PaaS) and Software as a Service (SaaS), and other models in the IT sector that use the Internet for delivering services to the user. Users can access infrastructure namely, the servers, software, and data center space or network equipment; the required computing platform and solution stack for a building an application, covering the cycle of development, testing, deployment, hosting and maintenance; and also most of the regular software applications; these are all provided cheaply and efficiently over the Internet.

About ASPHostPortal.com

ASPHostPortal.com is Microsoft No #1 Recommended Windows and ASP.NET Spotlight Hosting Partner in United States. Microsoft presents this award to ASPHostPortal.com for ability to support the latest Microsoft and ASP.NET technology, such as: WebMatrix, WebDeploy, Visual Studio 2012, ASP.NET 4.5, ASP.NET MVC 4.0, Silverlight 5 and Visual Studio Lightswitch. Click here for more information

Some of the benefits of the Cloud are listed below:

Decreased Costs: The Cloud eliminates the need for each user to invest in stand-alone servers or software that is capital intensive, but under-utilized most of the time. As technological innovations take place, these resources become obsolete and must be replaced with the latest in order to ensure operational efficiency – requiring more capital investment – and the cycle repeats. The Cloud eliminates the need for such ‘replacement’ capital expenditure.
Many users share a Cloud leading to distributed costs and economies of scale as resources including real estate, bandwidth, and power, are centralized. The enterprise also saves on overheads such as management costs, data storage costs, costs of software updates, and quality control and is able to use Cloud services at economical rates.

Scalability and Speed: Enterprises no longer have to invest time in buying and setting up the hardware, software and other resources necessary for a new application. They can quickly scale up or scale down their usage of services on the Cloud as per market demands, during hours of maximum activity, while launching sales campaigns, etc. Cloud services are most usually reliable, since many service providers have data centers in multiple locations for keeping the processing near users.

Innovation: Enterprises can focus on innovation, as they do not have to own or manage resources. Cloud computing facilitates faster prototype development, testing and validation. Research and development projects or activities where users have to collaborate for a task/project are especially benefited.

Convenience: Sharing of infrastructure and costs ensures low overheads and immediate availability of services. Payments are billed on the basis of actual consumption only. Details of billing are made available by the service provider also serves to check costs.
Other than an Internet-connected device, special equipment or specially-trained manpower is not needed. One-off tasks can be performed on the Cloud. High-speed bandwidth ensures real-time response from infrastructure located at different sites.

Location Independence: Service providers can set up infrastructure in areas with lower overheads and pass on the benefit. They can set up multiple redundant sites to facilitate business continuity and disaster recovery. This helps the enterprise cut costs further.

Optimal Resource Utilization: Servers, storage and network resources are better utilized as the Cloud is shared by multiple users, thus cutting down on waste at a global level. Cloud computing is more environment-friendly and energy efficient. Down-time is cut and optimization of resources across enterprises on the Cloud is achieved.

Flexibility: Users can opt out at will and thus gain a high level of operational flexibility.  The services are covered by service level agreements and the service provider is required to pay a penalty if the quality agreed to is not provided.

Device Independence: Applications provided through the Cloud can be accessed from any device – a computer, a smartphone, an iPad, etc. Any device that has access to the Internet can leverage the power of the Cloud.



ASP.NET MVC Hosting - ASPHostPortal :: Make a Captcha Image Validation with Jquery and MVC

clock January 28, 2013 09:37 by author Jervis

The code snippets below show how to use a simple class. To create a validation mechanism via captcha in ASP.Net , using Jquery and MVC. 

Using the code  

The code consists of two parts that work together to make the code work.

The first in javascript that runs on the client and should be placed on the page header, is responsible for making the request to the server. 

Note: I must remember that this javascript code requires Jquery, which can be downloaded here

   <script type="text/javascript" language="javascript">
        $(document).ready(function () {
            loadCaptcha();
        });
        function loadCaptcha() {
            $.ajax({
                type: 'GET', url: 'Home/generateCaptcha',
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                cache: false,
                success: function (data) { $("#m_imgCaptcha").attr('src', data); },
                error: function (data) { alert("Error while loading captcha image") }
            });
        }
    </script>

The second in C# runs  on the server.

That Receives the request from the page, generates an image with the specified text, this text can be generated by a function embedded in class or can be specified by the developer. The text is saved in the Session and is used to validate the data entered by the user. 

public ActionResult generateCaptcha()
        {
            System.Drawing.FontFamily family = new System.Drawing.FontFamily("Arial");
            CaptchaImage img = new CaptchaImage(150, 50, family);
            string text = img.CreateRandomText(4) + " " + img.CreateRandomText(3);
            img.SetText(text);
            img.GenerateImage();
            img.Image.Save(Server.MapPath("~") + this.Session.SessionID.ToString() + ".png", System.Drawing.Imaging.ImageFormat.Png);
            Session["captchaText"] = text;
            return Json(this.Session.SessionID.ToString() + ".png?t=" + DateTime.Now.Ticks, JsonRequestBehavior.AllowGet);
        }

Here is an example of a captcha image generated using this code.

Advantages of use

You know what's running on your server.

No special settings are needed.

Is not necessary use third party components that can fail.

It is fully customizable. 

 



ASP.NET MVC 4 Hosting - ASPHostPortal :: Getting WebApi and Areas to play nicely ASP.NET MVC 4

clock January 21, 2013 07:08 by author Jervis

In this blog, I discuss these limitations and present a possible solution.

Background

The WebApi and Areas features play an important role in the project I am currently working on. In this project, a web application is developed for multiple types of end-users. Areas are used to create separate frontends for each type of end-user. WebApi is used as part of an interaction framework (knockoutjs) that enriches the user experience. Below is a list of relevant design decisions that were made:

- The main MVC application resides in the root of the solution.
- All administrator functionality resides in a separate area.
- Each external party has its own area.
- Each area, including the root, constitutes a well separated functional block. Functionality from one area may not be exposed to another area. This is to prevent unauthorized access of data.
- Each area, including the root, has its own RESTfull API (WebApi).

During the development of this web application, I encountered an important limitation of WebApi when used in conjunction with Areas.

Routing and WebApi

Both regular and WebApi calls use ASP.NET MVC’s routing mechanism to translate HTTP requests to the appropriate controller action. However, only regular calls support areas, while WebApi calls are “arealess”. As a result, WebApi controllers in different areas are actually accessible from all areas. Additionally, having multiple WebApi controllers with identical names in different areas will produce an exception:

Multiple types were found that match the controller named ‘clients’. This can happen if the route that services this request (‘api/{controller}/{id}’) found multiple controllers defined with the same name but differing namespaces, which is not supported.

The request for ‘clients’ has found the following matching controllers:
MvcApplication.Areas.Administration.Controllers.Api.ClientsController
MvcApplication.Controllers.Api.ClientsController

The error message pretty much sums up the problem: ASP.NET MVC 4 RC does not support the partitioning of WebApi controllers across areas.

IHttpControllerSelector

The culprit is the DefaultHttpControllerSelector which is ASP.NET MVC’s default implementation of the IHttpControllerSelector interface. This class is responsible for selecting the appropriate IHttpController (the interface implemented by ApiController), when provided with a HTTP request message. At the heart of the DefaultHttpControllerSelector lies the HttpControllerTypeCache. This class runs through all assemblies that are used by the application and caches all types that implement the IHttpController. The SelectController method of the DefaultHttpControllerSelector uses this cache to lookup a matching type for the given controller name. This operation can end in three different manners:

- No matching types were found, which results in an HttpStatus.NotFound (404).
- One matching type was found, which is returned by the method and ASP.NET MVC continues to process the request.
- Multiple matches were found, which results in an exception similar to one displayed earlier.

In search for a solution

Fortunately, through the power of Inversion of Control, developers can inject their own implementation of IHttpControllerSelector. In a related blog by Andrew Malkov, he attempts to tackle the problem by creating a custom implementation called AreaHttpControllerSelector.

This class allows area specific WebApi controllers to co-exist, provided one makes a minor modification to the WebApi routes. In order to function, a default route parameter called “area” must be added to the HttpRoute definition in the AreaRegistration file.

1              context.Routes.MapHttpRoute(
2                  name: "Administration_DefaultApi",
3                  routeTemplate: "Administration/api/{controller}/{id}",
4                  defaults: new { area = "Administration", id = RouteParameter.Optional }
5              );

Unfortunately, adding this extra parameter introduces a new limitation: Querystring parameters on WebApi calls no longer function. E.g. GET /Administration/api/clients will work, but GET /Administration/api/clients?firstname=john will result in a 404.

Part of the problem lies in the manner in which AreaRegistration is used to define routes. Consider the AdministrationAreaRegistration below:

1              public class AdministrationAreaRegistration : AreaRegistration
2              {
3                  public override string AreaName
4                  {
5                      get
6                      {
7                          return "Administration";
8                      }
9                  }
10          
11               public override void RegisterArea(AreaRegistrationContext context)
12               {
13                   context.Routes.MapHttpRoute(
14                       name: "Administration_DefaultApi",
15                       routeTemplate: "Administration/api/{controller}/{id}",
16                       defaults: new { id = RouteParameter.Optional }
17                   );
18          
19                   context.MapRoute(
20                       "Administration_default",
21                       "Administration/{controller}/{action}/{id}",
22                       new { action = "Index", id = UrlParameter.Optional }
23                   );
24               }
25           }

The first route defines how ApiContollers can be reached, while the second route defines how regular controllers can be reached. Both registrations use a different method for registering the route in order to differentiate between normal calls and WebApi calls. Routes registered through MapHttpRoute are meant for WebApi controllers while routes registered through MapRoute are meant for regular controllers.

Note that MapHttpRoute is called on the Routes collection, whereas MapRoute is called on the AreaRegistrationContext itself. This implies that there is a difference between the default MapRoute and the one provided by the AreaRegistrationContext.

After digging through the sourcecode of ASP.NET MVC, I found that the most notable difference is that the MapRoute of AreaRegistrationContext incorporates the AreaName into the route’s metadata. Specifically, the value of the AreaName property is added to the route’s DataTokens.

Solution – Part 1

I created a MapHttpRoute extension method for the AreaRegistrationContext that performed a similar operation as the AreaRegistrationContext.MapRoute method.

1              public static class AreaRegistrationContextExtensions
2              {
3                  public static Route MapHttpRoute(this AreaRegistrationContext context, string name, string routeTemplate)
4                  {
5                      return context.MapHttpRoute(name, routeTemplate, null, null);
6                  }
7             
8                  public static Route MapHttpRoute(this AreaRegistrationContext context, string name, string routeTemplate, object defaults)
9                  {
10                   return context.MapHttpRoute(name, routeTemplate, defaults, null);
11               }
12          
13               public static Route MapHttpRoute(this AreaRegistrationContext context, string name, string routeTemplate, object defaults, object constraints)
14               {
15                   var route = context.Routes.MapHttpRoute(name, routeTemplate, defaults, constraints);
16                   if (route.DataTokens == null)
17                   {
18                       route.DataTokens = new RouteValueDictionary();
19                   }
20                   route.DataTokens.Add("area", context.AreaName);
21                   return route;
22               }
23           }

To use the new extension method, remove the Routes property from the call chain:

1              context.MapHttpRoute(
2                name: "Administration_DefaultApi",
3                routeTemplate: "Administration/api/{controller}/{id}",
4                defaults: new { id = RouteParameter.Optional }
5              );

Now both the regular routes and the WebApi routes have knowledge of their corresponding area.

Solution – Part 2

The second part of the solution is to create an implementation of IHttpControllerSelector that actually uses the area name. I took the AreaHttpControllerSelector class from Andrew Malkov’s blog post and used it as a base for my own solution.

1              namespace MvcApplication.Infrastructure.Dispatcher
2              {
3                  using System;
4                  using System.Collections.Concurrent;
5                  using System.Collections.Generic;
6                  using System.Globalization;
7                  using System.Linq;
8                  using System.Net.Http;
9                  using System.Web.Http;
10               using System.Web.Http.Controllers;
11               using System.Web.Http.Dispatcher;
12          
13               public class AreaHttpControllerSelector : DefaultHttpControllerSelector
14               {
15                   private const string AreaRouteVariableName = "area";
16          
17                   private readonly HttpConfiguration _configuration;
18                   private readonly Lazy<ConcurrentDictionary<string, Type>> _apiControllerTypes;
19          
20                   public AreaHttpControllerSelector(HttpConfiguration configuration)
21                       : base(configuration)
22                   {
23                       _configuration = configuration;
24                       _apiControllerTypes = new Lazy<ConcurrentDictionary<string,
Type>>(GetControllerTypes);
25                   }
26          
27                   public override HttpControllerDescriptor SelectController(HttpRequestMessage request)
28                   {
29                       return this.GetApiController(request);
30                   }
31          
32                   private static string GetAreaName(HttpRequestMessage request)
33                   {
34                       var data = request.GetRouteData();
35                       if (data.Route.DataTokens == null)
36                       {
37                           return null;
38                       }
39                       else
40                       {
41                           object areaName;
42                           return data.Route.DataTokens.TryGetValue(AreaRouteVariableName, out areaName) ? areaName.ToString() : null;
43                       }
44                   }
45          
46                   private static ConcurrentDictionary<string, Type> GetControllerTypes()
47                   {
48                       var assemblies = AppDomain.CurrentDomain.GetAssemblies();
49          
50                       var types = assemblies
51                           .SelectMany(a => a
52                               .GetTypes().Where(t =>
53                                   !t.IsAbstract &&
54                                   t.Name.EndsWith(ControllerSuffix, StringComparison.OrdinalIgnoreCase) &&
55                                   typeof(IHttpController).IsAssignableFrom(t)))
56                           .ToDictionary(t => t.FullName, t => t);
57          
58                       return new ConcurrentDictionary<string, Type>(types);
59                   }
60          
61                   private HttpControllerDescriptor GetApiController(HttpRequestMessage request)
62                   {
63                       var areaName = GetAreaName(request);
64                       var controllerName = GetControllerName(request);
65                       var type = GetControllerType(areaName, controllerName);
66          
67                       return new HttpControllerDescriptor(_configuration, controllerName, type);
68                   }
69          
70                   private Type GetControllerType(string areaName, string controllerName)
71                   {
72                       var query = _apiControllerTypes.Value.AsEnumerable();
73          
74                       if (string.IsNullOrEmpty(areaName))
75                       {
76                           query = query.WithoutAreaName();
77                       }
78                       else
79                       {
80                           query = query.ByAreaName(areaName);
81                       }
82          
83                       return query
84                           .ByControllerName(controllerName)
85                           .Select(x => x.Value)
86                           .Single();
87                   }
88               }
89          
90               public static class ControllerTypeSpecifications
91               {
92                   public static IEnumerable<KeyValuePair<string, Type>> ByAreaName(this IEnumerable<KeyValuePair<string, Type>> query, string areaName)
93                   {
94                       var areaNameToFind = string.Format(CultureInfo.InvariantCulture, ".{0}.", areaName);
95          
96                       return query.Where(x => x.Key.IndexOf(areaNameToFind, StringComparison.OrdinalIgnoreCase) != -1);
97                   }
98          
99                   public static IEnumerable<KeyValuePair<string, Type>> WithoutAreaName(this IEnumerable<KeyValuePair<string, Type>> query)
100                 {
101                     return query.Where(x => x.Key.IndexOf(".areas.", StringComparison.OrdinalIgnoreCase) == -1);
102                 }
103        
104                 public static IEnumerable<KeyValuePair<string, Type>> ByControllerName(this IEnumerable<KeyValuePair<string, Type>> query, string controllerName)
105                 {
106                     var controllerNameToFind = string.Format(CultureInfo.InvariantCulture, ".{0}{1}", controllerName, AreaHttpControllerSelector.ControllerSuffix);
107        
108                     return query.Where(x => x.Key.EndsWith(controllerNameToFind, StringComparison.OrdinalIgnoreCase));
109                 }
110             }
111         }

If you want to learn more about the technical details of the solution, I suggest you read Andrew’s excellent blog post first. The most significant modifications are:

Changed the GetAreaName method in order to retrieve the area name from the DataTokens property rather than the RouteData.

Added support for “arealess” WebApi controllers (e.g. those that reside in the root) to the GetControllerType method.

Removed the fallback mechanism from the SelectController method. The original implementation would call the SelectController method of the base-class in case GetControllerType failed to produce a result. I preferred an approach where the responsibility of successful controller selection resided in AreaHttpControllerSelector.

Finally, to inject the new AreaHttpControllerSelector class, the following line must be added to the Application_Start method in the Global.asax.cs

1              GlobalConfiguration.Configuration.Services.Replace(typeof(IHttpControllerSelector), new AreaHttpControllerSelector(GlobalConfiguration.Configuration));

After these modifications everything worked as expected!

 



ASP.NET MVC 4 Hosting - ASPHostPortal :: Implementing custom XmlMediaTypeFormatter that ignores XML namespaces

clock December 21, 2012 10:25 by author Jervis

In this blog post I will show how to implement a custom XmlMediaTypeFormatter that extends the default ASP.NET Web API XmlMediaTypeFormatter in a way that it ignores XML namespaces when parsing xml messages.

By default the ASP.NET Web API XmlMediaTypeFormatter is not able to parse XML requests that contain any XML namespace declarations. If you would like to support clients, that (for any reason) send messages containing XML namespaces you can use the IgnoreNamespacesXmlMediaTypeFormatter that is defined as follows:

public class IgnoreNamespacesXmlMediaTypeFormatter : XmlMediaTypeFormatter
{
  // See http://wiki.tei-c.org/index.php/Remove-Namespaces.xsl
  private const string NamespaceRemover =
    @"<xsl:stylesheet version='1.0' xmlns:xsl='http://www.w3.org/1999/XSL/Transform'>
        <xsl:output method='xml' indent='no'/>
        <xsl:template match='/|comment()|processing-instruction()'>
          <xsl:copy>
            <xsl:apply-templates/>
          </xsl:copy>
        </xsl:template>
        <xsl:template match='*'>
          <xsl:element name='{local-name()}'>
            <xsl:apply-templates select='@*|node()'/>
          </xsl:element>
        </xsl:template>
        <xsl:template match='@*'>
          <xsl:attribute name='{local-name()}'>
            <xsl:value-of select='.'/>
          </xsl:attribute>
        </xsl:template>
      </xsl:stylesheet>";

  private readonly XslCompiledTransform _xlstTransformer;

  public IgnoreNamespacesXmlMediaTypeFormatter()
  {
    var xslt = XDocument.Parse(NamespaceRemover, LoadOptions.PreserveWhitespace);
    _xlstTransformer = new XslCompiledTransform();
    _xlstTransformer.Load(xslt.CreateReader(), new XsltSettings(), new XmlUrlResolver());
  }

  public override Task<object> ReadFromStreamAsync(Type type, Stream stream, HttpContentHeaders contentHeaders, IFormatterLogger formatterLogger)
  {
    try
    {
      // Read XML
      var xmlDocument = XDocument.Load(new XmlTextReader(stream));

      // Transform XML
      var resultStream = new MemoryStream();
      _xlstTransformer.Transform(xmlDocument.CreateReader(), XmlWriter.Create(resultStream, new XmlWriterSettings() { OmitXmlDeclaration = true }));
      resultStream.Position = 0;

      // Process request with XmlMediaTypeFormatter default functionality
      return base.ReadFromStreamAsync(type, resultStream, contentHeaders, formatterLogger);
    }
    catch (XmlException)
    {
      return base.ReadFromStreamAsync(type, stream, contentHeaders, formatterLogger);
    }
  }
}

In detail the IgnoreNamespacesXmlMediaTypeFormatter removes the XML namespace declarations from the XML message and passes the modified XML to the base class to use the default XmlMediaTypeFormatter functionality. Removing the XML namespaces is done with a XSLT transformation (see http://wiki.tei-c.org/index.php/Remove-Namespaces.xsl)

To activate the IgnoreNamespacesXmlMediaTypeFormatter add the following lines in the file Global.asax.cs:

protected void Application_Start()
{
  [...]
  // Remove default XmlFormatter and add (customized) IgnoreNamespacesXmlMediaTypeFormatter GlobalConfiguration.Configuration.Formatters.Remove(GlobalConfiguration.Configuration.Formatters.XmlFormatter);
  var ignoreNamespacesXmlMediaTypeFormatter = new IgnoreNamespacesXmlMediaTypeFormatter{ UseXmlSerializer = true };

GlobalConfiguration.Configuration.Formatters.Add(ignoreNamespacesXmlMediaTypeFormatter);
  [...]
}



Visual Studio 2012 Hosting - ASPHostPortal :: How to Extract to User Control Visual Studio 2012

clock December 21, 2012 04:55 by author Jervis

Visual Studio 2012 introduces another great feature for creating a user control out of the existing code. Till now we used to create different User controls and use it in main page. Now, with the introduction of Visual Studio 2012, we are developing the pages and generate the User controls from the existing page design.

For our sample, I used the default ASP.Net web application created by the Visual Studio. The Default.aspx page looks like the below.



Let us create our new User Control from the ordered list specified in the Default.aspx. Select the Code Snippet and right click to open the Context Menu.  

From the Context Menu, select “Extract to User Control” option. This will open the “Save as” window, where we need to specify the User Control name and select OK.

Now, Visual Studio will create the new “MyUserControl” user control and modify the Default.aspx page to utilize the same.   

MyUserControl is generated using the selected ordered list code as shown below.

Notice the changes in the Default.aspx page. Register tag for registering the user control is added on top of the page. Selected code snippet [in our case ordered list code] is replaced by the user control declaration.

Note: Visual Studio will copy only the designer code; it won’t copy the corresponding code behind code like the event handlers associated with the code snippet. 



SQL Hosting - ASPHostPortal :: How to Schedule Backup with SQL Server Express

clock December 14, 2012 09:31 by author Jervis

Microsoft’s SQL Server Express is a fantastic product for anyone needing a relational database on a limited budget. Server Express is free but it comes with a few limitations such as only utilizing 1 GB of RAM,  databases are limited to 10 GB, and it does not include SQL Profiler. For low volume sites that do not need enterprise level capabilities, this is a compelling solution. Here is a complete SQL Server feature comparison of all the SQL Server editions.

There is one other important limitation that needs to be mentioned which is that SQL Server Express does not include SQL Agent. This means that you can not schedule administrative tasks such as backing up your databases.  As everyone knows backing up data is critical and with SQL Server Express you can still backup your databases but you have to do it manually. So what does one do if you don’t have a budget to license SQL Server  but you need scheduled backups of your databases?

The answer is SQL Scheduler. SQL Scheduler is a simple lightweight application that installs on your server and runs as a service. Using the application’s GUI you can create multiple jobs to run your backups on a predefined schedule and you can even configure it to send you an email notification if it completes or fails to run properly.

After you download the program, unzip the archive and run InstallService.bat file from the command prompt. The installation will complete quickly.

Once you launch the program you just need to connect to your local SQL Server Express instance on your server. Here is how it will appear without any jobs configured.

From the File menu create a new job. In this example we’ll create 1 job to take a full backup of each database that is configured on the server.

Click on the Details tab and you’ll be able to enter your SQL statements for whatever task you’re trying to accomplish. Be sure to edit the script and change the path of where you want the database backups stored on your server.

On the schedule tab you can define the time and date of your job will run.

To have the job send you an email upon completion or in the event of a failure open the SQLScheduler.WindowsService.exe.config file and enter the mail server address along with the and username and password for authentication.

<system.net>
  <mailSettings>
    <smtp deliveryMethod="Network" from=”[email protected]”>
      <network host="locahost" userName="x" password="x” />
    </smtp>
  </mailSettings>
</system.net>

Once the job runs a full backup will be created for each database and it will be stored in a subfolder of the path you specified in the script.
Now that your daily full backups are being created locally on the server the next step would be to either configure Windows Server Backup or configure 3rd party online backup solution.

 



Silverlight 5 Hosting - ASPHostPortal :: Telerik RadBarCode in SilverLight 5 Via WCF Service

clock November 29, 2012 08:03 by author Jervis

In this article let's concentrate on another Silverlight application, whereby communicating with a WCF Service to perform some operation.

The Telerik Rad Controls for Silverlight can be found from http://www.telerik.com/products/silverlight/controls.aspx.

The Rad Window is used to display the output in a nice and enhanced UI.

Question: What is RadBarCode?

In simple terms "It provides light weighted and easy systematic approach to generate bar-codes, it used to ensure unique id given to each product when evaluating".

Let's get this implemented practically for a better idea of this!!!

Step 1: The complete code of the IService1.cs looks like this.

using System;
using
System.Collections.Generic;
using
System.Linq;
using
System.Runtime.Serialization;
using
System.ServiceModel;
using
System.ServiceModel.Web;
using
System.Text;
namespace
Wcf_Rad_Bar
{
    // NOTE: You can use the "Rename" command on the "Refactor" menu to change the interface name "IService1" in both code and config file together.
    [ServiceContract]
    public interface IService1
    {
        [OperationContract]
        int bar(int a);
    }
}


Step 2: The complete code of the Service1.svc.cs looks like this.

using System;
using
System.Collections.Generic;
using
System.Linq;
using
System.Runtime.Serialization;
using
System.ServiceModel;
using
System.ServiceModel.Web;
using
System.Text;
namespace
Wcf_Rad_Bar
{
    // NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name "Service1" in code, svc and config file together.
    public class Service1 : IService1
    {
        public int bar(int a)
        {
            return a;
        }
    }
}


Step 3 : The complete code of the Web.Config looks like this.

<?xml version="1.0"?>
<
configuration>
  <system.web>
    <compilation debug="true" targetFramework="4.0" />
  </system.web>
  <system.serviceModel>
    <behaviors>
      <serviceBehaviors>
        <behavior>
          <!-- To avoid disclosing metadata information, set the value below to false and remove the metadata endpoint above before deployment -->
          <serviceMetadata httpGetEnabled="true"/>
          <!-- To receive exception details in faults for debugging purposes, set the value below to true.  Set to false before deployment to avoid disclosing exception information -->
          <serviceDebug includeExceptionDetailInFaults="false"/>
        </behavior>
      </serviceBehaviors>
    </behaviors>
    <serviceHostingEnvironment multipleSiteBindingsEnabled="true" />
  </system.serviceModel>
 <system.webServer>
    <modules runAllManagedModulesForAllRequests="true"/>
  </system.webServer>
</
configuration
>

Step 4 : The complete code of the Clientaccesspolicy.xml looks like this (to avoid cross domain problem in Silverlight).

<?xml version="1.0" encoding="utf-8"?>
<
access-policy>
    <cross-domain-access>
        <policy>
            <allow-from http-request-headers="SOAPAction">
                <domain uri="*"/>
            </allow-from>
            <grant-to>
                <resource path="/" include-subpaths="true"/>
            </grant-to>
        </policy>
    </cross-domain-access>
</
access-policy
>

Step 5 : The complete code of the MainPage.xaml looks like this. 

<UserControl x:Class="Rad_Bar_App.MainPage"
              xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
              xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
              xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
              xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
              xmlns:telerik="http://schemas.telerik.com/2008/xaml/presentation"
              mc:Ignorable="d" d:DesignWidth="640" d:DesignHeight="480">
    <Grid x:Name="LayoutRoot" Width="628" Height="452">
        <telerik:RadBarcode128 Name="radBar1"
                               ShowChecksum="False"
                               Margin="104,0,113,189"
                               Height="89"
                               VerticalAlignment="Bottom">
       </telerik:RadBarcode128>
        <TextBlock Height="23"
                   HorizontalAlignment="Left"
                   Margin="191,12,0,0"
                   Name="textBlock1" Text="Please Enter Bar Code Number"
                   FontFamily="Verdana"
                   FontSize="15"
                   VerticalAlignment="Top" />
         <TextBox Height="23"
                HorizontalAlignment="Left"
                 Margin="248,41,0,0"
                 Name="textBox1"
                 VerticalAlignment="Top"
                 Width="120" />
        <Button Content="Send BarCode"
                FontFamily="Verdana"
                Background="DeepSkyBlue"
                FontSize="15"
                Height="23"
                HorizontalAlignment="Left"
                Margin="235,82,0,0"
                Name="button1"
                VerticalAlignment="Top"
                Width="133"
                Click="button1_Click"/>
         <telerik:RadBarcode93 Name="radBar93"
                             Margin="104,336,113,22" ShowChecksum="False">
         </telerik:RadBarcode93>
       <TextBlock Height="23"
                   HorizontalAlignment="Left"
                   Margin="235,289,0,0"
                   Name="textBlock2"
                   Text="RadBarCode93"
                   FontFamily="Verdana"
                   FontSize="15"
                   VerticalAlignment="Top"
                   Width="170"
                   FontWeight="Bold"
                   Visibility="Collapsed"
                   /> 
        <TextBlock Height="23"
                   HorizontalAlignment="Left"
                   Margin="234,129,0,0"
                   Name="textBlock3"
                   Text="RadBarCode128"
                   FontFamily="Verdana"
                   FontSize="15"
                   FontWeight="Bold"
                   VerticalAlignment="Top"
                   Width="134"
                   Visibility="Collapsed"/>
    </Grid>
</
UserControl
>

Step 6 : The complete code of the MainPage.xaml.cs looks like this.

using System;
using
System.Collections.Generic;
using
System.Linq;
using
System.Net;
using
System.Windows;
using
System.Windows.Controls;
using
System.Windows.Documents;
using
System.Windows.Input;
using
System.Windows.Media;
using
System.Windows.Media.Animation;
using
System.Windows.Shapes;
using
Telerik.Windows.Controls;
using
Rad_Bar_App.ServiceReference1;
namespace
Rad_Bar_App
{    public partial class MainPage : UserControl
  {
        public MainPage()
        {
            InitializeComponent();
        }
       private void bar_Call(object sender, barCompletedEventArgs e)
        {
            radBar1.Visibility = System.Windows.Visibility.Visible;
            radBar93.Visibility = System.Windows.Visibility.Visible;
            radBar1.Text = e.Result.ToString();
            radBar93.Text = e.Result.ToString();
            textBlock2.Visibility = System.Windows.Visibility.Visible;
            textBlock3.Visibility = System.Windows.Visibility.Visible;
        }
        private void button1_Click(object sender, RoutedEventArgs e)
        {
            textBlock2.Visibility = System.Windows.Visibility.Collapsed;
            textBlock3.Visibility = System.Windows.Visibility.Collapsed;
            radBar1.Visibility = System.Windows.Visibility.Collapsed;
            radBar93.Visibility = System.Windows.Visibility.Collapsed;
            if (string.IsNullOrEmpty(textBox1.Text))
            {
                RadWindow.Alert("Please Enter Some Values");
           }
            else
            {
                Service1Client obj_Client = new Service1Client();
                obj_Client.barCompleted += new EventHandler<barCompletedEventArgs>(bar_Call);
                obj_Client.barAsync(Convert.ToInt32(textBox1.Text));
                textBox1.Text = "";
            }
        }
    }
}


Step 7 : The output of the application looks like this.

Step 8 : The output of the Nothing Entered Application looks like this.


Step 9 : The output of the BarCodeEntered Application looks like this.

 



SSRS 2012 Hosting - ASPHostPortal :: Permission in SSRS 2012

clock November 15, 2012 07:04 by author Jervis

Problem

As you begin developing reports for deployment to a Report Server, what security considerations need to be taken into account in order to grant users access to run a report.

Solution

Securing Reporting Services can be a daunting task for a rookie report developer. In this tip, we will focus on SQL Server Reporting Services 2012 (SSRS), although many of the items also apply to SSRS 2008 R2. Security consists of two main components: security and access at the Report Server level and authentication and permission at the data source level. Within this tip, we will cover Report Server Permissions first and then move on to database level security. Coverage of permission needed for a SSRS server in SharePoint integrated mode will be covered in a later tip.

SQL Report Server Permissions

Within the SSRS website, the first item to setup is to create system level permissions; these permissions are assigned to the main administrators of SSRS and the "power" users who publish reports. Similar to SSAS, SSRS uses a role concept. Two main roles, System Administrator and System User are predefined. Assignment to these roles is made by clicking on Site Setting in the upper right corner of the report server site;  next click on the Security link from the left menu.  Local and active directory groups and users can be assigned to either of these roles; however SQL Server logins cannot.

Clicking on the Edit option allows you to add, edit, or remove the roles assigned to the user or group as displayed in the below figure. Generally the System Administrator role is reserved for those who need to have full control over the Report Server whereas the System User role is applied to users / groups who are power users of the Report Server.

Moving beyond the system level roles, permissions must also be applied at the folder and report level on the Report Server. Similar to the System Assignments, a local or active directory user or group can be assigned to one or more roles. SSRS includes 5 predefined roles that should suffice in most circumstances. These roles include:

  • Browser-allows users to run reports and browse folders; this role will be used by most end users
  • Content Manager-allows users to manage and define folders and reports and to grant permissions
  • Report Builder-allows users to create Report Builder reports
  • Publisher-allows users to deploy / upload reports and create folders
  • My Reports-allows users to create and maintain personal MyReports folders

More details on each of these predefined roles can be found at: http://msdn.microsoft.com/en-us/library/ms157363.aspx.

In order to assign permissions to a report or folder, first select the desired report or folder and then click the down arrow on the right side of the report or folder name. Then select the security option from the left hand menu.

In the Group or User name textbox, enter the group or user name (prefixed with the appropriate domain if needed). Next, the appropriate role or roles must be selected and then last, click OK. As noted previously, most day to day users will only need the Browser role. Most high level power users will need to be assigned to either the Content Manager or Publisher role.

Some additional attention needs to directed to how permissions are inherited by subfolders and reports. First, the role assignments use a waterfall methodology. Thus, starting at the home page, all folders, subfolders, or reports underneath the home page in the hierarchy will have the same permission that are assigned to the home page UNLESS the permission chain is broken, either at the folder, subfolder, or report level. Clicking on the Edit Item Security button, as displayed below, will break the permission chain and allow for the customization of the security for that individual folder or report.

Selecting this option prompts the following warning to be displayed. After clicking OK, permissions must be maintained for that individual folder or report; changes to folders above this level including the home page are no longer utilized or considered.

Fortunately, if at some point you would like to go back to having your folder or report inherit its permission from a parent structure, you can click on the Revert to Parent Security button.

In addition to using the predefined roles in SSRS, customized roles can be created and used. Furthermore, the current set of the predefined roles can be altered; however, I highly recommend leaving the predefined roles as is, and create new roles with the appropriate permissions. Contrary to some older version of SSRS, in SSRS 2012, new roles and adjustments to existing roles must be performed in SQL Server Management studio, SSMS. After opening up SSMS, change the server type to Reporting Services, enter your Server Name, and login information and then click Connect. After connecting to the Report Server, open the Security Folder, as noted in the following screen print. Notice under the security tab, two Role Types Exist, one for the System Roles and one for the "regular user" Roles.

Right mouse clicking on Roles and Selecting New Role opens the New User Role window, which allows for the naming of the role and selection of particular tasks to assign to this new role.

Once created, these custom roles will now appear in the role assignment list as displayed in the below figure.

Once the SSRS report and folder level security has been planned and implemented, a second area of security must also be handled; as discussed next, this task centers around the security ramifications of the actual data itself and what access is granted to that data.

Database Level Security

For many DBA's and DWA's this second area of consideration is likely a more familiar topic. Specifically, for all data objects (ie tables, views, stored procedures) used in a particular report, the user running the report must have appropriate permissions to access the data and its related object (ie select permissions for tables and view and execute permissions for stored procedures). One decision that must be made early on in the report design process is whether the reporting user to be authenticated by SSRS will be a SQL Server Login or a Windows / Active Directory login. This decision is made in BIDS (Visual Studio 2010 using the Business Intelligence Development addin), specifically during the creation of the DataSource for the project, as noted in the below image.

The advantages of using Windows Authentication center around ease of maintenance and administration of the user whereas the use of the SQL Server login allows for the avoidance of the double hop issue ( see http://blogs.technet.com/b/rob/archive/2011/11/23/enabling-kerberos-authentication-for-reporting-services.aspx for details about the double hop issues).

Once the decision is made about which authentication method is used, the next step includes granting the appropriate privileges, whether to a windows user or group or a SQL Server login, for all objects involved in the dataset queries for the report. Of course these grants could include execute permissions on a stored procedure or select permissions for a group of tables and views.

Conclusion

Implementing SSRS Security requires a two step approach. Object permissions must be granted at the database level while SSRS folder and report level permissions requires that a user be assigned to one or more SSRS roles. Several predefined roles exist and will suffice for much of your permission needs. However, customized roles can also be generated.



About ASPHostPortal.com

We’re a company that works differently to most. Value is what we output and help our customers achieve, not how much money we put in the bank. It’s not because we are altruistic. It’s based on an even simpler principle. "Do good things, and good things will come to you".

Success for us is something that is continually experienced, not something that is reached. For us it is all about the experience – more than the journey. Life is a continual experience. We see the Internet as being an incredible amplifier to the experience of life for all of us. It can help humanity come together to explode in knowledge exploration and discussion. It is continual enlightenment of new ideas, experiences, and passions

 photo ahp banner aspnet-01_zps87l92lcl.png

Author Link

Corporate Address (Location)

ASPHostPortal
170 W 56th Street, Suite 121
New York, NY 10019
United States

Sign in