European ASP.NET 4.5 Hosting BLOG

BLOG about ASP.NET 4, ASP.NET 4.5 Hosting and Its Technology - Dedicated to European Windows Hosting Customer

European ASPEmail Hosting - HostForLIFE.eu :: How to Use ASPEMail to Send Email

clock August 27, 2015 11:45 by author Scott

This is only short tutorial about how to send email using ASPEmail. If you require ASPEmail Hosting with low cost, please visit our site at http://www.hostforlife.eu. You can always start from €3.00/month to get this feature.

AspEmail is an active server component for sending email messages using an external SMTP server in an ASP or VB environment. AspEmail supports multiple recipients, multiple CC, multiple Bcc, multiple file attachments, HTML format, embedded images, and non-US ASCII character sets. 

A free copy of AspEmail can be downloaded from www.aspemail.com/download.html. 

Changing from AspMail to AspEmail 

Please make sure that you have valid email address to implement this code below:

<%
Set Mail = Server.CreateObject("Persits.MailSender")
Mail.Host = "mail.yourdomain.com" 
Mail.From = "[email protected]
Mail.FromName = "Support Team" 

Mail.AddAddress "[email protected]", "ScottT”
Mail.AddAttachment "e:\html\domains\yourdomaincom\html\filename.htm"

Mail.Subject = "Support Issue"
Mail.Body = "Dear Scott:" & chr(13) & chr(10) & _
"Have a nice day and thank you."

On Error Resume Next
Mail.Send
If Err <> 0 Then
Response.Write "An error occurred: " & Err.Description
End If
%> 


NOTE: For the Mail.Host line, put the IP address of your web server, NOT the mail server IP. 

To add the message recipients, CCs, BCCs, and Reply-To's, use the AddAddress, AddCC, AddBcc and AddReplyTo methods, respectively. These methods accept two parameters: the email address and, optionally, name. Notice that you must not use an '= 'sign to pass values to the methods. For example: 

Mail.AddAddress "[email protected], "Support Team"
Mail.AddCC "[email protected]" ' Name is optional


Use the Subject and Body properties to specify the message subject and body text, respectively. A body can be in a text or HTML format. In the latter case, you must also set the IsHTML property to True.

For example: Mail.Subject = "Support Issue"
Mail.Body = "Dear Scott:" & chr(13) & chr(10) & "Have a nice day and thank you."


or

Mail.Subject = "Support Issue"
Mail.Body="<HTML><BODY BGCOLOR=#0000FF>DearScott:....</BODY></HTML>"
Mail.IsHTML = True


To send a file attachment with the message, use the AddAttachment method. It accepts the full path to the file being attached. Call this method as many times as you have attachments.

Notice that you must not use the '= 'sign to pass a value to the method: 

** Note from Tech Support: the path below is correct for you. Make sure that you put your attachment in this directory first. Don't forget that "yourdomaincom" may be "yourdomainnet", etc., as applicable. ** 

Mail.AddAttachment "e:\html\domains\yourdomaincom\html\filename.htm"

In order to reference information from fields on a form you will need to use the following format:

"First Name: " & Request.form("FirstName") & chr(13) & chr(10) & _
"Last Name: " & Request.form("LastName") & chr(13) & chr(10) & _
"Email: " & Request.form("Email") & chr(13) & chr(10) & _


To send a message, call the Send method. The method throws exceptions in case of an error. You may choose to handle them by using the On Error Resume Next statement, as follows: 

On Error Resume Next
Mail.Send
If Err <> 0 Then
Response.Write "An error occurred: " & Err.Description
End If

HostForLIFE.eu ASPEmail Hosting
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 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 Entity Framework Hosting - UK :: Introduction about Entity Framework 5 and Implement it on MVC

clock August 5, 2015 09:47 by author Scott

In this article, we will introduce the Entity Framework 5.0 Code First approach in MVC applications. The ADO.NET Entity Framework is an Object Relational Mapper (ORM) included with the .NET framework. It basically generates business objects and entities according to the database tables. It provides basic CRUD operations, easily managing relationships among entities with the ability to have an inheritance relationship among entities.

When using the EF we interact with an entity model instead of the application's relational database model. This abstraction allows us to focus on business behavior and the relationships among entities. We use the Entity Framework data context to perform queries. When one of the CRUD operations is invoked, the Entity Framework will generate the necessary SQL to perform the operation.

How to Implement

To create this application we should have a basic knowledge of the DbContext class of theSystem.Data.Entity namespace. We should also be familiar with views because in this article I am not describing views for each action method so you can create a view according to action methods or you can scaffold templates to create a view for Edit, List, Create, Delete and Details.

We need to install the Entity Framework Nuget package in our application. When we install the Entity Framework Nuget package, two references (System.Data.Entity and EntityFramework) are added to our application. Thereafter we can perform CRUD operations using Entity Framework.

How to Use Entity Framework

Whether you have an existing database or not, you can code your own classes and properties (aka Plain Old CLR Objects, or POCOs) that correspond to tables and columns and use them with the Entity Framework without an .edmx file. In this approach the Entity Framework does not leverage any kind of configuration file (.edmx file) to store the database schema, because the mapping API uses these conventions to generate the database schema dynamically at runtime. Currently, the Entity Framework Code First approach does not support mapping to Stored Procedures. The ExecuteSqlCommand() and SqlQuery() methods can be used to execute Stored Procedures.

To understand the Entity Framework Code First Approach, you need to create an MVC application that has two entities, one is Publisher and another is Book. So let's see an example step-by-step. To create your MVC Application, in Visual Studio select "File" -> "New" -> "Project..." then select "MVC 4 Application" then select "Empty Application".

1. Create Modal Classes

We create classes for Publisher and Book under the Models folder, those classes are used as entities and an entities set. These classes will have mapping with a database because we are using the code first approach and these classes will create a table in a database using the DbContext class of Entity Framework. So let's see these classes one by one.
The Publisher class is in the Models folder; that file name is Publisher.cs as in the following:
using System.Collections.Generic;
namespace ExampleCodeFirstApproch.Models
{
    public class Publisher
    {
        public int PublisherId { get; set; }
        public string PublisherName { get; set; }
        public string Address { get; set; }
        public ICollection<book> Books { get; set; }
    }
}</book>


The Book class is in the Models folder; that file name is Book.cs as in the following:

namespace
ExampleCodeFirstApproch.Models

{
    public class Book
    {
        public int BookId { get; set; }
        public string Title { get; set; }
        public string Year { get; set; }
        public int PublisherId { get; set; }
        public Publisher Publisher { get; set; }
    }
}


2. Create Data Access Layer
This part of the article is the heart of the article as well as the code first approach. First of all we need a connection string so we can connect with our database by application. We create a connection in the web.configfile. I provide the connection string name as DbConnectionString, you are free to give any name to it but remember it because we will use it in our context class.

<connectionStrings>
   
<add name="DbConnectionString"
     
connectionString="Data Source=steve-PC;Initial Catalog=CodeFirst;User ID=sa;
      Password=*******" providerName="System.Data.SqlClient" />
</connectionStrings>

We have both classes, Publisher and Book, so now we will create a context class. We create aLibraryContext class under the Models folder, that file name is LibraryContext.cs. This class inherits DbContextso we can use the DbContext class methods using a LibraryContext class object as in the following:
using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity;
namespace ExampleCodeFirstApproch.Models
{
    public class LibraryContext :DbContext
    {
        public LibraryContext()
            : base("name=DbConnectionString")
        {
        }
        public DbSet<Publisher> Publishers { get; set; }
        public DbSet<Book> Books { get; set; }
        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {                     
            modelBuilder.Entity<Publisher>().HasKey(p => p.PublisherId);
            modelBuilder.Entity<Publisher>().Property(c => c.PublisherId)
                .HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);           
            modelBuilder.Entity<Book>().HasKey(b => b.BookId);
            modelBuilder.Entity<Book>().Property(b => b.BookId)
                .HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);           
            modelBuilder.Entity<Book>().HasRequired(p => p.Publisher)
                .WithMany(b => b.Books).HasForeignKey(b=>b.PublisherId);           
            base.OnModelCreating(modelBuilder);
        }
    }
}

Our LibraryContext class that inherits the DbContext class is ready. The LibraryContext class has a three-part constructor, DbSet properties, and an OnModelCreating method. Let's see each one by one.

Constructor: It is an empty constructor that doesn't have any parameters, in other words it is the default constructor but it inherits the base class single string parameterized constructor. This constructor constructs a new context instance using the given string as the name (as we used) or the connection string for the database to which a connection will be made. Here DbConnectionString is the name of the connection string defined in the web.config file of the application.

public LibraryContext(): base("name=DbConnectionString")
{
}

Property: When developing with the Code First workflow you define a derived DbContext that represents the session with the database and exposes a DbSet for each type in your model. The common case shown in the Code First examples is to have a DbContext with public automatic DbSet properties for the entity types of your model.
public DbSet<Publisher> Publishers { get; set; }
public DbSet<Book> Books { get; set; }


The Dbset property represents an entity set used to perform create, read, update, and delete operations. A non-generic version of DbSet<TEntity> can be used when the type of entity is not known at build time. Here we are using the plural name of the property for an entity, that means your table will be created with this name in the database for that specific entity.

Method: The LibraryContext class has an override OnModelCreating method. This method is called when the model for a derived context has been initialized, but before the model has been locked down and used to initialize the context. The default implementation of this method does nothing, but it can be overridden in a derived class such that the model can be further configured before it is locked down. Basically in this method we configure the database table that will be created by a model or a defined relationship among those tables.
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{  
   modelBuilder.Entity<Publisher>().HasKey(p => p.PublisherId);
   modelBuilder.Entity<Publisher>().Property(c => c.PublisherId)
          .HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
   modelBuilder.Entity<Book>().HasKey(b => b.BookId);
   modelBuilder.Entity<Book>().Property(b => b.BookId)
         .HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
   modelBuilder.Entity<Book>().HasRequired(p => p.Publisher)
         .WithMany(b => b.Books).HasForeignKey(b=>b.PublisherId);
   base.OnModelCreating(modelBuilder);
}

This method accepts one parameter, an object of DbModelBuilder. This DbModelBuilder class maps POCO classes to database schema. This method is called only once when the first instance of a derived context is created. The model for that context is then cached and is for all further instances of the context in the app domain. This caching can be disabled by setting the ModelCaching property on the given ModelBuidler, but this can seriously degrade performance. More control over caching is provided through use of theDbModelBuilder and DbContext classes directly.

Configure/Mapping Properties with the Fluent API
The OnModelCreating() method under the LibraryContext class uses the Fluent API to map and configure properties in the table. So let's see each method used in the OnModelCreating() method one by one.

modelBuilder.Entity<Book>().HasRequired(p => p.Publisher)
.WithMany(b => b.Books).HasForeignKey(b=>b.PublisherId);

3. Create Controller for CRUD Operations

Now we create two controllers, one for Publisher CRUD operations (PublisherController.cs) and another for Book CRUD operations (BookController.cs) under the Controllers folder in the application. So here is the code for each.

The Publisher controller in the file PublisherController.cs in the Controllers folder:
using System.Linq;
using System.Web.Mvc;
using ExampleCodeFirstApproch.Models;
namespace ExampleCodeFirstApproch.Controllers
{
    public class PublisherController : Controller
    {
        LibraryContext objContext;
        public PublisherController()
        {
            objContext = new LibraryContext();
        }
        #region List and Details Publisher
        public ActionResult Index()
        {
            var publishers = objContext.Publishers.ToList();
            return View(publishers);
        }
        public ViewResult Details(int id)
        {
            Publisher publisher =
              objContext.Publishers.Where(x=>x.PublisherId==id).SingleOrDefault();
            return View(publisher);
        }
        #endregion
        #region Create Publisher
        public ActionResult Create()
        {
            return View(new Publisher());
        }
        [HttpPost]
        public ActionResult Create(Publisher publish)
        {
            objContext.Publishers.Add(publish);
            objContext.SaveChanges();
            return RedirectToAction("Index");
        }
        #endregion
        #region edit publisher
        public ActionResult Edit(int id)
        {
            Publisher publisher = objContext.Publishers.Where(
              x => x.PublisherId == id).SingleOrDefault();
            return View(publisher);
        }
        [HttpPost]
        public ActionResult Edit(Publisher model)
        {
            Publisher publisher = objContext.Publishers.Where(
              x => x.PublisherId == model.PublisherId).SingleOrDefault();
            if (publisher != null)
            {
                objContext.Entry(publisher).CurrentValues.SetValues(model);
                objContext.SaveChanges();
                return RedirectToAction("Index");
            }             
            return View(model);
        }
       #endregion
        #region Delete Publisher
        public ActionResult Delete(int id)
        {
            Publisher publisher = objContext.Publishers.Find(id);
            //.Where(x => x.PublisherId == id).SingleOrDefault();

            return View(publisher);
        }
        [HttpPost]
        public ActionResult Delete(int id, Publisher model)
        {
           var publisher =
             objContext.Publishers.Where(x => x.PublisherId == id).SingleOrDefault();
           if (publisher != null)
            {
                objContext.Publishers.Remove(publisher);
                objContext.SaveChanges();
            }
            return RedirectToAction("Index");
        }
        #endregion
    }
}

The Book controller in the file BookController.cs in the Controllers folder:
using
System.Linq;
using System.Web.Mvc;
using ExampleCodeFirstApproch.Models;
namespace ExampleCodeFirstApproch.Controllers
{
    public class BookController : Controller
    {
       LibraryContext objContext;
       public BookController()
        {
            objContext = new LibraryContext();
        }
        #region List and Details Book
        public ActionResult Index()
        {
            var books = objContext.Books.ToList();
            return View(books);
        }
        public ViewResult Details(int id)
        {
            Book book = objContext.Books.Where(x=>x.BookId==id).SingleOrDefault();
            return View(book);
        }
        #endregion
        #region Create Publisher
        public ActionResult Create()
        {
            return View(new Book());
        }
        [HttpPost]
        public ActionResult Create(Book book)
        {
            objContext.Books.Add(book);
            objContext.SaveChanges();
            return RedirectToAction("Index");
        }
        #endregion
        #region Edit Book
        public ActionResult Edit(int id)
        {
            Book book = objContext.Books.Where(x => x.BookId == id).SingleOrDefault();
            return View(book);
        } 
        [HttpPost]
        public ActionResult Edit(Book model)
        {
            Book book = objContext.Books.Where(x => x.BookId == model.BookId).SingleOrDefault();
            if (book != null)
            {
                objContext.Entry(book).CurrentValues.SetValues(model);
                objContext.SaveChanges();
                return RedirectToAction("Index");
            }             
            return View(model);
        }
       #endregion
        #region Delete Book
        public ActionResult Delete(int id)
        {
            Book book = objContext.Books.Find(id);
            return View(book);
        }
        [HttpPost]
        public ActionResult Delete(int id, Publisher model)
        {
           var book = objContext.Books.Where(x => x.BookId == id).SingleOrDefault();
           if (book != null)
            {
                objContext.Books.Remove(book);
                objContext.SaveChanges();
            }
            return RedirectToAction("Index");
        }
        #endregion
    }
}


Both Publisher and Book controllers are ready and create a view according to the action method using a scaffold template and you can download a zip folder. Run the application and you get that your tables are created in the database with a relationship.



European ASP.NET Hosting - Germany :: The Difference Between DataSet, DataReader, DataAdapter and DataView in .net

clock March 24, 2015 11:38 by author Scott

Here is short tutorial only about the difference DataSet, DataReader, DataAdapter and DataView in .net.

1. DataSet

Dataset is connection-less oriented, that means whenever we bind data from database it connects indirectly to the database and then disconnected. It has read/write access on data tables. It supports both forward and backward scanning of data.

DataSet is a container of one or more DataTable. More often than not, it will just contain one table, but if you do a query with multiple SELECT statements, the DataSet will contain a table for each.

You have to be careful about how much data you pull into a DataSet, because this is an in-memory representation. You can Fill a DataSet using the Fill() method of a DataAdapter.

You can download example code at the end of this tutorial!

2. DataReader

DataReader is connection-oriented, that means whenever we bind data from database it must require a connection and after that disconnected from the connection. It has read-only access, we can’t do any transaction on them. It supports forward-only scanning of data, in other words you can’t go backward.

DataReader fetches one row at a time so very less network cost as compare to DataSet(that fethces all the rows at a time). It is scalable to any number of records, at least in terms of memory pressure, since it only loads one record at a time. One typical way to get a DataReader is by using theExecuteReader() method of a DbCommand.

You can download example code at the end of this tutorial!

3. DataAdapter

DataAdapter is an ADO.NET Data Provider. DataAdapter can perform any SQL operations like Insert, Update, Delete, Select in the Data Source by using SqlCommand to transmit changes back to the database.

DataAdapter provides the communication between the Dataset/DataTable and the Datasource. We can use the DataAdapter in combination with the DataSet/DataTable objects. These two objects combine to enable both data access and data manipulation capabilities.

You can download example code at the end of this tutorial!

4. DataView

Generally, we use DataView to filter and sort DataTable rows. So we can say that DataView is like a virtual subset of a DataTable. This capability allows you to have two controls bound to the same DataTable, but showing different versions of the data.

For example, one control may be bound to a DataView showing all of the rows in the table, while a second may be configured to display only the rows that have been deleted from the DataTable. The DataTable also has a DefaultView property which returns the default DataView for the table.



European ASP.NET Hosting - France :: How to Improve your ASP.NET Web API Performance

clock February 24, 2015 08:46 by author Scott

In this article, I will share about how to improve your ASP.NET Web API performance

1. Use fastest JSON serializer

JSON serialization  can affect overall performance of ASP.NET Web API significantly. A year and a half I have switched from JSON.NET serializer on one of my project to ServiceStack.Text .

2. Use other formats if possible (protocol buffer, message pack)

If you can use other formats like Protocol Buffers or MessagePack in your project instead of JSON do it.

You will get huge performance benefits not only because Protocol Buffers serializer is faster, but because format is smaller than JSON which will result in smaller and faster responses.

3. Implement compression

Use GZIP or Deflate compression on your ASP.NET Web API.

Compression is an easy and effective way to reduce the size of packages and increase the speed.

4. Use Caching

If it makes sense, use output caching on your Web API methods. For example, if a lot of users accessing same response that will change maybe once a day.

5. Implement async on methods of Web API

Using asynchronous Web API services can increase the number of concurrent HTTP requests Web API can handle.

Implementation is simple. The operation is simply marked with the async keyword and the return type is changed to Task.

[HttpGet] 
public async Task OperationAsync() 
{  
    await Task.Delay(2000); 
}

6. Use classic ADO.NET if possible

Hand coded ADO.NET is still the fastest way to get data from database. If the performance of Web API is really important for you, don’t use ORMs.

Please just see this table performance below

The Dapper and the hand-written fetch code are very fast, as expected, all ORMs are slower than those three.

LLBLGen with resultset caching is very fast, but it fetches the resultset once and then re-materializes the objects from memory.

Hope above tutorial help you.



European ASP.NET Signal R Hosting - Paris :: How to Integrate ASP.NET with SignalR Hubs

clock February 23, 2015 07:40 by author Scott

In modern applications the end users want to get their data. They want it now, they want it up-to date. In fact it does not matter whether these are pure web application, native desktop installations or mobile apps: everybody wants his data now!

For .NET-minded developers there are a numbers of options to implement near-real-time push style communication from the server/the services to the clients/consumers. You can choose plain HTTP or the super-new WebSockets features available in .NET 4.5 together with Windows 8 and Windows Server 2012. But the coolest and increasingly popular approach is to use a new framework: ASP.NET SignalR.

While it is not intended- and surely beyond the scope of this ebook - to give an introduction or even deep dive into SignalR, we need to have a look at some concepts and code in order to realize a smooth integration of SignalR and AngularJS.

The final goal of this chapter is to have an AngularJS-style integration of calling and listening to server-side SignalR push services.

A Simple SignalR Hub

Our server-side hub for demonstration in this chapter will be a server time emitting push service.

It has one method which can be called as the inbound API. And we will add a background worker in ASP.NET which will periodically push the server time every 5 seconds to all connected clients. For the sake of clarification that hubs do not really need to have both, an inbound and outbound API we will use two different hubs:

  • one for calling the server time from the client (kind of a Web API replacement, but based on the hubs protocol) - aka inbound API.
  • another one for using the hub context to call into connected clients - aka outbound API.

using Microsoft.AspNet.SignalR;
using System;

namespace Henriquatre.Integration.SignalR
{
    public class ServerTimeHub : Hub
    {
        public string GetServerTime()
        {
            return DateTime.UtcNow.ToString();
        }
    }

    public class ClientPushHub : Hub
    {
    }
}

How to Schedule Frequent Pushes on the Server

The official and recommended approach to run scheduled background work in ASP.NET is to implement an IRegisteredObject with the ASP.NET runtime and hook it up at application start.

In the end it can be a simple as this:

using Microsoft.AspNet.SignalR;
using System;
using System.Threading;
using System.Web.Hosting;

namespace Henriquatre.Integration.SignalR
{
    public class BackgroundServerTimeTimer : IRegisteredObject
    {
        private Timer taskTimer;
        private IHubContext hub;

        public BackgroundServerTimeTimer()
        {
            HostingEnvironment.RegisterObject(this);

            hub = GlobalHost.ConnectionManager.GetHubContext<ClientPushHub>();          

            taskTimer = new Timer(OnTimerElapsed, null,
                TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(5));
        }

        private void OnTimerElapsed(object sender)
        {
            hub.Clients.All.serverTime(DateTime.UtcNow.ToString());
        }

        public void Stop(bool immediate)
        {
            taskTimer.Dispose();

            HostingEnvironment.UnregisterObject(this);
        }
    }
}

Inside of the constructor we get a reference to the hub context for our ClientsPushHub. This reference is then used in the timer's event to call all registered clients and actually call the serverTime 'method' on the client side.

In global.asax.cs we can simply create and set up the registered objects (we have another in place here for pushing performance data, see below in this chapter) and get our hubs pipeline working by adding the hub routes to the routes table. In this case we enable CORS as the SignalR services are located on a different server than the client-side HTML and JavaScript application.

using System.Web.Http;
using System.Web.Mvc;
using System.Web.Routing;
using Microsoft.AspNet.SignalR;

namespace Henriquatre.Integration.SignalR
{
    public class MvcApplication : System.Web.HttpApplication
    {
        private BackgroundServerTimeTimer bstt;
        private BackgroundPerformanceDataTimer bpdt;

        protected void Application_Start()
        {
            bstt = new BackgroundServerTimeTimer();
            bpdt = new BackgroundPerformanceDataTimer();

            RouteTable.Routes.MapHubs(new HubConfiguration
                { EnableCrossDomain = true });

            AreaRegistration.RegisterAllAreas();

            WebApiConfig.Register(GlobalConfiguration.Configuration);
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
        }
    }
}

Speaking of the JavaScript clients, let's have a quick look at how to build a JS-based application with the Microsoft-provided JavaScript APIs.

SignalR JavaScript Client APIs

The current version (1.1 beta as of writing) provides two jQuery-based JavaScript APIs:

  • with JS proxy: the client uses a dynamically generated JS file as a proxy description for the hubs ('SignalR-WSDL', if you like).
  • without JS proxy: there is no static metadata involved at all and we wire up events and do method calls based on event and method names.

For a smooth integration between SignalR's JavaScript and AngularJS we are going to choose the no proxy route (no pun intended!).

An AngularJS Service for Integrating Hubs

With the above in mind we can write an AngularJS service that wraps and encapsulates the SignalR communication.

The following code shows the fully functional service. We are actually creating a kind of factory which the user of the service can then do different things with by working on the internally created runtime proxy object:

  • register local JavaScript methods which can be called by a server-side SignalR hub (local events, if you will) - this happens through the on method.
  • unregister a local JavaScript method from the runtime proxy by using off.
  • calling server-side hub methods by using the invoke function.

For convenience, we are also exposing the SignalR hub connection in order to get relevant data like e.g. the connection ID.

'use strict';

app.factory('signalRHubProxy', ['$rootScope', 'signalRServer',
    function ($rootScope, signalRServer) {
        function signalRHubProxyFactory(serverUrl, hubName, startOptions) {
            var connection = $.hubConnection(signalRServer);
            var proxy = connection.createHubProxy(hubName);
            connection.start(startOptions).done(function () { });           

            return {
                on: function (eventName, callback) {
                    proxy.on(eventName, function (result) {
                        $rootScope.$apply(function () {
                            if (callback) {
                                callback(result);
                            }
                        });
                    });
                },
                off: function (eventName, callback) {
                    proxy.off(eventName, function (result) {
                        $rootScope.$apply(function () {
                            if (callback) {
                                callback(result);
                            }
                        });
                    });
                },
                invoke: function (methodName, callback) {
                    proxy.invoke(methodName)
                        .done(function (result) {
                            $rootScope.$apply(function () {
                                if (callback) {
                                    callback(result);
                                }
                            });
                        });
                },
                connection: connection
            };
        };

        return signalRHubProxyFactory;   
}]);

The sample controller below illustrates how to use the SignalR AngularJS service. First, we get a reference to that 'factory' object by passing in the base URL of the SignalR hubs. This is essential when using the hubs in a cross-domain scenario. Optionally we can also pass the documented SignalR client configuration options.

From there on it is straight-forward to hook up client events and invoke/call methods on the server.

function ServerTimeController($scope, signalRHubProxy) {
    var clientPushHubProxy = signalRHubProxy(
        signalRHubProxy.defaultServer, 'clientPushHub',
            { logging: true });
    var serverTimeHubProxy = signalRHubProxy(
        signalRHubProxy.defaultServer, 'serverTimeHub');

    clientPushHubProxy.on('serverTime', function (data) {
        $scope.currentServerTime = data;
        var x = clientPushHubProxy.connection.id;
    });  

    $scope.getServerTime = function () {
        serverTimeHubProxy.invoke('getServerTime', function (data) {
            $scope.currentServerTimeManually = data;
        });
    };
};

How Does it Works?

AngularJS internally works with cycles when it comes to execute data binding and to determine when values of the model have changed. One of the cycles is the digesting cycle where Angular checks for model changes by processing and evaluating all registered watch expressions. But if model changes happen outside of the AngularJS world - in our case we get a callback executed externally, not happening in any controller or AngularJS artifact - then we need to instruct Angular that the model actually has changed.

This is what $apply is for: available on the scope, it triggers (or forces) the digesting cycle by calling$digest internally (API Reference: ng.$rootScope.Scope) and this is what we need to use in our SignalR-wrapping service.

on: function (eventName, callback) {
    proxy.on(eventName, function (result) {
       $rootScope.$apply(function () {
          if (callback) {
             callback(result);
          }
       });
    });
}

Conclusion

Last but not least we are showing you a running embedded example of the AngularJS-SignalR integration. This does not only use the already shown and discussed two hubs for the server time but a new one which frequently pushes current performance counter data (CPU values, in this case) to the connected clients.



European ASP.NET 4.5 Hosting - UK :: Zip File Manipulation in ASP.NET 4.5

clock December 11, 2014 08:16 by author Scott

One of the missing feature of .NET framework was a support for Zip file manipulation such as reading the zip archive, adding files, extracting files, etc. and we were using some third party libraries such as excellent the DotNetZip. In .NET 4.5, we have an extensive support for manipulating .zip files.

First thing that you should do is to add System.IO.Compression assembly as reference to your project. You may also want to reference System.IO.Compression.FileSystem assembly to access three extension methods (from the ZipFileExtensions class) for the ZipArchive class: CreateEntryFromFile,CreateEntryFromFile, and ExtractToDirectory. These extension methods enable you to compress and decompress the contents of the entry to a file.

Let’s cover the bits and pieces that we get from System.IO.Compression assembly at first. The below sample shows how to read a zip archive easily with ZipArchive class:

static void Main(string[] args) {

    const string zipFilePath = @"C:\apps\Sample Pictures.zip";

    using (FileStream zipFileToOpen = new FileStream(zipFilePath, FileMode.Open))
    using (ZipArchive archive = new ZipArchive(zipFileToOpen, ZipArchiveMode.Read)) {

        foreach (var zipArchiveEntry in archive.Entries)
            Console.WriteLine(
                "FullName of the Zip Archive Entry: {0}", zipArchiveEntry.FullName
            );
    }
}

In this sample, we are opening the zip archive and iterate through the collection of entries. When we run the application, we should see the list of files inside the zip archive:

It’s also so easy to add a new file to the zip archive:

static void Main(string[] args) {

    const string zipFilePath = @"C:\apps\Sample Pictures.zip";

    using (FileStream zipFileToOpen = new FileStream(zipFilePath, FileMode.Open))
    using (ZipArchive archive = new ZipArchive(zipFileToOpen, ZipArchiveMode.Update)) {

        ZipArchiveEntry readMeEntry = archive.CreateEntry("ReadMe.txt");
        using (StreamWriter writer = new StreamWriter(readMeEntry.Open())) {
            writer.WriteLine("Lorem ipsum dolor sit amet...");
            writer.Write("Proin rutrum, massa sed molestie porta, urna...");
        }

        foreach (var zipArchiveEntry in archive.Entries)
            Console.WriteLine(
                "FullName of the Zip Archive Entry: {0}", zipArchiveEntry.FullName
            );
    }
}

In this sample, we are adding a file named ReadMe.txt at the root of archive and then we are writing some text into that file.

Extracting files is into a folder is so easy as well. You need reference the System.IO.Compression.FileSystem assembly along with System.IO.Compression assembly as mentioned before for this sample:

static void Main(string[] args) {

    const string zipFilePath = @"C:\apps\Sample Pictures.zip";
    const string dirToExtract = @"C:\apps\Sample Pictures\";

    using (FileStream zipFileToOpen = new FileStream(zipFilePath, FileMode.Open))
    using (ZipArchive archive = new ZipArchive(zipFileToOpen, ZipArchiveMode.Update))
        archive.ExtractToDirectory(dirToExtract);
}

There are some other handy APIs as well but it is so easy to discover them by yourself. 



European ASP.NET 4.5 Hosting - France :: Using HTML 5 and ASP.NET to Upload Files

clock December 4, 2014 07:03 by author Scott

ASP.NET web applications that require uploading files from the client machine to the server use the file field to select files. The selected files are uploaded to the server using form submission techniques. In addition to the file field, HTML5 also allows you to select files using drag and drop. Using this feature you can drag files from Windows Explorer or Desktop and drop them on a predefined area of a web page. The files can then be uploaded to the server. This article illustrates how the HTML5 drag and drop feature can be used to upload files on the server.  

Traditionally you use the HTML file field to select files that are to be uploaded to the server. ASP.NET web forms wrap the file field into the FileUpload server control and ASP.NET MVC applications can use an <input> element with type attribute set to file. Another alternative offered by HTML5 is dragging one or more files from Windows Explorer or Desktop and drop them onto some predefined HTML element of a web page. You can then access the dropped files using the dataTransfer object available to drag and drop events.

To understand how files can be selected using the drag and drop features of HTML5, let's develop a new ASP.NET web forms application. The HTML markup of the default web form is shown below:

<form id="form1" runat="server">
<center>
 
<div id="box">Drag & Drop files from your machine on this box.</div>
 
<br />
 
<input id="upload" type="button" value="Upload Selected Files" />
</center>
</form>

As you can see, the <form> consists of a <div> element and a button. The <div> element is intended to drop the files dragged from the local machine. Merely dropping the files won't upload them to the server. Clicking on the button initiates the file upload operation.

To handle the file drop operation you need to wire certain event handlers to the box <div> element. The following jQuery code shows how that can be done:

var selectedFiles; 

$(document).ready(function () {
  var box;
  box = document.getElementById("box");
  box.addEventListener("dragenter", OnDragEnter, false);
  box.addEventListener("dragover", OnDragOver, false);
  box.addEventListener("drop", OnDrop, false);
...
}

The code declares a global variable named selectedFiles for storing a list of selected files. The ready() function wires three event handler functions to the respective events of the box <div> element, viz. dragenter, dragover and drop using addEventListener() method. The first parameter of the addEventListener() method is the event name and the second parameter is the event handler function. The event handler functions are shown below:

function OnDragEnter(e) {
  e
.stopPropagation();
  e
.preventDefault();
} 

function OnDragOver(e) {
  e
.stopPropagation();
  e
.preventDefault();
} 

function OnDrop(e) {
  e
.stopPropagation();
  e
.preventDefault();
  selectedFiles
= e.dataTransfer.files;
  $
("#box").text(selectedFiles.length + " file(s) selected for uploading!");
}

The OnDragEnter() and OnDragOver() event handler functions are simple and they merely prevent the event bubbling of the respective events. The OnDrop() function is important since it handles the drop event. The list of files dragged and dropped on the <div> element is obtained using the files property of the dataTransfer object. The files object is of type FileList and each item of the FileList collection is of type File. These two objects are available as a part of the HTML5 File API. The OnDrop() function stores the selected files in the global variable - selectedFiles and displays a message in the <div> using the text() method that indicates the number of files selected. The following figure shows how the default web form looks after dragging and dropping files on the <div> element.

Default web form after dragging and dropping files to the <div> element

How to Send Files to the Servere?

To send the selected files from the client to the server you can use different techniques but in this example you will use jQuery $.ajax() method for uploading the files. The following code shows how $.ajax() method can be used for this purpose.

$("#upload").click(function () {
  var data = new FormData();
  for (var i = 0; i < selectedFiles.length; i++) {
    data.append(selectedFiles[i].name, selectedFiles[i]);
  }
  $.ajax({
    type: "POST",
    url: "FileHandler.ashx",
    contentType: false,
    processData: false,
    data: data,
    success: function (result) {
      alert(result);
    },
    error: function () {
      alert("There was error uploading files!");
    }
  });
});

The code shown above first creates a FormData object. The FormData object encapsulates form's data that you wish to send to the server. All the selected files are added to the FormData object using its append() method. The first parameter of the append() method is the name of the file being added and the second parameter is the File object itself. Once the FormData object is ready you make a POST request to a Generic ASP.NET Handler (FileHandler.ashx) using jQuery $.ajax() method. You will create the generic handler in the next section.

The type of the request is POST. The url is FileHandler.ashx. Notice that the processData option is set to false. By default when you use the $.ajax() method the data is sent in URL encoded format. To prevent this behavior processData is set to false. The data option  is set to the FormData object created earlier. The success function simply displays the message returned by the generic handler. The error handler function displays an error message in case there is any error while calling FileHandler.ashx.

Receive the Uploaded Files

The ASP.NET generic handler - FileHandler.ashx - receives the files sent by the $.ajax() method. The generic handler also saves them to a folder on the server. The following code shows how the handler accomplishes this task:

public void ProcessRequest(HttpContext context)
{
   
if (context.Request.Files.Count > 0)
   
{
       
HttpFileCollection files = context.Request.Files;
       
foreach (string key in files)
       
{
           
HttpPostedFile file = files[key];
           
string fileName = file.FileName;
            fileName
= context.Server.MapPath("~/uploads/" + fileName);
            file
.SaveAs(fileName);
       
}
   
}
    context
.Response.ContentType = "text/plain";
    context
.Response.Write("File(s) uploaded successfully!");
}

The ProcessRequest() method of the FileHandler.ashx is called when the files are sent to the server using the $.ajax() method. The uploaded files can be accessed using the Files collection of the Request object. Each item inside the Files collection is of type HttpPostedFile. A foreach loop iterates through all the files from the Files collection and saves the individual file using the SaveAs() method of HttpPostedFile class. Once all files are saved a success message is sent to the client.

Note that by default ASP.NET sets request length to 4096 bytes. If you wish to upload large files you may adjust the request length using web.config file as shown below:

<httpRuntime
  
maxRequestLength="20000"
  
requestValidationMode="4.5"
  
targetFramework="4.5"
  
encoderType="..." />

As you can see the maxRequestLength attribute of the <httpRuntime> section is set to 20000 bytes. You need to adjust this value as per your requirement.

That's it! You can now run the web form, drag and drop files on the <div> element and click on the "Upload Selected Files" button to upload them on the server. 



European ASP.NET 4.5 Hosting - Spain :: How to Count Your Visitors on Website Using ASP.NET C#

clock August 5, 2014 06:22 by author Scott

This is only simple tutorial how to count number of visitors to a website in asp.net using C#. Just only brief description and hope you enjoy this tutorial

1. First thing to do is open Global.asax file and write the code as shown below

void Application_Start(object sender, EventArgs e)
{
Application["VisitorCount"] = 0;
}

void Session_Start(object sender, EventArgs e)
{
Application["VisitorCount"] = (int)Application["VisitorCount"] + 1;


void Session_End(object sender, EventArgs e)
{
Application["VisitorCount"] = (int)Application["VisitorCount"] - 1;
}

2. Now open your aspx page in which you want to show the count and write the following code.

<div>
<asp:Label ID="lbl_Count" runat="server" ForeColor="Red" /> 

</div>

3. You’ll see the below code in the cs file on page load event

protected void Page_Load(object sender, EventArgs e)
{
lbl_Count.Text = Application["VisitorCount"].ToString();
}

Good luck and hope this tutorial help



European ASP.NET 4.5 Hosting - UK :: How to Use ListView Control in ASP.NET 4.5

clock July 24, 2014 08:49 by author Scott

ASP.NET 4.5 offer many great feature. Previously, we have discussed about one of new feature on ASP.NET 4.5, Key HTML Editor Features in ASP.NET 4.5. In today post, we will discuss about how to use ListView Control in ASP.NET 4.5

ASP.NET ListView Control has a great features that GridView and Repeater controls had control over the markup. The ListView Control allows you to display the data in various formats including grid format, bulleted list format and in flow format.

How to Insert and Delete Data with the ListView Control

OK, let’s get started

1. Drag the ListView control from data category of the toolbox to default.aspx page and choose the datasource for the control as shown below

2. Configure ListView option from ListViewControl smart tags as shown below

Provide the template information by selecting the desired template and also it allows you to select style for control. It also allows you to enable operations such as inserting and updating.

3. Add some custom styling to the control by adding a class as shown below

<LayoutTemplate>
            <ul id="itemPlaceholderContainer" runat="server" class="ItemStyle">
                <li runat="server" id="itemPlaceholder" />
            </ul>
</LayoutTemplate>

4. Remove the Id columns from ItemTemplate as these mark-ups generated automatically when you configure the control and columns. Repeat the same for InsertItemTemplate.

5. Add the custom styles to item containers as below

.ItemStyle
{
  width: 800px;
  list-style-type:none;
  clear:both;
}

.ItemStyle li
{
  height: 300px;
 width:250px;
 float:left;
}
.ItemStyle li img
{
 width:180px;
margin: 10px 20px 10px 0;
}

6. Run your application and you’ll see the result

Hosting Your ASP.NET 4.5 Site with HostForLIFE.eu

If you need/looking for cheap and reliable ASP.NET 4.5 hosting with European server, you can rely on us. We have support the latest ASP.NET 4.5 on our shared hosting environment. You can always start from only €1.29/month to test drive your new ASP.NET 4.5 application. Why wait longer??



European ASP.NET Hosting - Germany :: How to Fix - The specified string is not in the form required for an e-mail address

clock July 10, 2014 09:08 by author Scott

Hello, in this post, I will describe short tutorial about how to solve The specified string is not in the form required for an e-mail address. I found many people find this error on forums. Here is the error message:

As you can see above, that is the error message that you might find. So, what’s the problem?

OK, the problem in this case is not from the page itself, but it comes from your web.config file. This configuration file has a <system.net /> element that enables you to store information about the mail server and the from account. I will give you 2 examples below how it will crash your page:

<system.net>
  <mailSettings>
    <smtp from="you.yourprovider.com">
      <network host="smtp.yourprovider.com"/>
    </smtp>
  </mailSettings>
</system.net>

Please see the missing @ symbol in the mail address. And other error may come from incorrect encoded angled brackets, see this:

<system.net>
  <mailSettings>
    <smtp from="Your Name &lt;[email protected]">
      <network host="smtp.yourprovider.com"/>
    </smtp>
  </mailSettings>
</system.net>

This from attributes has an opening < character (encoded as &lt;) but lacks the closing > bracket. To avoid the error, make sure the e-mail address in the from attribute has a valid syntax and uses the right angled brackets (if you use both a name and an e-mail address) like this:

<system.net>
  <mailSettings>
    <smtp from="Your Name &lt;[email protected]&gt;">
      <network host="smtp.yourprovider.com"/>
    </smtp>
  </mailSettings>
</system.net>

If you are curious why your code crashed, then you can use Reflector and take a look in the class’s constructor code:

public MailMessage()
{
  this.body = string.Empty;
  this.message = new Message();
  if (Logging.On)
  {
    Logging.Associate(Logging.Web, this, this.message);
  }
  string from = SmtpClient.MailConfiguration.Smtp.From;
  if ((from != null) && (from.Length > 0))
  {
    this.message.From = new MailAddress(from);
  }
}

Here you can see that the code uses the (internal and static) MailConfiguration property of the SmtpClient class that in turn provides access to the From name and address. This name and address value is then passed into the constructor of the MailAddress class which performs the actual validation using its private ParseValue method.

Choosing Best ASP.NET Hosting with HostForLIFE.eu

We know that it is quite hard to find good asp.net hosting in Europe. Why you need to choose us to be your hosting partner?


HostForLIFE.eu is awarded Top No#1 SPOTLIGHT Recommended Hosting Partner by Microsoft (see 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.



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 2016 Hosting, ASP.NET Core 2.2.1 Hosting, ASP.NET MVC 6 Hosting and SQL 2017 Hosting.


Tag cloud

Sign in