European ASP.NET MVC Hosting

BLOG about Latest ASP.NET MVC Hosting and Its Technology - Dedicated to European Windows Hosting Customer

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.



ASP.NET MVC 6 Hosting - HostForLIFE.eu :: How to Authenticate HTML files with ASP.NET MVC ?

clock June 26, 2015 08:08 by author Peter

Today, let me explain about how to Authenticate HTML files with ASP.NET MVC. To Check Html URL is Authenticated or Not Using Asp.net/MVC using the following code:
Coding:
if (Request.RawUrl.ToLower().EndsWith(".html")) 

if (Request.Cookies[".ASPXAUTH"] != null) 

  string value = Request.Cookies[".ASPXAUTH"].Value; 
  if (value == null || value == "") 
  { 
     Response.Redirect("~/Account/LogOn"); 
  } 

else 

  Response.Redirect("~/Account/LogOn"); 

}

The .ASPXAUTH is the Form Authentication Cookies and Account is the Controller. The LogOn is the action. Next step, write the following code in webconfig section:
<buildProviders> 
<add extension=".html" type="System.Web.Compilation.PageBuildProvider" /> 
<add extension=".htm" type="System.Web.Compilation.PageBuildProvider" /> 
</buildProviders> 

<handlers> 
<add name="HTML" path="*.html" verb="GET, HEAD, POST, DEBUG" type="System.Web.UI.PageHandlerFactory" resourceT
ype="Unspecified" requireAccess="Script" /> 
<add name="HTM" path="*.htm" verb="GET, HEAD, POST, DEBUG" type="System.Web.UI.PageHandlerFactory" resourceTyp
e="Unspecified" requireAccess="Script" /> 
</handlers>  

I hope it works for you! Happy coding.

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 Dropzone.js and HTML to Upload File in ASP.NET MVC

clock June 26, 2015 06:19 by author Rebecca

In this article, you can learn how to file upload in ASP.NET MVC using Dropzone.js and HTML5. Dropzone.js is an open source library that provides drag and drop file uploads with image previews. It’s lightweight, doesn’t depend on any other library (like jQuery) and is highly customizable. Follow these steps to upload your file using Dropzone.js and HTML.

Step 1

Before jumping to the project, first you will download the Dropzone.js files. You can download the latest version from the official site here http://www.dropzonejs.com/ and also you can install using the nuget package manage console by the following command Package Manager Console:

PM> Install-Package dropzone

In this tutorial, I'm using the nuget command to install Dropzone.js:

Step 2

Next is file upload implementation. You have to create a default ASP.NET MVC Web Application after you have installed the Dropzone.js. Then, create a bundle for your script file in BundleConfig.cs:

bundles.Add(new ScriptBundle("~/bundles/dropzonescripts").Include(
                     "~/Scripts/dropzone/dropzone.js"));

Step 3

Similarly you can add the Dropzone stylesheet in the BundleConfig.cs:

bundles.Add(new StyleBundle("~/Content/dropzonescss").Include(
                     "~/Scripts/dropzone/css/basic.css",
                     "~/Scripts/dropzone/css/dropzone.css"));

Step 4

Now add the bundle reference in your _Layout page:

Step 5

Everything is fine, you can start writing up the application code. Now go to /Home/Index.cshtml file and Dropzone form in the page using this code:

div class="jumbotron">
    <form action="~/Home/SaveUploadedFile" method="post" enctype="multipart/form-data" class="dropzone" id="dropzoneForm" style="width: 50px; background: none; border: none;">
        <div class="fallback">
            <input name="file" type="file" multiple />
            <input type="submit" value="Upload" />
        </div>
    </form>
</div>

Step 6

Now open the HomeController.cs and add the following code as follows:

public ActionResult SaveUploadedFile()
        {
            bool isSavedSuccessfully = true;
            string fName = "";
                    try{
            foreach (string fileName in Request.Files)
            {
                HttpPostedFileBase file = Request.Files[fileName];
                //Save file content goes here
                fName = file.FileName;
                if (file != null && file.ContentLength > 0)
                {

                    var originalDirectory = new DirectoryInfo(string.Format("{0}Images\\WallImages", Server.MapPath(@"\")));

                    string pathString = System.IO.Path.Combine(originalDirectory.ToString(), "imagepath");

                    var fileName1 = Path.GetFileName(file.FileName);

                    bool isExists = System.IO.Directory.Exists(pathString);

                    if (!isExists)
                        System.IO.Directory.CreateDirectory(pathString);

                    var path = string.Format("{0}\\{1}", pathString, file.FileName);
                    file.SaveAs(path);

                }

            }
                       
           }
           catch(Exception ex)
            {
                isSavedSuccessfully = false;
            }


            if (isSavedSuccessfully)
            {
                return Json(new { Message = fName });
            }
            else
            {
                return Json(new { Message = "Error in saving file" });
            }
        }

Step 7

Then, add the following script to your Index.cshtml page:

//File Upload response from the server
        Dropzone.options.dropzoneForm = {
            init: function () {
                this.on("complete", function (data) {
                    //var res = eval('(' + data.xhr.responseText + ')');
                     var res = JSON.parse(data.xhr.responseText);
                });
            }
        };

Also add the following css:

#dropZone {
        background: gray;
        border: black dashed 3px;
        width: 200px;
        padding: 50px;
        text-align: center;
        color: white;
    }

Now, you have uploaded your file using Dropzone.js and HTML5.

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 Deploy Google ReCAPTCHA in ASP.NET MVC

clock June 22, 2015 06:48 by author Rebecca

Here in this tutorial, I will explain about how to use Google reCAPTCHA in ASP.NET MVC. 

What is reCAPTCHA? reCAPTCHA protects the websites you love from spam and abuse. Google has updated thier reCAPTCHA API  to 2.0 . Now, users can now attest they are human without having to solve a CAPTCHA. Instead with just a single click they’ll confirm they are not a robot and it is called as “No CAPTCHA reCAPTCHA“.  This is how new reCAPTCHA look as follows:

Getting Google ReCAPTCHA

Now, lets create an API key pair for your site at https://www.google.com/recaptcha/intro/index.html and click on Get reCAPTCHA at top of the page and follow the below steps to create an application.

 

Once you have done with registration, the following keys will be generated:

  • Site key : is used to display the widget in your page or code.
  • Secret key: can be used as communication between your site and Google to verify the user response whether the reCAPTCHA is valid or not.

The next is to display the reCAPTCHA widget in your site.

Displaying Widget

We can render the Google reCAPTCHA widget in two ways as:

  1.     Automatically render the widget
  2.     Explicitly render the widget

For this example we will use Automatically render the widget in your page.

First load the script reference:

<script src="https://www.google.com/recaptcha/api.js" async defer></script>

Now, you need generate a DIV element with class name as g-recaptcha and your site key in the data-site key attribute in your webpage to generate reCAPTCHA.

<div class="g-recaptcha" data-sitekey="your_site_key"></div>

Now, implement above code in Home/Index.cshtml view page.

<div class="row">
    <div class="col-md-12">
        <form action="/home/validatecaptcha" method="POST">
            <div class="g-recaptcha" data-sitekey="6LfiS_8SAAAAABvF6ixcyP5MtsevE5RZ9dTorUWr"></div>
            <br />
            <input type="submit" value="Submit">
        </form>
    </div>

 
</div>
@section scripts{
   <script src="https://www.google.com/recaptcha/api.js" async defer></script>
}

Verifying User Response

Once reCAPTCHA is generated  and solved by a end user, a field with g-recaptcha-response will be populated in the html. When ever user submit the form on your site, you can POST the parameter g-recaptcha-response to verify the user response. The following API url is used to verify the user response.

https://www.google.com/recaptcha/api/siteverify?secret=your_secret&response=response_string&remoteip=user_ip_address

In above API url the secret and response parameters are required and where as remoteip is optional. Here secret represents the Secret Key that was generated in the key pair and the repsonse is the g-recaptcha-response that was submitted during the form post. The following is the API JSON response object that we get once the response is submitted.

{
  "success": true|false,
  "error-codes": [...]   // optional
}

Next, you will create an response class to verify the user response:

public class CaptchaResponse
{
    [JsonProperty("success")]
    public bool Success { get; set; }

    [JsonProperty("error-codes")]
    public List<string> ErrorCodes { get; set; }
}

Then, you can create a POST method in Index action in the Home controller to verify the user response.

[HttpPost]
public ActionResult ValidateCaptcha()
{
    var response = Request["g-recaptcha-response"];
    //secret that was generated in key value pair
    const string secret = "YOUR KEY VALUE PAIR";

    var client = new WebClient();
    var reply =
        client.DownloadString(
            string.Format("https://www.google.com/recaptcha/api/siteverify?secret={0}&response={1}", secret, response));

    var captchaResponse = JsonConvert.DeserializeObject<CaptchaResponse>(reply);

    //when response is false check for the error message
    if (!captchaResponse.Success)
    {
        if (captchaResponse.ErrorCodes.Count <= 0) return View();

        var error = captchaResponse.ErrorCodes[0].ToLower();
        switch (error)
        {
            case ("missing-input-secret"):
                ViewBag.Message = "The secret parameter is missing.";
                break;
            case ("invalid-input-secret"):
                ViewBag.Message = "The secret parameter is invalid or malformed.";
                break;

            case ("missing-input-response"):
                ViewBag.Message = "The response parameter is missing.";
                break;
            case ("invalid-input-response"):
                ViewBag.Message = "The response parameter is invalid or malformed.";
                break;

            default:
                ViewBag.Message = "Error occured. Please try again";
                break;
        }
    }
    else
    {
        ViewBag.Message = "Valid";
    }

    return View();
}

That's all! Hope it works for you!

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 Return JavaScript Content from The Controller

clock June 19, 2015 06:50 by author Rebecca

In this tutorial, we're gonna discuss about how to return JavaScript Content from controller action method. I have created a demonstration here, let's follow it step by step.

Step 1

Create a controller action method that returns a view:

public ActionResult OutputJavaScript()
  {
      return View();
  }

View for above action method:

@{
    ViewBag.Title = "OutputJavaScript";
}

<h2>OutputJavaScript</h2>

Try clicking on the link below <br />

@Html.ActionLink("Test JavaScript", "OutputJavaScriptAlert)

Step 2

The view appears in the browser like below:

Notice the 2nd parameter of the ActionLink method, this is the action method name of the controller. When the link “Test JavaScript” is clicked, it calls the OutputJavaScriptAlert action method of the controller.

Step 3

Controller code:

public JavaScriptResult OutputJavaScriptAlert()
  {
      string a = "alert('this is alert')";
      return JavaScript(a);
  }


This action method returns JavaScript content that we get it in the new window or to download as displayed in the above picture (depending on the browser).

In general, these methods are used in the Ajax methods to return partial 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 6 Hosting - HostForLIFE.eu :: How to Validate Input in ASP.NET MVC ?

clock June 18, 2015 08:37 by author Peter

When you develop an app, sometimes your requirements could be that you need to send HTML values from view to the controller. Sometimes, we tend to use HTML Editors to save lots of some information into the view. By default, ASP.NET MVC does not permit a user to submit the HTML content. thus let's have a look at how to submit your form with HTML content.

First step, Open Visual Studio, then choose "New Project", then choose ASP.NET MVC Apps.

Name it the project name, then click OK.

Now, select Internet Application, then click OK.

Next step, make a new Model
ValidateModel.cs
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace ValidateInputDemo.Models
{
    public class ValidateModel
    {
        public string description { get; set; }
    }
}

HomeController.cs
public ActionResult ValidateInput()
{
    return View();
}
[HttpPost]
public ActionResult  ValidateInput(string description)
{
    ValidateModel validateInputModel = new ValidateModel();
    validateInputModel.description = description;
    return View(validateInputModel);
}

Add a new method to your Controller

ValidateInput.cshtml
@model ValidateInputDemo.Models.ValidateModel
@{
       ViewBag.Title = "ValidateInput";
}
@using (@Html.BeginForm("ValidateInput","Home",
FormMethod.Post, new { @id = "form1", @enctype = "multipart/form-data" }))
{
    <label id="lblDescription">Description

     @Html.TextAreaFor(m=>m.description, new {@id="txtDescription",@name="description" })

    <input type="submit" id="bttn_Submit" />
}


You can see in the code above, there is a text area and a submit button, have a glance within the browser. Press F5.

You'll be able to see in the preceding screen, if you type one thing into the description and press Submit then nothing happens.

Now check the following example. Add HTML content into text area.

You'll get the error higher than. This error comes because this is often the security from ASP.NET MVC. For applications, a user cannot send HTML values to the controller, but sometimes we wish to send values to the controller. For resolving this issue, we've the ValidateInput(false) attribute. simply place this into your controller and have a look.
[HttpPost]
[ValidateInput(false)]
public ActionResult  ValidateInput(string description)
{
   ValidateModel validateInputModel = new ValidateModel();
   validateInputModel.description = description;
   return View(validateInputModel);
}

Now press F5. After filling in the HTML attribute press the submit button, you will never get an error. So when you want to work with HTML attributes in your app text area or textboxes, remember to use validateinpute(false) in your ActionMethod.

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.



About HostForLIFE

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

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


Month List

Tag cloud

Sign in