European Windows 2012 Hosting BLOG

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

European Visual Studio LightSwitch 2012 Hosting - Amsterdam :: New Features in VS LightSwitch 2012

clock October 29, 2012 06:28 by author Scott

As we know, Visual Studio 2012 has been released on Aug 15, 2012 I just wanted to discuss about the new features of LightSwitch.

In Visual Studio 2012, LightSwitch is included as a core part and we can create the LightSwitch application from Visual Studio 2012 IDE. LightSwitch will be available as a Project Template group Node in the Visual Studio 2012.


New Lightswitch Architecture

Visual Studio 2012 LightSwitch has a lot of enhancements including OData Services which leads to define the new architecture for the LightSwitch Application Development. You can get more details about the LightSwitch Architecture, please have a look at
MSDN.

New Enhancements in LightSwitch 2012

There are ton of new features included in the Visual Studio 2012 LightSwitch. We will briefly discuss about all the new features of the new enhanced LightSwitch.

1. Connecting with OData Services:

LightSwitch 2012 now supports Open Data Protocol Services.

2. Formatting Numbers & Dates:

We can easily format the Numbers and Dates using Format Pattern property in LightSwitch 2012. This Format Pattern Property is available only for the particular data types.

3. New Data Types in LightSwitch:

Visual Studio LightSwitch team has introduced two more Data Types namely Percent and Web Address. Here the Decimal will be treated as Percent business type and the String will be treated as Web Address.

4. Static Label & Image Control:

LightSwitch 2012 includes two more controls which can be used to display the content statically without binding data. These controls can be used to display the static texts about the organization and logo.

5. Improved Application Security:

In LightSwitch Business Application we can apply security by two ways like Forms Authentication and Windows Authentication, In Windows Authentication it is possible to provide the Roles & Permissions to Active Directory User Groups.

You can download the Visual Studio 2012 90 days trail version from the
Microsoft site.

If you need LightSwitch hosting, please check our site at
http://www.hostforlife.eu.

 



European DNN Hosting - Amsterdam :: Steps to Apply Facebox Effect in your DNN Blog

clock October 24, 2012 08:04 by author Scott

Facebox is a jQuery-based, Facebook-style lightbox which can display images, divs, or entire remote pages. And now, you can use it with your DNN module to make your DNN module more interactive. Today I would like to show you how to apply lightbox effect for some big image within dnn blog post. Note that we just demonstrated the process in Window Live Writer. Actually we also recommend that you should manage your posts with WLW, which will make your post management simply and easily. Now you just follow the simple steps below:

1) Open up your WLW and get started to write your post.


2) Just copy your big graphs or images into the content section of WLW and it will be scaled in to a little one. Also you can apply some options for some customized effects, like size, text wrapping, borders.




3) Set the option [Link to] as Source Picture and click the Options below. Then it should pop up the Source Picture Options window and there you can set it as follows and click "OK":




4) Switch the source tab at the left-bottom of content panel, find out the image tag section and insert the rel property for facebox detected. The following code should look like:




Okey, that’s all. Now the built-in facebox plugin will automatically attach the Facebook-style lightbox for your picture.


In the end I presented an illustration depicting a common scenario for DotNetNuke Deployment in the Enterprise.


 



European Orchard CMS Hosting - Amsterdam :: How to Install Orchard CMS with WebMatrix

clock October 22, 2012 07:01 by author Scott

Today, I will show you how to install Orchard CMS with WebMatrix. If you don’t have WebMatrix, you can download it first from Microsoft site.

WebMatrix currently gives you three options for creating a new website:


1) Site From Web Gallery

2) Site From Template
3) Site From Folder.



The
Site From Web Gallery Option is a portal into a number of Web Applications based on the .NET Framework. You will find some really nice ASP.NET Content Management Systems ( CMS ) that you can use to power your website. Of course, in this case we are interested in our favorite ASP.NET CMS, Orchard!

Once you choose Orchard CMS from the Web Gallery and give your new Orchard Website a name, click the next button to continue the process of installing Orchard CMS on your PC.




The next step is to confirm the download location and accept the Orchard CMS license. Click on I Accept to begin the download and installation of Orchard CMS on your PC.




WebMatrix will begin to download and install Orchard CMS into the
My Websites Directory under the name you called your new Orchard Website. Once download and installation is complete, you will be greeted with your final step.



Click OK! Congratulations, you have now successfully installed Orchard onto your PC.


You can now run your new Orchard Website within WebMatrix for the first time and begin configuring it based on your needs.




By default, Orchard includes a built-in database that you can use without installing a separate database server. However, if you are running SQL Server or SQL Server Express, you can configure Orchard to use either of those products instead by specifying a connection string. Optionally, you can enter a table prefix so that multiple Orchard installations can share the same database but keep their data separate.




The setup screen also includes a section where you can choose an Orchard recipe to set up your site. You can choose from the following Orchard recipes:


-
Default. Sets up a site with frequently used Orchard features.
- Blog. Sets up a site as a personal blog.
- Core. Sets up a site that has only the Orchard framework for development use.

<image>


Hope this tutorial help you. If you’re looking for Orchard CMS hosting, please visit our site at
http://www.hostforlife.eu. Find us also at Microsoft site, http://www.microsoft.com/web/hosting/HostingProvider/Details/953.

 



European WebMatrix Hosting - Amsterdam :: Deploy your Web Application with HostForLIFE.eu

clock October 15, 2012 08:24 by author Scott

Getting Ready to Publish

Before you publish your site to the world-wide-web it is a good idea click on the ‘Reports’ tab and ask WebMatrix to run a full site report. The generated report includes useful information on the site’s performance and hints on Search Engine Optimisation (SEO), to help make your site more visible to popular search engines such as Yahoo, Google and Bing.



To correct any errors or warnings simply click the ‘Edit this page’ link to be taken directly to the area of concern.




At this point it is also worth proof-reading your content and using the ‘Run’button on the toolbar to carry out cross-browser compatibility checks to ensure an optimal experience for all your users.


Once you are satisfied that your web site is ready for publication it is time to find a suitable hosting provider.


Finding a Hosting Provider

WebMatrix has a facility designed to help you find a suitable host for your web site. If you already have an account with a web hosting provider you may want to skip to the next section, ‘Configuring WebMatrix Publish Settings’.




By clicking on the ‘Need web hosting for your web site?’ button on the ‘Site’tab of the WebMatrix home page you will be directed to the ‘Find Web Hosting...’ page of the Microsoft web site.



WebMatrix passes some basic information about your web site to this page in order to generate a list of hosting plans tailored to meet the requirements of your site. The results can be filtered and the criteria changed, using the tools on the page.


You should be careful about changing some of these settings, in particular the scripting language; otherwise you could end up purchasing an account on a web server which won’t support the language in which your site has been written. If you are unsure of the scripting language you should leave it set to its default of ASP.NET 4.0. This is the default scripting language for all new WebMatrix projects.


The filters for minimum and maximum price, storage (GB), number of SQL databases, number of e-mail accounts and bandwidth per month can be set using the sliders.


The initial storage required for your site can be estimated by viewing the folder properties of your local site in Windows Explorer. However, this should only be taken as a guide as the overall required storage depends a great deal on the features of your site. For example, if your site has a facility to allow users to upload content, or contains a blog which will grow over time, be sure to allow for future expansion. Generally though web sites primarily consist of text files and small images and do not require a huge amount of disk space.


If your site requires the use of a database other than SQL Server Compact you will need to find a web host which has this facility. If you are using SQL Server or MySQL, WebMatrix will automatically publish scripts to create tables and insert data to replicate the schema and data on your development computer. These scripts will need to be run on the database provided for you by your chosen hosting provider, usually through the host’s control panel.


If you are using a SQL Server Compact database there is no need to choose a host with additional database facilities as SQL Server Compact is file-based, which can deliver a significant cost-saving in some cases. If you do choose this option though it is important to consider the disk-space required to store the database files - SQL Server Compact databases can grow to a maximum of 4GB in size. In addition to the SQL Server Compact (.sdf) file containing the data, WebMatrix will also upload the database program itself to the web server to ensure the site will work even if SQL Server Compact is not already installed.


To set up a new account, choose a suitable provider and click the green ‘Learn More’ button. This will display more information about the hosting package and a link to ‘Sign Up’ on the hosting company’s web site.


Configuring WebMatrix Publish Settings

Once you have chosen and purchased a hosting plan, the provider will typically send you an email confirming the details of your account and the information necessary to configure WebMatrix for publishing. This information will be provided either as a list of settings or as a .PublishSettings file.


Configuration Using A Publish Settings File


If your hosting company has provided you with a .PublishSettings file, this is the easiest way to set up publishing within WebMatrix.



To open the ‘Publish Settings’ dialog click the ‘Set up the remote publishing location for your web site’ button in the ‘Site’ tab of the WebMatrix home page.




Click on the ‘Import Publish Settings’ link and browse to your Publish Settings file. This will populate the Publish Settings dialog for you, including connection strings for any non-SQL Compact databases you may be using.


Click the ‘Validate Connection’ button to have WebMatrix check the settings and click ‘Save’.


Manual Configuration Without A Publish Settings File

If your web hosting company has not provided you with a .PublishSettings file it is easy to configure the Publish Settings manually using the host settings, usually sent to you in your confirmation email or available through the host’s control panel.




If you selected your hosting provider through WebMatrix you can leave the Protocol drop-down set to ‘Web Deploy’. If you did not choose your hosting provider through WebMatrix and your host does not support Web Deploy, you should skip ahead to the next section, ‘Configuring Publish Settings Using FTP’.


Enter the information provided to you by your web host into the boxes provided:


·
Server– This is typically referred to as the ‘Server Name’ or ‘Service URL’.

o E.g.- server.sample.com


·
User Name& Password – These are usually chosen by you at sign up, although alternatives for publishing may be set by the provider.

·
Site Name– Web hosting companies often refer to this as the ‘Site’ or ‘Site/Application’

o E.g.- site.server.sample.com


·
Destination URL – This is the URL that will be used to browse to your site.

o E.g.–
http://site.server.sample.com

Once you have entered all of the required information, click the ‘Validate Connection’ button to verify that WebMatrix can successfully connect to your hosting account and click ‘Save’.


Configuring Database Connections

If your web site is using a database other than SQL Server Compact, your site will need a web.configfile that tells the site how to connect to the database on your local development machine. When you add a database through the ‘Connect to Database’dialog in the ‘Databases’ tab, the file is automatically created and configured for you and looks something like this:


01.<?xml version="1.0" encoding="UTF-8"?>
02.
03.<configuration>
04.
05. <connectionStrings>
06.
07. <add connectionString="Uid=testUser;Server=testDBServer; Pwd=passw0rd; Database=testDB" name="testDB" providerName="System.Data.SqlClient" />
08.
09. </connectionStrings>
10.
11.</configuration>


Your web host will provide you with a connection string, or a series of settings, for connecting to the hosted database which you should enter in the‘Publish Settings’ dialog box.



These settings tell WebMatrix how to connect to the live data and overwrite the web.config settings on the host server.

Publishing Your Site to the World Wide Web

OK, so you have checked your site for errors, selected a web host and configured the WebMatrix Publish Settings; it’s time to publish your site.

The first time you click the ‘Publish’ button on the WebMatrix toolbar, a dialog will appear asking whether you would like WebMatrix to test your sites compatibility and adjust .NET settings on the remote server if necessary. Click ‘Yes’ to proceed with the test:



Once the test is complete the ‘Publish Preview’ dialog will be displayed. This dialog allows you to check the list of files to be published and make changes as necessary.


If this is the first time you have published your site you should ensure that you check the boxes next to any necessary databases, to have MebMatrix include them in the file upload. On subsequent publishes only the changed files will appear in this dialog, enabling you to easily keep your local development and remote hosted sites synchronized.




Once you are happy with your selection, click ‘Continue’ to publish your web site.


The yellow bar at the bottom of the screen will show the progress of file uploads and let you know when the publishing has been completed:




And that’s it! You have seen how easy it really is to find a suitable web site host and deploy feature-rich, dynamic, data-driven websites to your web server, using the power and flexibility of Microsoft WebMatrix.

 



Visual Studio 2012 Hosting - ASPHostPortal :: What is new in C# and Visual Basic in Visual Studio 2012

clock October 10, 2012 09:34 by author Scott

This post discusses the new language features that is introduced in Visual Studio 2012. One of the main things that language team introduced is the idea of producing windows 8 App. These APPs are talking to new API called windows runtime.

This release also brings iterators to Visual Basic. The main discussion in this post is around Asynchronous programming in C# language.




If you want to give importance on responsiveness of client and scalability in server App then you probably call Asynchronous API’s. These API’s take Callbacks as parameters and uses that Callback to notify you about result of available. When you start write these call backs then it is harder maintain the code but with new Async language support that introduced in Visual Basic and C# and it is easy consume these API’s.


Below is the synchronous code in C#




The code basically Searches the movie index in
Netflix using OData by taking Year as parameter. While it is downloading the movies using above code , you can notice you can not interact with your user interface. You can scroll along UI and explore the movies only after the search operation is complete. Users expects more responsive apps.

Why the above code is Unresponsive?

The call to DownloadString is of webclient type and it asks you to wait till it returns string. During this process your UI is going to hang-up and holds the thread until it returns the result back you.


Two different options here, you can put this code on background Thread and it is bit complicated. You may have to marshal and unmarshal the code. The second option is to interact with Asynchronous API there you have an overloaded function DownloadStringAsync, But when you use this method you are no longer take back data as result. You need to sign-up a call-back when a result is available. If you have multiple Async calls then you have to write multiple call-backs. In this case your code is getting more difficult to understand.

Solution

The new overload method is DownloadStringTaskAsync, This method now returns string of type Task, Task of string is object that notify you when result is available. Now you can change the signature of the method QueryMovies and mark this as async. This tells the compiler that this method is pausable and resumeable , they can wait without locking to the UI thread. Now change the return type of method from Movie array to Task<Movie[]> array. Write a word await to get the string from Task of objects from DownloadStringTaskAsync call.



Now you can call the above even from while loop




The compiler is now able to figure out how to handle the await inside the while loop and resume it when it gets the result. Now you should be able to interact with your UI without any hang-ups.

 



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.

 



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.

We have offered the latest Windows 2012 Hosting, ASP.NET 4.5 Hosting, ASP.NET MVC 5 Hosting, SQL 2014 Hosting and SQL 2014 Hosting.

Tag cloud

Sign in