European Windows 2019 Hosting BLOG

BLOG about Windows 2019 Hosting and SQL 2019 Hosting - Dedicated to European Windows Hosting Customer

European ASP.NET MVC 4 Hosting - Amsterdam :: ASP.NET MVC 4 Mobile Tutorial - Part III

clock October 8, 2012 07:07 by author Scott

This final post will discuss the final piece; the UI and how it all comes together.

The User Interface

The default project uses the
jQuery mobile plugin to target mobile devices. The jQuery mobile plugin is touch-optimized for smartphones and tablets and it targets iOS, Android, Blackberry, Bada, Windows Phone, Palm WebOS, Symbian and MeeGo.

Lets start with the JavaScript logic, which will perform the interaction between the HTML UI and the JSON web service.


1. In the Scripts folder, add a folder called com then mobile underneath that and finally babyfeeding underneath that


2. In the final babyfeeding folder, add a JavaScript file and called it proxy.js


3. Copy and paste the following code into the js file


if
(mobile == undefined) var mobile;
if
(!mobile) mobile = {};

//Constructor

mobile.Proxy = function (siteBaseUrl) {

    // constructor
    mobile.Proxy.prototype.baseUrl = siteBaseUrl;
    mobile.Proxy.prototype.heartBeatUrl = siteBaseUrl + "/Services/BabyMonitorService.svc/HeartBeat";
    mobile.Proxy.prototype.FeeedingUrl = siteBaseUrl + "/Services/BabyMonitorService.svc/AddFeedingEntry"
    mobile.Proxy.prototype.DiaperingUrl = siteBaseUrl + "/Services/BabyMonitorService.svc/AddDiaperingEntry"
}


mobile.Proxy.prototype = {

    CallWebService: function (url, input, successCallBack, errorCallBack) {
        //Uncomment the next line to support JSONP
        //url = url + "?callback=?";      
        $.ajax({
            async: false,
            cache: false,
            type: "GET",
            contentType: "application/json; charset=utf-8",
            url: url,
            dataType: "json",
            data: input,
            success: successCallBack,
            error: errorCallBack
        });

    },

    HeartBeat: function (successFunction, failFunction) {
        this.CallWebService(this.heartBeatUrl, "", successFunction, failFunction);
    },
    AddFeeding: function (UserId, FeedType, FeedAmount, successFunction, failFunction) {
        var input = "UserId=" + UserId + "&FeedType=" + FeedType + "&FeedAmount=" + FeedAmount;
        this.CallWebService(this.FeeedingUrl, input, successFunction, failFunction);
    },
    AddDiapering: function (UserId, DiaperType, successFunction, failFunction) {
        var input = "UserId=" + UserId + "&DiaperType=" + DiaperType;
        this.CallWebService(this.DiaperingUrl, input, successFunction, failFunction);
    }
};


4. The JavaScript is structured using objects and namespaces. Every JavaScript object contains an inner class called Prototype. By defining methods on this inner class, we can encapsulate object variables and methods and share them across concrete instances of the class. In the code above, the Proxy object defines the following methods:


- CallWebService - helper method for invoking the JSON service

- HearBeat - invokes the Heat method call for diagnostics
- AddFeeding - creates a feed entry by taking input from the form and invoking the web service
- AddDiapering - creates an entry for a diaper change by taking input from the form and invoking the web service

Finally, we encapsulate the Proxy object inside the mobile object to create a namespace so that the proxy object can be referenced like so: mobile.Proxy


The Index.cshtml View

Copy and paste the following code for the Index page


@{
    ViewBag.Title = "Baby Log Home";
}

<script type="text/javascript">
    $(document).ready(function () {
        $("#btnSubmit").click(function () {

            $("#txtLastEntry").val("Last: ");

            // Create the proxt class
            var proxy = new mobile.Proxy("@Request.Url.GetLeftPart(UriPartial.Authority)");
            // Add the feeding entry
            if ($("#chkFeed").attr("checked") != undefined && $("#chkFeed").attr("checked") == "checked") {
                proxy.AddFeeding("@Membership.GetUser().UserName", $("#drpType").val(), $("#drpAmount").val(),
                    function (result) {
                        // succeeded
                        $("#txtLastEntry").val($("#txtLastEntry").val() + $("#drpAmount option:selected").text() +
                        " of " + $("#drpType option:selected").text());
                    },
                    function (jqXHR, textStatus, errorThrown) {
                        // failed
                        var err = "Details: " + textStatus;
                        if (errorThrown != undefined) {
                            err += "\rMore details : " + errorThrown;
                        }
                        alert(err);
                    });
            }
            // Add the diapering entry
            if ($("#chkDiaper").attr("checked") != undefined && $("#chkDiaper").attr("checked") == "checked") {
                proxy.AddDiapering("@Membership.GetUser().UserName",
$("#drpDiaper").val(),

                    function (result) {
                        // succeeded
                        $("#txtLastEntry").val($("#txtLastEntry").val() + ", " +
                        $("#drpDiaper option:selected").text() + " diaper");
                    },
                    function (jqXHR, textStatus, errorThrown) {
                        // failed
                        var err = "Details: " + textStatus;
                        if (errorThrown != undefined) {
                            err += "\rMore details : " + errorThrown;
                        }
                        alert(err);
                    });
            }
        });
    });
</script>
<div data-role="fieldcontain" data-inset="true">
    <fieldset data-role="controlgroup">
        <legend>Feed Details</legend>
        <input id='chkFeed' name='chkFeed-1' type="checkbox" checked="checked" class="custom" />
        <label for="chkFeed">

            Log Feed</label>
    </fieldset>
    <fieldset data-role="controlgroup">
        <legend>Feed Type:</legend>
        @Html.DropDownList("drpType", new List<SelectListItem> {
            new SelectListItem { Text="Bottle", Value="Bottle", Selected=true },
            new SelectListItem { Text="Left", Value="Left" },
            new SelectListItem { Text="Right", Value="Right" },
        })
    </fieldset>
    <fieldset data-role="controlgroup">
        <legend>Amount:</legend>
        @Html.DropDownList("drpAmount", new List<SelectListItem> {
            new SelectListItem { Text="0.5 oz.", Value="0_5" },
            new SelectListItem { Text="1.0 oz.", Value="1_0" },
            new SelectListItem { Text="1.5 oz.", Value="1_5" },
            new SelectListItem { Text="2.0 oz.", Value="2_0" },
            new SelectListItem { Text="2.5 oz.", Value="2_5", Selected=true },
            new SelectListItem { Text="3.0 oz.", Value="3_0" },
            new SelectListItem { Text="3.5 oz.", Value="3_5" },
            new SelectListItem { Text="4.0 oz.", Value="4_0" },
            new SelectListItem { Text="4.5 oz.", Value="4_5" },
            new SelectListItem { Text="5.0 oz.", Value="5_0" },
            new SelectListItem { Text="5.5 oz.", Value="5_5" },
            new SelectListItem { Text="6.0 oz.", Value="6_0" },
            new SelectListItem { Text="6.5 oz.", Value="6_5" },
            new SelectListItem { Text="7.0 oz.", Value="7_0" },
            new SelectListItem { Text="7.5 oz.", Value="7_5" },
            new SelectListItem { Text="8.0 oz.", Value="8_0" },
            new SelectListItem { Text="8.5 oz.", Value="8_5" },
            new SelectListItem { Text="9.0 oz.", Value="9_0" }
        })
    </fieldset>
</div>
<div data-role="fieldcontain" data-inset="true">
    <fieldset data-role="controlgroup">
        <legend>Diaper Details</legend>
        <input id='chkDiaper' name='chkDiaper-1' type="checkbox" class="custom" />
        <label for="chkDiaper">
            Log Diaper</label>
    </fieldset>
    <fieldset data-role="controlgroup">
        <legend>Diaper:</legend>
        @Html.DropDownList("drpDiaper", new List<SelectListItem> {
            new SelectListItem { Text="Wet", Value="wet", Selected=true },
            new SelectListItem { Text="Dirty", Value="dirty" },
            new SelectListItem { Text="Both", Value="both" }
        })
    </fieldset>
</div>
<div data-role="fieldcontain" data-inset="true">
    <input id="btnSubmit" type="submit" value="Submit" data-role="button" />
    <fieldset data-role="controlgroup">
        <input id="txtLastEntry" readonly="readonly" type="text" />
    </fieldset>
</div>


The HTML code builds the input form for entering the feed and diaper change details and the Javascript code collects the input, creates the proxy class and calls its methods to invoke the web service.

Notice how the @ tag is used to inject runtime variables, such as the logged on user and the base url.



 



European ASP.NET MVC 4 Hosting - Amsterdam :: ASP.NET MVC 4 Mobile Tutorial - Part II

clock October 5, 2012 08:13 by author Scott

In the last post, we covered the database design and the Entity model for the sample ASP.Net MVC4 Mobile application. We will continue with the Service layer in this post.

The Service Layer

We will define some methods in our service class to enter data into our SQL log tables.


-
Right-click the project, select Add->New Folder and call it Services
-
Right-click the Services folder, select Add, New Item and click on WCF service. Name the service



- Update the system.serviceModel section in the web.config file so that it looks like the following


<
system.serviceModel>
    <bindings>
      <webHttpBinding>
        <binding name="customWebHttpBinding">
          <security mode="None"></security>
        </binding>
      </webHttpBinding>
    </bindings>
    <behaviors>
      <endpointBehaviors>
        <behavior name="JSLearning.Services.BabyMonitorServiceBehavior">
          <enableWebScript />
        </behavior>
      </endpointBehaviors>
      <serviceBehaviors>
        <behavior name="DebugBehavior">
          <serviceMetadata httpGetEnabled="true" />
          <serviceDebug includeExceptionDetailInFaults="true" />
        </behavior>
      </serviceBehaviors>
    </behaviors>
    <services>
      <service name="JSLearning.Services.BabyMonitorService" behaviorConfiguration="DebugBehavior">
        <endpoint address="" behaviorConfiguration="JSLearning.Services.BabyMonitorServiceBehavior" binding="webHttpBinding" contract="JSLearning.Services.IBabyMonitorService" bindingConfiguration="customWebHttpBinding" />
        <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
      </service>
    </services>
    <serviceHostingEnvironment multipleSiteBindingsEnabled="true" />
  </system.serviceModel
>

- In the Services folder, add a ServiceBase class and then copy and paste the following code to it. The ServiceBase class provides useful methods for interacting with the data Entity Model

public
class ServiceBase
    {
        private BabyLogEntities _context = null;
        private string _connectionString = string.Empty;

        protected ServiceBase()
        {
            RenewContext();
        }

         protected ServiceBase(string connectionString) {
             _connectionString = connectionString;
             _context = new BabyLogEntities(_connectionString);
        }

        protected BabyLogEntities Context

        {
            get
            {
                return _context;
            }
        }

        protected void RenewContext()
        {
             if (_connectionString == string.Empty)
             {
                 _connectionString = System.Configuration.ConfigurationManager.ConnectionStrings["BabyLogEntities"].ConnectionString;
             }
             _context = new BabyLogEntities(_connectionString);
            return;
        }

    }

- Edit the BabyMonitorService.svc.cs file and have it inherit from ServiceBase.cs

public class BabyMonitorService : ServiceBase, IBabyMonitorService

- Copy and paste the following into your IBabyMonitorService.cs interface


[ServiceContract]

    public interface IBabyMonitorService
    {
        [OperationContract]
        [WebMethod]
        [WebInvoke(Method = "GET", ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.WrappedRequest)]
        string HeartBeat();

        [OperationContract]
        [WebMethod]
        [WebInvoke(Method = "GET", ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.WrappedRequest)]
        string AddFeedingEntry(string UserId, string FeedType, string FeedAmount);

        [OperationContract]
        [WebMethod]
        [WebInvoke(Method = "GET", ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.WrappedRequest)]
        string AddDiaperingEntry(string UserId, string DiaperType);
    }

- Here is an explanation of the public methods:

1. HeartBeat - is a simple contract to verify that the service is responding

2. AddFeedingEntry - is used to make an entry for a feeding session
3. AddDiaperingEntry - is used to make an entry for a diaper change

- Open the BabyMonitorService.svc.cs file and add the following code:


public class BabyMonitorService : ServiceBase, IBabyMonitorService
    {
        public BabyMonitorService() : base()
        { }

        /// <summary>
        /// Check that the service is available
        /// </summary>
        /// <returns></returns>
        public string HeartBeat()
        {
            return "Service is alive";
        }

        /// <summary>
        /// Add a feed entry
        /// </summary>
        /// <param name="UserId"></param>
        /// <param name="FeedType"></param>
        /// <param name="FeedAmount"></param>
        /// <returns></returns>
        public string AddFeedingEntry(string UserId, string FeedType, string FeedAmount)
        {
            Models.WebServiceResponse response = new Models.WebServiceResponse();
            try
            {
                var log = new FeedingLog
                {
                    ID = Guid.NewGuid(),
                    DateCreated = DateTime.Now,
                    FeedType = FeedType,
                    // since IIS does not like the . character, we are passing decimals as x_y and converting to x.y
                    FeedAmount = Decimal.Parse(FeedAmount.Replace("_", ".")),
                    UserID = UserId
                };

                RenewContext();
                Context.AddToFeedingLogs(log);
                Context.SaveChanges();

                response.IsSuccess = true;
            }
            catch (Exception ex)
            {
                response.IsSuccess = false;
                response.ErrorMessage = ex.Message;
            }
            return SerializeAsJSON(response);
        }

        /// <summary>
        /// Add an entry for a diaper change
        /// </summary>
        /// <param name="UserId"></param>
        /// <param name="DiaperType"></param>
        /// <returns></returns>
        public string AddDiaperingEntry(string UserId, string DiaperType)
        {
            Models.WebServiceResponse response = new
Models.WebServiceResponse();

            try
            {
                var log = new DiaperLog
                {
                    ID = Guid.NewGuid(),
                    DateCreated = DateTime.Now,
                    DiaperType = DiaperType,
                    UserID = UserId
                };

                RenewContext();
                Context.AddToDiaperLogs(log);
                Context.SaveChanges();

                response.IsSuccess = true;
            }
            catch (Exception ex)
            {
                response.IsSuccess = false;
                response.ErrorMessage = ex.Message;
            }
            return SerializeAsJSON(response);
        }

        /// <summary>
        /// Serializes an object to JSON
        /// </summary>
        /// <param name="response"></param>
        /// <returns></returns>
        private string SerializeAsJSON(Models.WebServiceResponse response)
        {
            using (MemoryStream s = new MemoryStream())
            {
                DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(Models.WebServiceResponse));
                ser.WriteObject(s, response);
                s.Position = 0;
                using (StreamReader sr = new StreamReader(s))
                {
                    return sr.ReadToEnd();
                }
            }
        }
    }

- The code is quite simple, it uses the Entity Model to make an entry into the respective tables and returns the WebServiceResponse object in JSON format.
- In the Models folder, add a class called WebServiceResponse and add the following code. The WebServiceResponse is a nice way to return an object as the JSON response, and it can contain a lot of details from the service rather than a simple string error message. Check the service class to see how this object is built.

[DataContract]

    public class WebServiceResponse
    {
        /// <summary>
        /// Indicates if the web service call was successful
        /// </summary>
        [DataMember]
        public bool IsSuccess = false;
        /// <summary>
        /// Contains the response message from the service
        /// </summary>
        [DataMember]
        public object Payload = "Object not assigned";
        /// <summary>
        /// Contains a friendly error message if the service encountered an exception
        /// </summary>
        [DataMember]
        public string FriendlyErrorMessage = string.Empty;
        /// <summary>
        /// Contains the full text of the exception, if one occurred
        /// </summary>
        [DataMember]
        public string ErrorMessage = string.Empty;
        /// <summary>
        /// Contains the exception trace, if one occurred
        /// </summary>
        [DataMember]
        public string ErrorStackTrace = string.Empty;
        /// <summary>
        /// Contains the date and time of the service response in UTC format.
        /// </summary>
        [DataMember]
        public string UTC_DateOfResponse = DateTime.Now.ToUniversalTime().ToString("dd MMM yyyy hh:mm:ss tt");
    }


- At this point we should be able to compile the project and browse to the service. Go to http://yoursite/Services/BabyMonitorService.svc

- You can also invoke the HeartBeat method from earlier to see if your service is working correctly. Note, you will need to save the JSON response and then open it in notepad to see the results

 



European ASP.NET MVC 4 Hosting - Amsterdam :: ASP.Net MVC4 Mobile Tutorial - Part I

clock October 4, 2012 06:27 by author Scott

In this posting I will show you how to build a new mobile web application based on my real world experience of tracking the feeding activities of my 4 month old baby.

The Design

We have a 4 month old baby and wanted to keep track of his feeding sessions so we do not wake each other up, especially late at night and to also make sure that the baby was feeding regularly. I have an iPhone, my wife has a HTC phone and we also own a Windows table (running Windows 8 Developer Preview), 2 laptops and a home server/multimedia system. I wanted to write an app for this, but it would be too difficult writing an maintaining an iPhone app, a Metro app and windows applications separately. That's why I decided to write a single web application leveraging the SQL Azure database.


Getting Started

You will need one of the following emulators to test the code:

-
Windows Phone Emulator (RC)
-
Opera Mobile Emulator
-
Apple Safari with the user agent set to iPhone. Click here for instructions.
-
FireFox with FireFox User Agent Switcher

Building the Solution

1. Install ASP.Net MVC 4 from here

2. Start Visual Studio 2010, choose new Project, then choose Web and select the "ASP.Net MVC 4 Web Application"



3. In the project template box, choose "Mobile Application", leave the View engine as Razor and leave the checkbox for HTML5 semantic markup




4. You will get a default mobile app with forms authentication ready to go


The Database

We will need to create a database and the schema for this demo next.


-
On your local instance, create a SQL Server 2008 R2 (SQL 2005+ will do) database and call it BabyLog

- We need two tables in the database for our application, one to hold records for feeding logs and the other for diaper changes. Run the following SQL to create those


CREATE TABLE [dbo].[FeedingLog](
    [ID] [uniqueidentifier] NOT NULL CONSTRAINT [DF_Log_ID]  DEFAULT (newid()),
    [UserID] [varchar](255) NOT NULL,
    [FeedType] [varchar](255) NOT NULL,
    [FeedAmount] [decimal](18, 1) NOT NULL,
    [DateCreated] [datetime] NOT NULL,
 CONSTRAINT [PK_Log] PRIMARY KEY CLUSTERED
(
    [ID] ASC
)WITH (STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF)
)
GO


CREATE
TABLE [dbo].[DiaperLog](
    [ID] [uniqueidentifier] NOT NULL CONSTRAINT [DF_DiaperLog_ID]  DEFAULT (newid()),
    [UserID] [varchar](255) NOT NULL,
    [DiaperType] [varchar](255) NOT NULL,
    [DateCreated] [datetime] NOT NULL,
 CONSTRAINT [PK_DiaperLog] PRIMARY KEY CLUSTERED
(
    [ID] ASC
)WITH (STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF)
)
GO


- Next we need to create tables to support Forms authentication. Open the Visual Studio command prompt and type: aspnet_regsql




- Click next, select "Configure SQL Server for application services", provider the server name, credentials and the database name and click next.


- Once the wizard finishes, you will see your database tables




The Database Model

Next we will create the Entity Model for our database as well as the WCF uses that our website will use to enter data into the database.


- In the ASP.Net MVC project, right-click on the Models folder and select "Add New Item"


- Select the Data template and choose "ADO.Net Entity Data Model




- Select "Generate from Database", then click Next


- Supply the connection details for your database and name your connection string


- Select the FeedingLog and DiaperLog tables and leave the Model namespace as BabyLogModel




- You should now have a model with the required tables


 



HostForLIFE.eu now supports Windows Server 2012 Hosting Platform in European Data Center

clock October 1, 2012 07:58 by author Scott

Microsoft has just officially released the highly anticipated Windows Server 2012. The newly released server operating system offers a number of features that can be utilized to benefit developers, resellers and businesses. As a premier European Windows and ASP.NET hosting provider that follow the developments of Microsoft products, HostForLIFE.eu proudly announces the support of Windows Server 2012 Hosting Platform in the world-class Amsterdam (The Netherlands) data center.

“We know that our customers are always looking for new technologies and the latest Microsoft product. With the launch of Windows Server 2012, we believe that anyone can take advantage of all the improvements available in this platform”, said Manager of HostForLIFE.eu, Kevin Joseph. “The focus on high availability, scalability, and virtualization has made this one of the most important releases of Windows Server to date. We have been working closely with Microsoft throughout the pre-release development cycle of the platform to both drive the direction of the product and ensure our team is ready to support Server 2012 solutions. We couldn’t be more excited and confident in the solutions now available to our clients with Windows Server 2012.”


With our Windows Server 2012 Hosting Platform, customers have an access directly to all the newest technologies and frameworks, such as ASP.NET 4.5 Hosting, ASP.NET MVC 4 Hosting, Silverlight 5 Hosting, WebMatrix Hosting, Visual Studio Lightswitch Hosting and SQL 2012 Hosting. All these technologies/frameworks are integrated properly on our world-class Control Panel. The package is offered from just €2.45/month and we believe that this is the most affordable, features-rich Windows and ASP.NET Hosting package in European market.


HostForLIFE.eu is awarded Top No#1 SPOTLIGHT Recommended Hosting Partner by Microsoft (see
http://www.microsoft.com/web/hosting/HostingProvider/Details/953). Our service is ranked the highest top #1 spot in several European countries, such as: Germany, Italy, Netherlands, France, Belgium, United Kingdom, Sweden, Finland, Switzerland and other European countries. Besides this award, we have also won several awards from reputable organizations in the hosting industry and the detail can be found on our official website.

For more information about our service, please visit
http://www.hostforlife.eu.

About HostForLIFE.eu:


HostForLIFE.eu is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes.


Our number one goal is constant uptime. Our data center uses cutting edge technology, processes, and equipment. We have one of the best up time reputations in the industry.


Our second goal is providing excellent customer service. Our technical management structure is headed by professionals who have been in the industry since its inception. We have customers from around the globe, spread across every continent. We serve the hosting needs of the business and professional, government and nonprofit, entertainment and personal use market segments.

 



European Visual Studio 2012 Hosting - Amsterdam :: Visual Studio 2012 is More Friendly with Javascript and CSS

clock September 27, 2012 07:26 by author Scott

Visual Studio over the years has provided very good support for the core application development languages like C#, VB, etc. But when it comes to web development languages like javascript and CSS, Visual Studio lacked some main support such as intellisense, debugging, etc. This article discusses some key features introduced in Visual Studio 11 with respect to Javascript and CSS.

Javascript


In this section we will look at some important and useful features that the Visual Studio 11 JavaScript editor provides.


Intellisense, Type Inference & Documentation

Prior versions of Visual Studio were a pain for Javascript developers due to the lack of intellisense for Javascript. The intellisense provided was very basic; developers had to be very sure of the method and class names, including the casing. Now Visual Studio 11 provides complete intellisense support for all the javascript objects and its methods. Fig below is a sample intellisense menu and you can see the number of options.




Visual Studio 11 also provides rich intellisense support for popular third party Javascript libraries like JQuery. Since Jquery is used by almost all web developers this will be of tremendous help to them. Fig below shows a sample intellisense available for JQuery in the Visual Studio 11 IDE.




In the above screenshot you would have noticed documentation for the method in the intellisense window like C# code. You could provide the documentation for your Javascript method as shown in the below example.


<
script type="text/javascript">
        function DoSummation(a, b) {
            ///      <summary>
            ///            Returns the sum of the variables a and b
            ///      </summary>
            ///      <param name="a" type="int">Integer variable 1</param>
            /// <param name="b" type="int">Integer variable 2</param>
            return a + b;
        }
</script
>

The Javascript editor also performs type inference, for example if a Javascript variable is assigned with a string value and later when the variable is used then the intellisense displays only the string related methods.

Curly Brace and Bracket Matching

When I use to write a large amount of Javascript code, especially with object oriented Javascript or jQuery, I used to get confused with the brackets and curly braces on their scopes. It may sometimes be a nightmare for developers to fix a brace mismatch on a huge Javascript code file. Fig below shows how the bracket scopes are highlighted by Visual Studio 11.



Go to Definition Feature

Like the C# Visual Studio editor of Visual Studio, now the Javascript editor also provides the Go to definition feature, which will be very useful in going through the code flow or to debug a Javascript issue especially when there are a lot of files involved and the method calls are scattered. In order to make this feature work you need to add the reference path of the .js file containing the method implementation onto the caller .js file. Below is a sample.


/// <reference path="File1HavingImplementation.js" />


A generic approach to provide the reference path is to add them to the _references.js file.


Debugging

There is a new window added to Visual Studio 11 called the Javascript Console, which provides various features in terms of debuggingJjavascript code. I will cover this topic in a separate article.


CSS

In this article we will take a look at two important features on the CSS front.

Code Snippets and Writing Vendor Specific CSS

One of the most repetitive and boring tasks for the UI developer is to write the vendor specific styles in a CSS file. Vendor specific CSS is nothing but writing the same style with different names as supported by different browsers in order to get the style working on multiple browser combinations. Now Visual Studio 11 provides CSS code snippets, for example type transform and hitting tab would create the different vendor specific properties for transform in a CSS class. Below is the generated CSS class.

.MyClass
{
       -ms-transform: rotate(-90deg);
       -moz-transform: rotate(-90deg);
       -o-transform: rotate(-90deg);
       -webkit-transform: rotate(-90deg);
       transform: rotate(-90deg);
}


Color Picker

One thing that bothered me while writing CSS classes is providing the color code. I had to use some external utility to figure out the color code of the color being used, which I was trying to create a style for. Now with Visual Studio 11 the UI designer doesn’t have to move away from the CSS editor to pick the color, the editor itself has the color picker integrated. Fig below shows the screenshot of the color picker on a CSS file.



I hope these features have simplified and provided solutions for some long lasting issues faced by web developers.


Happy reading!

 



European SQL 2012 Hosting - Amsterdam :: Data Alerting in SQL Server 2012

clock September 18, 2012 08:43 by author Scott

You can create a data alert to email notification in SQL Server 2012 reporting services. This data alert sends e-mail notification when only when specific conditions in the data are true at a schedule time. This Date Alerting feature is available only when reporting services runs in sharepoint integration mode. It works only with reports that are designed using Report Designer or Report Builder. You can not create alert for Power View reports.

Data Alerts Designer

You can create one or more data alerts for any report provided report must return the data at the time you create the data alert.


Steps to create a Data Alert

Open the report that you want to add the data alert, Select new Data Alert from the actions menu in reports toolbar



Note
: You must have a permission in sharepoint to create an alert.

Using Data Alert designer you can define rules for one or more data regions in the report that control reporting services send an alert. When you save the alerting definitions, reporting services saves it in the alerting database and schedules a corresponding SQL Server Agent Job.




You can create one or more rules that compares a field value to value that you enter, Data Alert designer combines multiple rules for the same data feed by using logical AND operator.


In schedule section of the Data Alert designer , you can configure the daily, weekly intervals at which to run the SQL Server Agent job for the data alert.




Final, you must specify email address as a recipient for the data alert. Reporting services alert service manages the process of refreshing data feed and applying the rules in the data alert definition. Alerting service adds an alerting instance to the alerting database.




The email for successful data alert shows the user name of the person who created the alert and description of the data from the alert and rows from the data feed that generated the data alert. The Sample alert shown as below




If an error occurs during the alert processing then it sends an alert message to recipient describing the error message.


Data Alert Manager

Data Alert Manager lists all data alerts that you created for the report as shown below. To open the Data Alert Manager , Open the document library which has the report then click the down arrow and select Manage Data Alerts.


 



European Windows 2012 Hosting - Amsterdam :: New features in Windows 2012

clock September 11, 2012 10:22 by author Scott

With Windows Server 2012 (formerly “Windows Server 8”) on the horizon and many IT shops mulling upgrades, it’s more likely upgrades to Server 2012 will be incremental rather than all-at-once. It’s likely that those with infrastructure built on top of Windows Server will have both Server 2012 and older versions of Server running side-by-side for some time.

Given that, here are a few answers to common questions in this area how the new and older versions of Windows Server might have coexistence issues.


Can I run Windows Server 2012 systems in a cluster with earlier versions of Windows Server?

The small answer is “no.” There are several reasons for this, not least of which are the major improvements in the way clustering is managed and deployed across servers in Windows Server 2012. The new clustering features aren’t backward-compatible with earlier versions of Windows Server, so clusters can’t be upgraded in a “rolling” fashion; each node in a cluster has to be evicted from the cluster, upgraded to Windows Server 2012 and added to a total new cluster of 2012-only servers.

Here are some of the key new clustering features in Windows Server 2012, which will not be supported by earlier versions of the operating system:

Storage migration
. This allows cluster-managed VMs to be live-migrated to a new place while the VM is up and running, in much the same manner as VMware’s vMotion.

Clustered shared volumes
. This feature is not new to Server 2012 — it was introduced in Windows Server 2008 R2 — but it’s been revised and expanded, and the expanded functionality is not available for previous versions of Server. Multiple nodes in the same cluster can share the same file system, which allows a VM hosted on any node in that cluster to be migrated to any other node on that cluster.

Cluster-aware updating (CAU)
. Updates to machines in a Windows Server 2012 cluster can be applied automatically in a rolling fashion. This way, the total cluster remains online during the process. Plugins that talk to an API expand CAU’s behavior.

There are many other new features, but to use them uniformly across a cluster requires a cluster-wide upgrade to Windows Server 2012.


What do I need to know in this area using file shares between Windows Server 2012 and earlier versions of Windows Server?

Windows Server 2012 uses the new SMB 3.0 protocol (originally SMB 2.2) for establishing file shares between Windows systems.


SMB 3.0 clients will always attempt to negotiate the highest possible level of the protocol with any peer it connects with, so if you establish a share between Windows Server 2012 and earlier versions of Windows Server, the connection will be negotiated according to whatever level of SMB is available on the other server. Microsoft TechNet blogger Jose Barreto has a post with a chart that spells out the highest grade of SMB available to a connection negotiated between any two editions of Windows.

SMB 3.0′s new features are only available to other Windows Server 2012 or Windows 8 systems. Some of the new features include:

Scale-out
. The same folder can be shared from multiple nodes in a cluster for the sake of failover, surpass use of bandwidth, dynamic capacity scaling, load balancing and fault tolerance.

Multichannel help
. Any multiple, redundant network associations between SMB peers can be used to accelerate the connection.

End-to-end encryption
. Data sent between SMB 3.0 peers is encrypted by default.

VSS help
. SMB shares are now covered by volume shadow copies as well, so data on file shares can also be backed up and restored owing to any VSS-aware software.

SMB Direct
. Servers that use RDMA-capable network adapters can delight in high-speed memory-to-memory data transfers with far less CPU usage and latency than conventional copy operations.

SMB index leasing
. This feature reduces latency for documents accessed via the Branch Cache feature, by locally caching more of the metadata associated with the document and reducing the amount of roundtrips to the original server.

Note that if you have a mixed infrastructure where all the clients and servers use SMB 2 or surpass — Windows Vista on the client side, Windows Server 2008 on the server side — disable the use of SMB 1.x with the PowerShell command Set-SmbServerConfiguration –EnableSMB1Protocol $fake. Disabling SMB 1.x reduces the potential attack surface for the server. If the protocol isn’t in use, it’s best to disable it to preclude a possible future exploit from being used on it.

What Windows Server features are being deprecated in Windows Server 2012?

Some features in Windows Server are no longer supported as of Windows Server 2012, or are in the process of being removed. Most of these deprecations only occupy code or applications that run directly on the new OS, rather than interoperations with other editions. That said, there are exceptions especially if, for instance, you have an older application that expects the same behavior when it tries to interoperate with the newer version of Server.

Here’s a list of some of the major deprecations and feature removals in Windows Server 2012 (with more listed at TechNet), which may impact cross-server compatibility or applications running on other servers:

Clustering
. 32-bit cluster resource DLLs are being deprecated and must be replaced with their 64-bit counterparts whenever possible. Also, if you have any programs that use the Cluster Automation Server (MSClus) COM API, be aware that this API is now only available via an optional component named FailoverCluster-AutomationServer, which isn’t installed by default.

Databases
. 16- and 32-bit ODBC help has been removed, as have ODBC and OLEDB drivers for Oracle and Jet Red databases. (Use vendor-supplied database connectors.) ODBC/OLEDB help is also being canned for any versions of SQL Server beyond 2000; for those editions of SQL Server and higher, use SQL Native Client instead. Finally, no version of SQL Server earlier than 7.0 is supported at all. It’s unlikely that anyone is still running SQL Server 6.5 or earlier, but any attempts to connect to a SQL Server 6.5 (or earlier) instance from Windows Server 2012 will breed an error.

Committed Index
. Help for resource groups and using Committed Index Lightweight Index Services as an certification store have been deprecated.

UNIX
. Many UNIX subsystem features are being deprecated or removed. Microsoft entire SUA POSIX subsystem is being deprecated, along with the line printer daemon protocol that is often used by UNIX clients. As a general replacement for Microsoft’s UNIX features consider using the Cygwin or MinGW, open source tools and APIs that are maintained entirely apart from Windows’s own evolution.

WMI
. Many individual WMI providers are being removed or deprecated: SNMP (because SNMP itself is deprecated); the WMI provider for Committed Index (eclipsed by PowerShell), and the Win32_ServerFeature API.

Finally, the Windows Help application (winhlp32.exe) has also been removed although it has not shipped with Windows Server since Windows Server 2008. What’s more, no add-on version of the Windows Help program is being supplied owing to Microsoft as a download, as it did with previous versions of Windows that mislaid Windows Help. (Even if, a Windows Help journal for the client journal of Windows 8 will be made available later, which must do the job.)

 



European SSRS Hosting - Amsterdam :: Add a Clear button to SQL Server Reporting Services (SSRS)

clock September 10, 2012 07:35 by author Scott

If you ever had the need to add a clear / reset button to your standard SQL Server Reporting Services report viewer, here’s a way to do it. Normally when reports are displayed, they are piped through the ReportViewer.aspx page that comes with SSRS. This page hosts the Reporting Server host component, and adds text boxes, radio buttton etc. based on the number of parameters you have in your report.

Something like this:




You can’t simply replace this file with your own custom page, because SSRS has HTTP handlers installed that prevents any other file to be rendered except the ReportViewer.aspx page.


So how to add a clear button to clear the text boxes? One way to do it is to modify the OOB ReportViewer.aspx page by injecting some javascript that does this for us. Initially I wanted to use jQuery, but again, the HTTP handler prohibits us from accessing the external .js file. Back to plain old Javascript it is.


Essentially, we just need to find the container that holds the View Report button, and add our custom button.


In the body tag, add a page onload event handler:


<body style="margin: 0px; overflow: auto" onload="addClearButton();">


and then add some javascript code:

<script type="text/javascript">

document.getElementsByClassName = function(cl) {

    var retnode = [];
    var myclass = new RegExp('\\b'+cl+'\\b');
    var elem = this.getElementsByTagName('*');
    for (var i = 0; i < elem.length; i++) {
        var classes = elem[i].className;
        if (myclass.test(classes)) retnode.push(elem[i]);
    }
    return retnode;
};


function addClearButton(){

    var inputs = document.getElementsByClassName('SubmitButtonCell');

    // can't find the cell, return
    if (inputs.length<1)
        return;   

    // create a button
    var clearButton = document.createElement("input");
    clearButton.type = "button";
    clearButton.value = "Clear";
    clearButton.name = "btnClear";
    clearButton.style.width = "100%";

    // add clear text boxes functionality to the onclick event
    clearButton.onclick = function (){
        var textBoxes = document.getElementsByTagName("input");
        for (var i=0;i<textBoxes.length;i++){
        if (textBoxes[i].getAttribute("type")=="text"){
          textBoxes[i].value ="";
          }
        }
    };

    // find the relevant cells
    var tdSubmitButtonCell = inputs[0];

    // find the child table
    var table = tdSubmitButtonCell.childNodes[0];
    var lastRow = table.rows.length;
    var row = table.insertRow(lastRow);
    var cellLeft = row.insertCell(0);

    // add the clear button
    cellLeft.appendChild(clearButton);
  } 

</script>

The final result will look something like this:


 



European SQL 2012 Hosting - Amsterdam :: Enabling Contained Databases in SQL Server 2012

clock September 8, 2012 05:48 by author Scott

Authentication mechanism to login to SQL Server database engine is either Windows authentication or SQL Server account. Sometimes you will face authentication issues with database portability, example when you migrate a database from one SQL Server instance to another SQL Server instance, DBA has to ensure that all logins in Source SQL Server instance is existed on the target SQL Server instance. Organisations often experience these problems during failover when using database mirroring.

SQL Server 2012
addresses these authentication and login dependency challenges by introducing Contained Database authentication to enhance authorization and portability of user databases.

What is Contained Database Authentication?

Contained Database Authentication allows users to be authenticate directly into a user database without logins that reside in database engine. It allows authentication without logins for both SQL users with passwords and windows authentication without login. It is a great feature when you want to implement AlwaysOn Availability Groups.


Enabling Contained Databases

Contained Databases is a property which you can enable or disable via the Advanced Properties page in SQL Server Management Studio or with T-SQL

Enable Contained Database Authentication using SQL server Management Studio

1. In Object explorer, right-click a SQL Server instance, and then click properties

2. Select the Advanced page, and in the Containment section , set the property Contained Database to true and then click OK.



Enable Contained Database Authentication using T-SQL

   1: sp_configure 'show advanced options' 1,
   2: Go
   3: sp_configure 'Contained database authentication', 1;
   4: Go
   5: RECONFIGURE;
   6: GO


Creating Users

If user does not have a login in master database, the connection string must include the contained database as initial catalog. The below T-SQL can be used to create a contained database user with a password.

   1: CREATE User KennyB
   2: WITH PASSWORD = '2e4ZK933'
   3: ,DEFAULT_LANGUAGE = [ENGLISH]
   4: ,DEFAULT_SCHEMA = [dbo]
   5: GO


To migrate the SQL Server authentication login to contained database user with a password then you can use below T-SQL

   1: sp_migrate_user_to_contained
   2: @username = N '<User Name>',
   3: @rename = N 'keep_name',
   4: @disablelogin = N 'do_not_disable_login';
   5: GO


Contained Database Authentication Security Concerns

Without knowledge of DBA, user can create and grant database users in contained database if user has ALTER ANY USER permission.If user gains the access to a database via contained database authentication then user has potential to access other databases within the database engine if these databases has the guest account enabled.

 



European Visual Studio LightSwitch Hosting - Amsterdam :: Deploy LightSwitch Application as DotNetNuke Module

clock September 4, 2012 07:28 by author Scott

Visual Studio LightSwitch is a Microsoft tool used for building business applications. If you want your LightSwitch application to be deployed as a DotNetNuke then you can.

DotNetNuke is the leading Web Content Management Platform for Microsoft .NET, powering more than 700,000 web sites worldwide. Whether you need a content management system (CMS) for your personal web site or for a Fortune 500 company, DotNetNuke has a solution that fits your needs. For details of DotNetNuke, please visit this link:
http://www.dotnetnuke.com/

Before deploying yourLightSwitch applications inDotNetNuke you will need at least DotNetNuke 5 (using ASP.NET 4.0). Or you can use the newest DotNetNuke 6.


1. Open Visual Studio LightSwitch->Create new table.


2. Create a table such as Task.




3. Then, right click on Screen
à Add Screen.



4. Select list and details screen->Select screen data (Task)->Ok.




5. Click on write code
à Select Task_Created.



Code

using System;

 using System.Collections.Generic;using System.Linq;
 using System.Text;
 using Microsoft.LightSwitch;
 namespace LightSwitchApplication
 {
     public partial class Task
     {
         partial void Task_Created()
         {
             this.UserName = this.Application.User.Name;
         }
     }
 }


Description
: This code set the Username field to the "Application.User.Name".

6. Go to properties in the Solution Explorer.



7. Click on access control-> select Use Forms authentication




8. Click on application type-> select Host application services on IIS




9. Go to configuration manager in debug.




10. Select release mode in debug.




11. Go to build in menu bar->Publish your application (DotNetNuke).




12. Click on publish for publish your application.




13. Run your application (Press F5).

 



About HostForLIFE

HostForLIFE is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes.

We have offered the latest Windows 2019 Hosting, ASP.NET 5 Hosting, ASP.NET MVC 6 Hosting and SQL 2019 Hosting.


Month List

Tag cloud

Sign in