European ASP.NET MVC 4 and MVC 5 Hosting

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

ASP.NET MVC 6 Hosting - HostForLIFE.eu :: How to Use jQuery and Bootstrap to Create Tree View

clock August 26, 2015 05:52 by author Rebecca

This article tells how to create a parent / child tree view in ASP.NET MVC using Bootstrap and jQuery. It is a practical approach so you can create an example in which you will create a parent object. The parent object will have associated child objects.

Step 1

You will create two classes, one is AuthorViewModel and another is BookViewModel. AuthorViewModel is the main class that has an association with the BookViewModel class. In other words each AuthorViewModel class object has a list of BookViewModel class objects. The following is the code snippet for the BookViewModel class.

namespace TreeView.Models  

    public class BookViewModel  
    { 
        public long Id  
        { 
            get; 
            set; 
        } 
        public string Title  
        { 
            get; 
            set; 
        } 
        public bool IsWritten  
        { 
            get; 
            set; 
        } 
    } 

}

The following is the code snippet for the AuthorViewModel class:


    using System.Collections.Generic; 
     
    namespace TreeView.Models { 
        public class AuthorViewModel  
        { 
            public AuthorViewModel()  
            { 
                BookViewModel = new List < BookViewModel > (); 
            } 
            public int Id  
            { 
                get; 
                set; 
            } 
            public string Name  
            { 
                get; 
                set; 
            } 
            public bool IsAuthor  
            { 
                get; 
                set; 
            } 
            public IList < BookViewModel > BookViewModel  
            { 
                get; 
                set; 
            } 
        } 
    }  

Step 2

Now, create a controller “HomeController” that has two action methods for both GET and POST requests. The action method's name is “Index”. The Get request action method returns a tree view in the UI whereas the POST request method gets the posted data from the UI. The following is the code snippet for HomeController.

    using System.Collections.Generic; 
    using System.Linq; 
    using System.Web.Mvc; 
    using TreeView.Models; 
     
    namespace TreeView.Controllers 
    { 
        public class HomeController : Controller 
        { 
            [HttpGet] 
            public ActionResult Index() 
            { 
                List<AuthorViewModel> model = new List<AuthorViewModel>(); 
     
                AuthorViewModel firstAuthor = new AuthorViewModel 
                { 
                    Id = 1, 
                    Name = "John", 
                    BookViewModel = new List<BookViewModel>{ 
                        new BookViewModel{ 
                            Id=1, 
                            Title = "JQuery", 
                            IsWritten = false 
                        }, new BookViewModel{ 
                            Id=1, 
                            Title = "JavaScript", 
                            IsWritten = false 
                        } 
                    } 
                }; 
     
                AuthorViewModel secondAuthor = new AuthorViewModel 
                { 
                    Id = 2, 
                    Name = "Deo", 
                    BookViewModel = new List<BookViewModel>{ 
                        new BookViewModel{ 
                            Id=3, 
                            Title = "C#", 
                            IsWritten = false 
                        }, new BookViewModel{ 
                            Id=4, 
                            Title = "Entity Framework", 
                            IsWritten = false 
                        } 
                    } 
                }; 
                model.Add(firstAuthor); 
                model.Add(secondAuthor); 
                return View("Index", model); 
            } 
     
            [HttpPost] 
            public ActionResult Index(List<AuthorViewModel> model) 
            { 
                List<AuthorViewModel> selectedAuthors = model.Where(a => a.IsAuthor).ToList(); 
                List<BookViewModel> selectedBooks = model.Where(a => a.IsAuthor) 
                                                    .SelectMany(a => a.BookViewModel.Where(b => b.IsWritten)).ToList(); 
                return View(); 
            } 
        }  

The preceding code shows how books are associated with an author in the GET action method and how to get a selected tree node (authors and books) in the POST request.

Step 3

Bootstrap CSS is already added to the application but we write a new custom CSS for the tree view design. The following is the code snippet for the tree CSS.

.tree li { 
        margin: 0px 0;   
        list-style-type: none; 
        position: relative; 
        padding: 20px 5px 0px 5px; 
    } 
     
    .tree li::before{ 
        content: ''; 
        position: absolute;  
        top: 0; 
        width: 1px;  
        height: 100%; 
        right: auto;  
        left: -20px; 
        border-left: 1px solid #ccc; 
        bottom: 50px; 
    } 
    .tree li::after{ 
        content: ''; 
        position: absolute;  
        top: 30px;  
        width: 25px;  
        height: 20px; 
        right: auto;  
        left: -20px; 
        border-top: 1px solid #ccc; 
    } 
    .tree li a{ 
        display: inline-block; 
        border: 1px solid #ccc; 
        padding: 5px 10px; 
        text-decoration: none; 
        color: #666;     
        font-family: 'Open Sans',sans-serif; 
        font-size: 14px; 
        font-weight :600; 
        border-radius: 5px; 
        -webkit-border-radius: 5px; 
        -moz-border-radius: 5px; 
    } 
     
    /*Remove connectors before root*/ 
    .tree > ul > li::before, .tree > ul > li::after{ 
        border: 0; 
    } 
    /*Remove connectors after last child*/ 
    .tree li:last-child::before{  
          height: 30px; 
    } 
     
    /*Time for some hover effects*/ 
    /*We will apply the hover effect the the lineage of the element also*/ 
    .tree li a:hover, .tree li a:hover+ul li a { 
        background: #dd4814; color: #ffffff; border: 1px solid #dd4814; 
    } 
    /*Connector styles on hover*/ 
    .tree li a:hover+ul li::after,  
    .tree li a:hover+ul li::before,  
    .tree li a:hover+ul::before,  
    .tree li a:hover+ul ul::before{ 
        border-color:  #dd4814; 
    } 
    .tree-checkbox{ 
        margin :4px !important; 
    } 
     
      
    .tree:before { 
        border-left:  1px solid #ccc; 
        bottom: 16px; 
        content: ""; 
        display: block; 
        left: 0; 
        position: absolute; 
        top: -21px; 
        width: 1px; 
        z-index: 1; 
    } 
     
    .tree ul:after { 
        border-top: 1px solid #ccc; 
        content: ""; 
        height: 20px; 
        left: -29px; 
        position: absolute; 
        right: auto; 
        top: 37px; 
        width: 34px; 
    } 
    *:before, *:after { 
        box-sizing: border-box; 
    } 
    *:before, *:after { 
        box-sizing: border-box; 
    } 
    .tree { 
        overflow: auto; 
        padding-left: 0px; 
        position: relative; 
    }  

Step 4

Now, create an Index view that renders in the browser and shows the tree view for the author and book. The following is the code snippet for the Index view.

    @model List 
    <TreeView.Models.AuthorViewModel> 
    @section head{ 
    @Styles.Render("~/Content/css/tree.css") 
    } 
        <div class="panel panel-primary"> 
            <div class="panel-heading panel-head">Author Book Tree View</div> 
            <div id="frm-author" class="panel-body"> 
    @using (Html.BeginForm()) 
    { 
     
                <div class="tree"> 
    @for (int i = 0; i < Model.Count(); i++) 
    { 
     
                    <ul> 
                        <li> 
                            <a href="#"> 
    @Html.CheckBoxFor(model => model[i].IsAuthor, new { @class = "tree-checkbox parent", @id = @Model[i].Id }) 
     
                                <label for=@i> 
                                    <strong>Author:</strong> 
    @Html.DisplayFor(model => model[i].Name) 
     
                                </label> 
                            </a> 
                            <ul> 
    @for (int j = 0; j < Model[i].BookViewModel.Count(); j++) 
    { 
    int k = 1 + j; 
    @Html.HiddenFor(model => model[i].BookViewModel[j].Id) 
     
                                <li> 
                                    <a href="#"> 
    @Html.CheckBoxFor(model => model[i].BookViewModel[j].IsWritten, new { @class = "tree-checkbox node-item", @iid = i + "" + j }) 
     
                                        <label for=@i@j> 
                                            <strong>Book @(k):</strong> @Html.DisplayFor(model => model[i].BookViewModel[j].Title) 
                                        </label> 
                                    </a> 
                                </li> 
     
    } 
     
                            </ul> 
                        </li> 
                    </ul> 
    } 
     
                </div> 
                <div class="form-group"> 
                    <div class="col-lg-9"></div> 
                    <div class="col-lg-3"> 
                        <button class="btn btn-success" id="btnSubmit" type="submit"> 
    Submit 
    </button> 
                    </div> 
                </div> 
    } 
     
            </div> 
        </div> 
     
    @section scripts{ 
    @Scripts.Render("~/Scripts/tree.js") 
    }

Step 5

Thereafter, you can create the JavaScript file tree.js with the following code:

 

(function($)  
    { 
        function Tree() { 
            var $this = this; 
     
            function treeNodeClick()  
            { 
                $(document).on('click', '.tree li a input[type="checkbox"]', function() { 
                    $(this).closest('li').find('ul input[type="checkbox"]').prop('checked', $(this).is(':checked')); 
                }).on('click', '.node-item', function() { 
                    var parentNode = $(this).parents('.tree ul'); 
                    if ($(this).is(':checked')) { 
                        parentNode.find('li a .parent').prop('checked', true); 
                    } else { 
                        var elements = parentNode.find('ul input[type="checkbox"]:checked'); 
                        if (elements.length == 0) { 
                            parentNode.find('li a .parent').prop('checked', false); 
                        } 
                    } 
                }); 
            }; 
     
            $this.init = function() { 
                treeNodeClick(); 
            } 
        } 
        $(function() { 
            var self = new Tree(); 
            self.init(); 
        }) 
    }(jQuery))  

Output

This figure shows the parent child (author-book) tree view:

HostForLIFE.eu ASP.NET MVC 6 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.



ASP.NET MVC 6 Hosting - HostForLIFE.eu :: How to Use Chart Helper to Display Graphical Data

clock August 20, 2015 06:24 by author Rebecca

In this tutorial, you will learn how to display data in graphical form using the Chart Helper in ASP.NET MVC. The “Chart Helper” can create chart images of different types with many formatting options and labels. It can create standard charts like area charts, bar charts, column charts, line charts, and pie charts, along with more specialized charts like stock charts. The data you display in a chart can be from an array, from the results returned from a database, or from data that’s in an XML file.

Step 1

Lets create new ASP.NET MVC application and name it to “MvcChartDemo” then add the below ProductSales model and DbContext class inside Models folder.

public class ProductSales
{
    public int Id { get; set; }

    public string Name { get; set; }

    public int Sales { get; set; }
}

public class SalesContext : DbContext
{
    public DbSet ProductSales { get; set; }
}

Step 2

Next, add the below connectionStrings in Web.config file:

<connectionStrings>
     <add name="SalesContext" providerName="System.Data.SqlClient" connectionString="Data Source=./SQLExpress;Initial Catalog=Test;Integrated Security=SSPI;" />
</connectionStrings>

Step 3

Next, create HomeController and add the Index action method. Also, create the /Views/Home/Index.cshtml view and replace the content with the following code:

Index.cshtml

@model IEnumerable<MvcChartDemo.Models.ProductSales>

@{
   ViewBag.Title = "Chart Helper Demo";
}

<h2>Chart Helper Demo</h2>
@{
var key = new Chart(width: 600, height: 400)
                  .AddTitle("Product Sales")
                  .AddSeries("Default",
                             xValue: Model, xField: "Name",
                             yValues: Model, yFields: "Sales")
                  .Write();
}

Here, we create the Chart using the following Chart Helpers method.

@{
var key = new Chart(width: 600, height: 400)
                 .AddTitle("Product Sales")
                 .AddSeries("Default",
                             xValue: Model, xField: "Name",
                             yValues: Model, yFields: "Sales")
                 .Write();
}

The code first creates a new chart and sets its width and height. You specify the chart title by using the AddTitle method. To add data, you use the AddSeries method. In this example, you use the name, xValue, and yValues parameters of the AddSeries method. The name parameter is displayed in the chart legend. The xValue parameter contains an array of data that is displayed along the horizontal axis of the chart. The yValues parameter contains an array of data this is used to plot the vertical points of the chart.

The Write method actually renders the chart. In this case, because you did not specify a chart type, the Chart helper renders its default chart, which is a column chart.

Now, run the application and you will see below output:

Step 4

You can change the Chart Type by defines chartType parameter of chart inside AddSeries method:

@{
var key = new Chart(width: 600, height: 400)
                  .AddTitle("Product Sales")
                  .AddSeries(chartType: "Pie",
                             xValue: Model, xField: "Name",
                             yValues: Model, yFields: "Sales")
                  .Write();
}

HostForLIFE.eu ASP.NET MVC 6 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.

 



HostForLIFE.eu Launches Umbraco 7.2.8 Hosting

clock August 19, 2015 06:59 by author Peter

HostForLIFE.eu, a leading web hosting provider, has leveraged its gold partner status with Microsoft to launch its latest Umbraco 7.2.8 Hosting support

HostForLIFE.eu, a leading Windows web hosting provider with innovative technology solutions and a dedicated professional services team, today announced the support for Umbraco 7.2.8 hosting plan due to high demand of Umbraco users in Europe. The company has managed to build a strong client base in a very short period of time. It is known for offering ultra-fast, fully-managed and secured services in the competitive market.

HostForLIFE.eu hosts its servers in top class data centers that is located in Amsterdam (NL), London (UK), Paris (FR), Frankfurt (DE) and Seattle (US) to guarantee 99.9% network uptime. All data center feature redundancies in network connectivity, power, HVAC, security and fire suppression. All hosting plans from HostForLIFE.eu include 24×7 support and 30 days money back guarantee. HostForLIFE Umbraco hosting plan starts from just as low as €3.00/month only and this plan has supported ASP.NET 4.5, ASP.NET MVC 5/6 and SQL Server 2012/2014.

Umbraco 7.2.8 is a fully-featured open source content management system with the flexibility to run anything from small campaign or brochure sites right through to complex applications for Fortune 500's and some of the largest media sites in the world. Umbraco was sometimes unable to read the umbraco.config file, making Umbraco think it had no content and showing a blank page instead (issue U4-6802), this is the main issue fixed in this release. This affects people on 7.2.5 and 7.2.6 only. 7.2.8 also fixes a conflict with Courier and some other packages.

Umbraco 7.2.8 Hosting is strongly supported by both an active and welcoming community of users around the world, and backed up by a rock-solid commercial organization providing professional support and tools. Umbraco 7.2.8 can be used in its free, open-source format with the additional option of professional tools and support if required. Not only can you publish great multilingual websites using Umbraco 7.2.8 out of the box, you can also build in your chosen language with our multilingual back office tools.

Further information and the full range of features Umbraco 7.2.8 Hosting can be viewed here: http://hostforlife.eu/European-Umbraco-728-Hosting

About HostForLIFE.eu

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

HostForLIFE.eu is awarded Top No#1 SPOTLIGHT Recommended Hosting Partner by Microsoft (see http://www.asp.net/hosting/hostingprovider/details/953). Their 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, they have also won several awards from reputable organizations in the hosting industry and the detail can be found on their official website.



ASP.NET MVC 6 Hosting - HostForLIFE.eu :: How to Use Adaptor to Create 3D Image Slider in ASP.NET MVC

clock August 18, 2015 06:20 by author Rebecca

In this article, I will tell you how create a Responsive jQuery 3D Content Image Slider in ASP.NET MVC using Adaptor. You can find the plugin here. Adaptor content slider aims to provide a simple interface for developers to create cool 2D or 3D slide animation transitions.

Follow these steps to create 3D content image slider in ASP.NET MVC:

Step 1

Create a new project in ASP.NET MVC named JQueryImageSlider. After that copy the css, img, js folders and paste in JQueryImageSlider project.

 

Step 2

In the _Layout.cshtml page reference the Adaptor 3D slider files:

Step 3

Now create class models ImageModel that holds images from database:

public class ImageModel
{
    public int ImageID { get; set; }
    public string ImageName { get; set; }
    public string ImagePath { get; set; }
}

Step 4

Get the images list from the repository and bind it to slider:

public ActionResult Index()
{
   //Bind it from the repository
   List imageList = new List();
   imageList.Add(new ImageModel { ImageID = 1, ImageName = "Image 1", ImagePath = "/img/the-battle.jpg" });
   imageList.Add(new
      ImageModel { ImageID = 2, ImageName = "Image 2", ImagePath = "/img/hiding-the-map.jpg"
   });
   imageList.Add(new ImageModel { ImageID = 3, ImageName = "Image 3", ImagePath = "/img/theres-the-buoy.jpg" });
   imageList.Add(new ImageModel { ImageID = 4, ImageName = "Image 4", ImagePath = "/img/finding-the-key.jpg" });
   imageList.Add(new ImageModel { ImageID = 5, ImageName = "Image 5", ImagePath = "/img/lets-get-out-of-here.jpg"});
   return View(imageList);
}

Step 5

In the View page add the following code:

<div id="viewport-shadow">
    <a href="#" id="prev" title="go to the next slide"></a>
    <a href="#" id="next" title="go to the next slide"></a>
    <div id="viewport">
        <div id="box">
            @*Bind images here*@
            @foreach (var item in Model)
            {
                <figure class="slide">
                    <img [email protected]>
                </figure>
            }


        </div>
    </div>
    <div id="time-indicator"></div>
</div>

@* here we are binding the slider controls navigation *@
<footer>
    <nav class="slider-controls">
        <ul id="controls">
            @{int index = 0;}
            @foreach (var item in Model)
            {
               
                 string cssClass = index.Equals(0) ? "goto-slide current" : "goto-slide";

                 <li><a class="@cssClass" href=" #" data-slideindex="@index"></a></li>
                 index= index +1;
            }
         
        </ul>
    </nav>
</footer>

Step 6

We can also add the caption for image slider using the figcaption tag:

<figure class="slide">
    <img [email protected] class="img-responsive">
    <figcaption>Static Caption</figcaption>
</figure>

HostForLIFE.eu ASP.NET MVC 6 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.



ASP.NET MVC 6 Hosting - HostForLIFE.eu :: How to Use SignalR & SQL Dependency to Display Updates from SQL Server

clock August 13, 2015 06:05 by author Rebecca

In this post, you will learn how to display real time updates from the  SQL Server  by using SignalR  and SQL Dependency in ASP.NET MVC.

The following are the steps that we need to enable in the SQL Server first.

Step 1 - Enable Service Broker on the database

The following is the query that need to enable the service broker:

ALTER DATABASE BlogDemos SET ENABLE_BROKER WITH ROLLBACK IMMEDIATE ;

Step 2 - Add Connection string to the Web.Config file

<add name=”DefaultConnection” connectionString=”Server=servername;Database=databasename;User Id=userid;Password=password;” providerName=”System.Data.SqlClient” />

Step 3 - Enable SQL Dependency

In Global.asax start the SQL Dependency in App_Start() event and Stop SQL dependency in the Application_End() event:

public class MvcApplication : System.Web.HttpApplication
    {
        string connString = ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;

        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);
            GlobalConfiguration.Configure(WebApiConfig.Register);
            //Start SqlDependency with application initialization
            SqlDependency.Start(connString);
        }

        protected void Application_End()
        {
            //Stop SQL dependency
            SqlDependency.Stop(connString);
        }
    }

Step 4 - Install SignalR from The Nuget

Run the following command in the Package Manager Console:

Install-Package Microsoft.AspNet.SignalR

Step 5 - Create SignalR Hub Class

Create MessagesHub class in the Hubs folder:

public class MessagesHub : Hub
    {
        private static string conString = ConfigurationManager.ConnectionStrings["DefaultConnection"].ToString();
        public void Hello()
        {
            Clients.All.hello();
        }

        [HubMethodName("sendMessages")]
        public static void SendMessages()
        {
            IHubContext context = GlobalHost.ConnectionManager.GetHubContext<MessagesHub>();
            context.Clients.All.updateMessages();
        }  
    }

Step 6 - Get the  Data from the Repository

Create MessagesRepository to get the messages from the database when data is updated.

public class MessagesRepository
    {
        readonly string _connString = ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;

        public IEnumerable<Messages> GetAllMessages()
        {
            var messages = new List<Messages>();
            using (var connection = new SqlConnection(_connString))
            {
                connection.Open();
                using (var command = new SqlCommand(@"SELECT [MessageID], [Message], [EmptyMessage], [Date] FROM [dbo].[Messages]", connection))
                {
                    command.Notification = null;

                    var dependency = new SqlDependency(command);
                    dependency.OnChange += new OnChangeEventHandler(dependency_OnChange);

                    if (connection.State == ConnectionState.Closed)
                        connection.Open();

                    var reader = command.ExecuteReader();

                    while (reader.Read())
                    {
                        messages.Add(item: new Messages { MessageID = (int)reader["MessageID"], Message = (string)reader["Message"], EmptyMessage =  reader["EmptyMessage"] != DBNull.Value ? (string) reader["EmptyMessage"] : "", MessageDate = Convert.ToDateTime(reader["Date"]) });
                    }
                }
             
            }
            return messages;
          
           
        }

        private void dependency_OnChange(object sender, SqlNotificationEventArgs e)
        {
            if (e.Type == SqlNotificationType.Change)
            {
                MessagesHub.SendMessages();
            }
        }
    }

Step 7 - Register SignalR at Startup Class

Add the following code:

app.MapSignalR();

Step 8 - View Page

Create div messagesTable that will append the table data from the database:

<div class="row">
    <div class="col-md-12">
       <div id="messagesTable"></div>
    </div>
</div>

Now Add the SignalR related scripts in the page >> getAllMessages is a function that return the partialview data and bind it into the messagesTable div.

<script src="/Scripts/jquery.signalR-2.1.1.js"></script>
 <!--Reference the autogenerated SignalR hub script. -->
    <script src="/signalr/hubs"></script>

<script type="text/javascript">
    $(function () {
        // Declare a proxy to reference the hub.
        var notifications = $.connection.messagesHub;
      
        //debugger;
        // Create a function that the hub can call to broadcast messages.
        notifications.client.updateMessages = function () {
            getAllMessages()
          
        };
        // Start the connection.
        $.connection.hub.start().done(function () {
            alert("connection started")
            getAllMessages();
        }).fail(function (e) {
            alert(e);
        });
    });


    function getAllMessages()
    {
        var tbl = $('#messagesTable');
        $.ajax({
            url: '/home/GetMessages',
            contentType: 'application/html ; charset:utf-8',
            type: 'GET',
            dataType: 'html'
        }).success(function (result) {
            tbl.empty().append(result);
        }).error(function () {
           
        });
    }
</script>

Step 9 - Create Partial View Page

Create a partial view _MessagesList.cshtml that returns all the messages:

@model IEnumerable<SignalRDbUpdates.Models.Messages>

<p>
    @Html.ActionLink("Create New", "Create")
</p>
<table class="table">
    <tr>
        <th>@Html.DisplayNameFor(model => model.MessageID)</th>
        <th>
            @Html.DisplayNameFor(model => model.Message)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.EmptyMessage)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.MessageDate)
        </th>
       
    </tr>

@foreach (var item in Model) {
    <tr>
        <td>
            @Html.DisplayFor(modelItem => item.MessageID)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.Message)
        </td>
        <th>
            @Html.DisplayFor(modelItem => item.EmptyMessage)
        </th>
        <td>
            @Html.DisplayFor(modelItem => item.MessageDate)
        </td>
       
    </tr>
}
</table>

Step 10 - Set Up the Database

Create the database called blogdemos and run the following script:

USE [BlogDemos]
GO
/****** Object:  Table [dbo].[Messages]    Script Date: 10/16/2014 12:43:55 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Messages](
    [MessageID] [int] IDENTITY(1,1) NOT NULL,
    [Message] [nvarchar](50) NULL,
    [EmptyMessage] [nvarchar](50) NULL,
    [Date] [datetime] NULL,
 CONSTRAINT [PK_Messages] PRIMARY KEY CLUSTERED
(
    [MessageID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
ALTER TABLE [dbo].[Messages] ADD  CONSTRAINT [DF_Messages_Date]  DEFAULT (getdate()) FOR [Date]
GO

Step 11 - Run the project

When eve data is inserted into the table the dependency_OnChange method will fire.

HostForLIFE.eu ASP.NET MVC 6 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.



ASP.NET MVC 6 Hosting - HostForLIFE.eu :: How to Create SignalR Database Update Notifications using SQL Dependency in ASP.NET MVC ?

clock August 6, 2015 09:09 by author Peter

In this article, we will learn how to create SignalR database update notifications using SQL dependency in ASP.NET MVC 6. The following are the steps that we want to enable within the SQL Server first.
1. Enable Service Broker on the database
The following is the query that require to enable the service broker:
ALTER DATABASE BlogDemos SET ENABLE_BROKER WITH ROLLBACK IMMEDIATE;

2. Now Add Connection string to the Web.Config file and the following code:
<add name=”DefaultConnection” connectionString=”Server=servername;Database=databasename;User Id=userid;Password=password;” providerName=”System.Data.SqlClient” />

3. Next step, Enable the SQL Dependency
In Global.asax start the SQL Dependency in App_Start() event and Stop SQL dependency in the Application_End() event and write the following code:
public class MvcApplication : System.Web.HttpApplication
{
string connString = ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;

protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
GlobalConfiguration.Configure(WebApiConfig.Register);
//Start SqlDependency with application initialization
SqlDependency.Start(connString);
}

protected void Application_End()
{
//Stop SQL dependency
SqlDependency.Stop(connString);
}
}


4. Install SignalR from the Nuget
Run the following command in the Package Manager Console
Install-Package Microsoft.AspNet.SignalR

5. And then, Make a SignalR Hub Class
Make MessagesHub class in the Hubs folder
public class MessagesHub : Hub
{
private static string conString = ConfigurationManager.ConnectionStrings["DefaultConnection"].ToString();
public void Hello()
{
Clients.All.hello();
}


[HubMethodName("sendMessages")]
public static void SendMessages()
{
IHubContext context = GlobalHost.ConnectionManager.GetHubContext<MessagesHub>();
context.Clients.All.updateMessages();
}
}


6. Get the Data from the Repository
Make MessagesRepository to get the messages from the database when data is updated.
public class MessagesRepository
{
readonly string _connString = ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;

public IEnumerable<Messages> GetAllMessages()
{
var messages = new List<Messages>();
using (var connection = new SqlConnection(_connString))
{
connection.Open();
using (var command = new SqlCommand(@"SELECT [MessageID], [Message], [EmptyMessage], [Date] FROM [dbo].[Messages]", connection))
{
command.Notification = null;

var dependency = new SqlDependency(command);
dependency.OnChange += new OnChangeEventHandler(dependency_OnChange);

if (connection.State == ConnectionState.Closed)
    connection.Open();
var reader = command.ExecuteReader();
while (reader.Read())
{
    messages.Add(item: new Messages { MessageID = (int)reader["MessageID"], Message = (string)reader["Message"], EmptyMessage =  reader["EmptyMessage"] != DBNull.Value ? (string) reader["EmptyMessage"] : "", MessageDate = Convert.ToDateTime(reader["Date"]) });
}
}

}
return messages;
}

private void dependency_OnChange(object sender, SqlNotificationEventArgs e)
{
if (e.Type == SqlNotificationType.Change)
{
MessagesHub.SendMessages();
}
}

7. Next step, you must Register SignalR at startup class
Write the following code:
app.MapSignalR();

8. View Page
Create div messagesTable that will append the table data from the database
<div class="row">
<div class="col-md-12">
   <div id="messagesTable"></div>
</div>
</div>


Now Add the SignalR related scripts in the page.
getAllMessages is a function that return the partialview data and bind it into the messagesTable div.
<script src="/Scripts/jquery.signalR-2.1.1.js"></script>
<!--Reference the autogenerated SignalR hub script. -->
<script src="/signalr/hubs"></script>

<script type="text/javascript">
$(function () {
    // Declare a proxy to reference the hub.
    var notifications = $.connection.messagesHub;
  
    //debugger;
    // Create a function that the hub can call to broadcast messages.
    notifications.client.updateMessages = function () {
        getAllMessages()
      
    };
    // Start the connection.
    $.connection.hub.start().done(function () {
        alert("connection started")
        getAllMessages();
    }).fail(function (e) {
        alert(e);
    });
});
function getAllMessages()
{
    var tbl = $('#messagesTable');
    $.ajax({
        url: '/home/GetMessages',
        contentType: 'application/html ; charset:utf-8',
        type: 'GET',
        dataType: 'html'
    }).success(function (result) {
        tbl.empty().append(result);
    }).error(function () {
       
    });
}
</script>


9. Create Partial View Page
Create a partial view _MessagesList.cshtml that returns all the messages.
@model IEnumerable<SignalRDbUpdates.Models.Messages>

<p>
@Html.ActionLink("Create New", "Create")
</p>
<table class="table">
<tr>
    <th>@Html.DisplayNameFor(model => model.MessageID)</th>
    <th>
        @Html.DisplayNameFor(model => model.Message)
    </th>
    <th>
        @Html.DisplayNameFor(model => model.EmptyMessage)
    </th>
    <th>
        @Html.DisplayNameFor(model => model.MessageDate)
    </th>
   
</tr>

@foreach (var item in Model) {
<tr>
    <td>
        @Html.DisplayFor(modelItem => item.MessageID)
    </td>
    <td>
        @Html.DisplayFor(modelItem => item.Message)
    </td>
    <th>
        @Html.DisplayFor(modelItem => item.EmptyMessage)
    </th>
    <td>
        @Html.DisplayFor(modelItem => item.MessageDate)
    </td>
   
</tr>
}
</table>

10. Set Up the Database
Create the database called blogdemos and run the following script:
USE [BlogDemos]
GO

/****** Object:  Table [dbo].[Messages]    ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE TABLE [dbo].[Messages](
[MessageID] [int] IDENTITY(1,1) NOT NULL,
[Message] [nvarchar](50) NULL,
[EmptyMessage] [nvarchar](50) NULL,
[Date] [datetime] NULL,
CONSTRAINT [PK_Messages] PRIMARY KEY CLUSTERED
(
[MessageID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
ALTER TABLE [dbo].[Messages] ADD  CONSTRAINT [DF_Messages_Date]  DEFAULT (getdate()) FOR [Date]
GO


11. Let's Run the project
When eve data is inserted into the table the dependency_OnChange method will fire.



HostForLIFE.eu Launches nopCommerce 3.60 Hosting

clock July 14, 2015 10:52 by author Peter

HostForLIFE.eu, a leading web hosting provider, has leveraged its gold partner status with Microsoft to launch its latest NopCommerce 3.60 Hosting support

European Recommended Windows and ASP.NET Spotlight Hosting Partner, HostForLIFE.eu, has announced the availability of new hosting plans that are optimized for the latest update of the NopCommerce 3.60 hosting technology.

HostForLIFE.eu supports NopCommerce 3.60 hosting on their latest Windows Server and this service is available to all their new and existing customers. nopCommerce 3.60 is a fully customizable shopping cart. It's stable and highly usable. nopCommerce is an open source ecommerce solution that is ASP.NET (MVC) based with a MS SQL 2008 (or higher) backend database. Their easy-to-use shopping cart solution is uniquely suited for merchants that have outgrown existing systems, and may be hosted with your current web hosting. It has everything you need to get started in selling physical and digital goods over the internet.

HostForLIFE.eu Launches nopCommerce 3.60 Hosting

nopCommerce 3.60 is a fully customizable shopping cart. nopCommerce 3.60 provides new clean default theme. The theme features a clean, modern look and a great responsive design. The HTML have been refactored, which will make the theme easier to work with and customize , predefined (default) product attribute values. They are helpful for a store owner when creating new products. So when you add the attribute to a product, you don't have to create the same values again , Base price (PAngV) support added. Required for German/Austrian/Swiss users, “Applied to manufacturers” discount type and Security and performance enhancements.

HostForLIFE.eu hosts its servers in top class data centers that is located in Amsterdam, London, Paris, Seattle (US) and Frankfurt (Germany) to guarantee 99.9% network uptime. All data center feature redundancies in network connectivity, power, HVAC, security, and fire suppression. All hosting plans from HostForLIFE.eu include 24×7 support and 30 days money back guarantee.

All hosting plans from HostForLIFE.eu include 24×7 support and 30 days money back guarantee. The customer can start hosting their NopCommerce 3.60 site on their environment from as just low €3.00/month only. HostForLIFE.eu is a popular online Windows based hosting service provider catering to those people who face such issues. The company has managed to build a strong client base in a very short period of time. It is known for offering ultra-fast, fully-managed and secured services in the competitive market. Their powerful servers are specially optimized and ensure NopCommerce 3.60 performance.

For more information about this new product, please visit http://hostforlife.eu/European-nopCommerce-36-Hosting



ASP.NET MVC 6 Hosting - HostForLIFE.eu :: How to Bind & Sort Grid with Jquery in ASP.NET MVC 6?

clock July 14, 2015 09:22 by author Peter

In this tutorial, I will show you How to Bind & Sort Grid with Jquery in ASP.NET MVC 6. You can sort by clicking on column names & paging by selecting the page size and the click on arrows first arrow is to move to first page,click on arrows second arrow is to move to previous page,click on arrows third arrow is to move to next page and click on arrows fourth arrow is to move to last page. First step, you should create a MVC app and make model Users.cs. Now write the following code:

Model: Users.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using System.Data.SqlClient;
using System.ComponentModel.DataAnnotations;
namespace MvcMovieStore.Models
{
public class Users
{
DataSet ds;
[Required]
[Display(Name = "ID")]
public int ID { get; set; }

[Required]
[Display(Name = "UserName")]
public string UserName { get; set; }

[Required]
[Display(Name = "Gender")]
public string Gender { get; set; }

[Required]
[Display(Name = "Country")]
public string Country { get; set; }

public DataTable GetUsers()
{
try
{
ds = new DataSet();
     SqlConnection con = new qlConnection(System.Configuration.ConfigurationManager.
ConnectionStrings["con"].ConnectionString);
SqlDataAdapter sqlAda = new SqlDataAdapter("Select User_Id,UserName,Country,Gender from User_Details", con);
sqlAda.Fill(ds);
return ds.Tables[0];
}
catch (Exception err)
{
throw err;
}
}

}
}


Controller: UsersController.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Data;
using MvcMovieStore.Models;

namespace MvcMovieStore.Controllers
{
public class UsersController : Controller
{
//
// GET: /Users/
public ActionResult Index()
{
DataTable dtGrid = new DataTable();
Users objUser = new Users();
dtGrid = objUser.GetUsers();

List<Users> Gridd = new List<Users>();

foreach (DataRow dr in dtGrid.Rows)
{
    Users users = new Users();
    users.ID = Convert.ToInt32(dr["User_Id"]);
    users.UserName = dr["UserName"].ToString();
    users.Country = dr["Country"].ToString();
    users.Gender = dr["Gender"].ToString();

    Gridd.Add(users);
}
return View("Index", Gridd);
}
}
}


View: Index.aspx
<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master"
Inherits="System.Web.Mvc.ViewPage<IEnumerable<MvcMovieStore.Models.Users>>"%>
<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
Binding and Sorting Grid in ASP.NET MVC 2.0 using JQuery
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js">
</script>
<script src="../../Scripts/jquery.tablesorter.min.js" type="text/javascript"></script>
<script src="../../Scripts/jquery.tablesorter.pager.js" type="text/javascript"></script>
<style type="text/css">
table.tablesorter thead tr .header
{
    background-color: #000000;
    color: #fff;
    cursor: pointer;
    padding: 5px 15px;
}
img{width=20px;height:20px;}
</style>
<h2>
Index</h2>
<%-- only for sorting
<script type="text/javascript">
$(document).ready(function () {
    $("#userTable").tablesorter();
});
</script>--%>
<%--Sorting and paging --%>
<script type="text/javascript">
$(function () {
    $("#userTable")
          .tablesorter({ widthFixed: true })
          .tablesorterPager({ container: $("#pager") });
    $("#userTable").bind("sortStart", function () {
    }).bind("sortEnd", function () {
    });

    //Hide/delete row on click.
    $("#userTable img").click(function () { $(this).parent().parent().hide(); });
});
</script>
<p>
<%: Html.ActionLink("Create New", "Create") %>
</p>
<table id="userTable" class="tablesorter" style="height: 100%">
<thead>
<tr>
    <th>
        ID
    </th>
    <th>
        UserName
    </th>
    <th>
        Gender
    </th>
    <th>
        Country
    </th>
    <th>
        Edit
    </th>
    <th>
        Details
    </th>
    <th>
        Delete
    </th>
</tr>
</thead>
<% foreach (var item in Model)
   { %>
<tr>
    <td>
        <%: item.ID %>
    </td>
    <td>
        <%: item.UserName %>
    </td>
    <td>
        <%: item.Gender %>
    </td>
    <td>
        <%: item.Country %>
    </td>
    <td>
        <%: Html.ActionLink("Edit", "Edit", new {id=item.ID  }) %>
    </td>
    <td>
        <%: Html.ActionLink("Details", "Details", new { id = item.ID })%>
    </td>
    <td>
        <%: Html.ActionLink("Delete", "Delete", new { id = item.ID })%>
    </td>
</tr>
<% } %>
</table>
<div id="pager" class="pager">
<br />
<img src="../../Content/arrow-left.png" class="first"  />
<img src="../../Content/arrow-left.png" class="prev"  />
<input type="text" class="pagedisplay" />
<img src="../../Content/arrow-right.png" class="next"   />
<img src="../../Content/arrow-right.png" class="last"   />
<select class="pagesize">
    <option selected="selected" value="1">1</option>
    <option value="2">2</option>
    <option value="3">3</option>
    <option value="4">4</option>
</select>
</div>
</asp:Content>

HostForLIFE.eu ASP.NET MVC 6 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.



ASP.NET MVC 5 Hosting - HostForLIFE.eu :: Tracking Error with Log4net Library in ASP.NET MVC

clock June 29, 2015 08:48 by author Peter

Logging may be a method of tracking/monitoring what's happening when an application is in progress/running. Log records are going to be most required things when one thing goes wrong in your application, be it Windows Forms, mobile or web applications.

Here I will be able to be walking through the basic steps in implementing work functionality using Apache log4net framework in an ASP.NET MVC 5 application. I'm using Visual Studio express 2013 for web as my development environment targeting .NET framework 4.5. Open Visual Studio 2013 for web and build a new ASP.NET web application selecting MVC template.

Here in this demo application, we are going to use Apache Log4net framework for logging. We'd like to add reference of Log4net DLL using NuGet package manager. In VS 2013 solution explorer and then Right click on Reference and select Manage NuGet Packages. Search for ‘log4net’ and Install.

Once installation is successful, we are able to see the log4net DLL added beneath the solution explorer Reference section as shown below:

Next, we'd like to piece our application to use log4net logging framework. Add the below line in your startup.cs get into ASP.NET MVC5 solution folder. The below line of code provides data about log4net configuration file.
[assembly: log4net.Config.XmlConfigurator(ConfigFile = "Web.config", Watch = true)]

Now, write the following code to web.config file:
<configSections>
<!-- Add log4net config section-->
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler,     log4net" />
</configSections>

<log4net debug="true">
<appender name="RollingLogFileAppender" type="log4net.Appender.RollingFileAppender">
<file value="logs\log.txt" />
<appendToFile value="true" />
<rollingStyle value="Size" />
<maxSizeRollBackups value="10" />
<maximumFileSize value="10MB" />
<staticLogFileName value="true" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%-5p %d %5rms %-22.22c{1} %-18.18M - %m%n" />
</layout>
</appender>
<root>
<level value="DEBUG" />
<appender-ref ref="RollingLogFileAppender" />
</root>
</log4net>


Modify the Global.asax.cs and add the following code inside Application_Start() method.
log4net.Config.XmlConfigurator.Configure(new FileInfo(Server.MapPath("~/Web.config")));

Now our log4net library is ready to use with MVC5 application.
Add logger declaration in classes for which we want to make logs as below:
readonly log4net.ILog logger = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

Use the following logger.Error() method to log messages when needed as you can see on the below picture:

Run an application and that we will see the log file generated underneath the logs folder under the application root directory as configured in the web config file.

HostForLIFE.eu ASP.NET MVC 5 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.



ASP.NET MVC Hosting - HostForLIFE.eu :: How to List Data from Database Into Grid

clock June 27, 2015 11:25 by author Rebecca

In this article, you are going to learn how to quickly list the data from the database into Grid in ASP.NET MVC. We all know the benefit and beauty of GridView in ASP.NET Web Form. This is the best data control in ASP.NET MVC to quickly list the data from the database without specifying columns, table format etc. This was missing in ASP.NET MVC as it has not server side control like GridView.

The good thing here is that you can still use the GridView of System.Web.UI.WebControls namespace in ASP.NET MVC and populate with data and get it rendered in the ASP.NET MVC view. Here is how the action method looks like:

The Controller

public ActionResult ListDataInGridView()

        {

            System.Web.UI.WebControls.GridView gView =

                new System.Web.UI.WebControls.GridView();

            gView.DataSource = db.PersonalDetails.ToList();

            gView.DataBind();


            using (System.IO.StringWriter sw = new System.IO.StringWriter())

            {

                using (System.Web.UI.HtmlTextWriter htw = new System.Web.UI.HtmlTextWriter(sw))

                {

                    gView.RenderControl(htw);

                    ViewBag.GridViewString = sw.ToString();

                }

            }

            return View();

        }

In this action method, you have first instantiated the GridView control and set its data source and called DataBind method that will bind the data from the data source. 

Next, you have to use StringWriter and HtmlTextWriter to render the GridView content string into the StringWriter. The same is being set to the ViewBag.GridViewString.

The View

The View looks like below that simply use @Html.Raw method to write the content of the ViewBag:

@{ ViewBag.Title = "ListDataInGridView"; }

<h2>List Data In GridView</h2>

@Html.Raw(ViewBag.GridViewString)

Using @Html.Raw method is important as without this, it will simply render the HTML encoded characters of the GridView content string.

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.



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