Integrate DISQUS For Comment Management In MVC

3. September 2011 18:02

API ASP.NET MVC 

I have been working on a MVC project which I will be using to save and manage all my code snippets. I get this plan in my head when my 160GB of HDD got crashed which holds most of my work and code. I started writing the web application in web forms and almost got it completed, but eventually changed my mind and started writing the application from scratch in MVC 3 with Razor view engine.

As I will be making this application online, I am sure to receive some comments when I share my code with others. To know what people thing about the code I published, I must have a commenting system for my application to know what people think. Instead of writing my own comment mechanism I would rather want to go with DISQUS commenting system. For my blog I am not using DISQUS, but for this application I will use DISQUS as it will save my time and is also a reliable way to manage comments.

Working with MVC is fun and even more when you are working with helper classes. Read my blog post on Working with Microsoft Web Helpers in ASP.NET to know more about helper classes and their features and how they can save your time in developing applications. I am going to show you how you can integrate DISQUS commenting system in your MVC application with ease. To get started, register a DISQUS account

Create a new MVC project in Visual Studio and without any delay go to NuGet console and type in the below command to add the DISQUS helper class.

 
The DISQUS helper class has 2 methods which we will be going to use.
  • Initialize: This method will help us to initialize the commenting system. It accepts your short forum name as a parameter which you have created at the time of creating your account at DISQUS.
  • ShowComments: This method accepts the name of the page.
To initialize DISQUS, we need to set the Initialize method in _ViewStart.cshtml file. You can find this file under Views folder. Make sure that this is a first line in the file as we have to initialize before the layout of the page gets rendered.
@{
    Disqus.Initialize("shortforumname");
 }
Now as we have initialized, we can show the comments on the page. To show the comments on the page we will use the ShowComments method and pass the page name in the parameter. Just to be more precise about this parameter, I would like to point out that on a forum, blog or on a website every page has a unique name or forum post id or blog post and the parameter that we are going to pass to this method should also be the same unique post id or page name.
@Disqus.ShowComments(pageIdentifier: "post123")
This will render the DISQUS comments as shown below:
Someone will now make a comment here and move to another page and then make another comment. The only way DISQUS has to identify the comments on the basis of the PageIdentifier parameter in the ShowComments method. When some other user requests the same page again from a different geographical location, the DISQUS will check the PageIdentifier and then load the related comments.
I hope this post gives you an overview on how you can integrate DISQUS commenting system on you site in MVC.
Currently rated 4.5 by 2 people

Using ReCaptcha In ASP.NET WebForms And MVC

31. July 2011 14:58

API ASP.NET ASP.NET MVC 

ReCaptcha is now being used widely by many websites especially where there is a possibility of spamming the website, blog or a forum. Here I will show you on how you can use ReCaptcha in ASP.NET and MVC. Get a ReCaptcha Gobal Key and ASP.NET ReCaptcha DLL. Once you get the global key we are ready to go.
 
ReCaptcha in WebForms
 
Fire Visual Studio and create a new ASP.NET web forms project. First add a ReCaptcha DLL in the project and as we are talking about a user control we will have to register the control. On the top of the page use the register directive to register the ReCaptcha control.
<%@ register tagprefix="recaptcha" namespace="Recaptcha" assembly="Recaptcha" %>
Now on the page, we will use the control.
<recaptcha:recaptchacontrol id="recaptcha" runat="server" publickey="public key"  privatekey="private key" />
You will get the public key and the private key when you register for the ReCaptcha global key. This will render the ReCaptcha control on the page.
Notice that I have also placed a button and the label (with no text) on the page along with the ReCaptcha control. On the submit button we will check the Page.IsValid method. If the ReCaptcha text entered by the user is correct then the Page.IsValid method will return true else it will return false. Therefore the code on the submit button will be as follows:
if (Page.IsValid)
{
      lblStatus.Text = "Captcha Validated!";
}
else
{
      lblStatus.Text = "Invalid Captcha!";
}
This is it, hit F5 and try it out. We are now done implementing ReCaptcha in web forms and now we will see it in action in MVC.
 
ReCaptcha in MVC
 
Create a new MVC project in Visual Studio and I am using MVC 3 with RAZOR View Engine. To implement ReCaptcha in MVC, we will be using Microsoft Web Helpers. I assume you are aware of NuGet. Just in case if you are not aware of the Microsoft Web Helpers read my post on Working With Microsoft Web Helpers In MVC 3 Razor View. Microsoft web helpers allow us to use ReCaptcha in a very easy way. In WebForms we have used a DLL to render the ReCaptcha control on the page, but with Microsoft web helpers we can render the control with a single line of code. As you have used NuGet to install Microsoft Web Helpers library, make sure that you also use the correct namespace on the top of the page.
@using Microsoft.Web.Helpers;

@using (Html.BeginForm("Submit", "Home", FormMethod.Post))
{
    @ReCaptcha.GetHtml(publicKey: "<public key>", theme: "red")
}
I have rendered the control inside the form because when the data gets submitted after user enters the text the Submit method of the Home controller gets fired and check the captcha text entered by the user. As you know we have two keys with us, one is a public key and the other is a private key. We have used the public key to render the control on the page and we will now use the private key to validate the captcha. Also make sure that in order to use the ReCaptcha class on server side code you need to add the Microsoft.Web.Helpers namespace.
[HttpPost]
public ActionResult Submit()
{
        if (ReCaptcha.Validate(privateKey: "<private key>"))
        {
             return Content("Valid Captcha");
        }
        else
       {
            return Content("InValid Captcha");
       }
}
The ReCaptcha class of the web helpers provides a method to validate the entered text by the user. The private key of the ReCaptcha is passed as a parameter in order to validate the captcha text.
Using ReCaptcha with ASP.NET WebForms or MVC is pretty simple and easy. Here are some of the links which I feel you might find useful.
Currently rated 5.0 by 1 person

Handling Text Changed Event In ASP.NET MVC 3 With JQuery

16. July 2011 13:00

ASP.NET MVC Jquery 

In my quest of learning MVC I came across many problems and here is one of them. I was trying to fire an event whenever a text changed event occurred. I am using JQuery to handle the text changed event but eventually the text changed event doesn't seems to be working in MVC as it is working for a text box changed event in web forms. The solution I found seems to be working fine for me as I don't want to fire an event on every key press.

To get started fire Visual Studio and create a new MVC 3 application with RAZOR view engine. I have build a simple contact manager application which allows the user to create a new contact, edit and delete existing contacts. While creating a new contact, what I want is when the user enters the e-mail address of the contact I want to make an AJAX call, which then call the method in the controller and return the HtmlString which will then show the Gravatar on the webpage.

Here is the default view of the index view. I will ask the user to enter some very basic information like name, address, email and phone.

Now, when the user enters the email address of the contact and press TAB key to move to another field or just click somewhere else on the page, the focus on the text field will be changed and the controller function then returns HtmlString to show the Gravatar image.

Here is the markup of the Create View (Create.cshtml):

@model TextChangedMVC.Models.Contacts
@{
    ViewBag.Title = "Create";
}
<h2>
    Create</h2>
<script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>
@using (Html.BeginForm())
{
    @Html.ValidationSummary(true)
    <fieldset>
        <legend>Contacts</legend>
        <div class="editor-label">
            @Html.LabelFor(model => model.Name)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.Name)
            @Html.ValidationMessageFor(model => model.Name)
        </div>
        <div class="editor-label">
            @Html.LabelFor(model => model.Address)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.Address)
            @Html.ValidationMessageFor(model => model.Address)
        </div>
        <div class="editor-label">
            @Html.LabelFor(model => model.Email)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.Email)
            <div id="Gravatar">
            </div>
            @Html.ValidationMessageFor(model => model.Email)
        </div>
        <div class="editor-label">
            @Html.LabelFor(model => model.Phone)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.Phone)
            @Html.ValidationMessageFor(model => model.Phone)
        </div>
        <p>
            <input type="submit" value="Create" />
        </p>
    </fieldset>
}
<div>
    @Html.ActionLink("Back to List", "Index")
</div>

Check the highlighted code in the above markup where I have a DIV called Gravatar. This is where I will display the Gravatar of the person. Remember, when the user enters the email address we need to make sure that the Gravatar of the person displays without being an obstruction to the user, so an AJAX request to the controller will help in achieving this.

Below is the Jquery which will call the controller method called Avatar which accepts email as a parameter of string type.

<script type="text/javascript">
    $('#Email').change(function () {
        $('#Gravatar').html('');
        var selection = $('#Email').val();
        if (selection.length > 0) {
            $.post("/Home/Avatar", { email: selection },
        function (data) {
            $('#Gravatar').html(data)
        })
        }
    });
</script>

The above script is simple and here I am calling the controller's Avatar method which returns an HtmlString. At line 6, we are making a request and calling the controller's method. At line 8, the data (which is a HTML) returned will be set on the DIV called Gravatar (the placeholder for the Gravatar image).

The controller method Avatar is as follows:

public HtmlString Avatar(string email)
{
      return Gravatar.GetHtml(email, defaultImage: "http://midnightprogrammer.net/pics/default.gif");
}

Gravatar is a method is a part of the Microsoft Web Helpers. You can use web helpers by downloading it via NuGet. Check it out here if you miss my blog post on how to use Microsoft Web Helpers in MVC.

Related Post:

Currently rated 3.4 by 9 people

Bin Deploy ASP.NET MVC 3 Application With SQL CE 4.0 & Entity Framework

4. July 2011 14:26

.NET Framework ASP.NET MVC Visual Studio 

A few days back Phil Haack wrote a blog post on how to bin deploy ASP.NET MVC 3 application on the web server where ASP.NET MVC 3 is not installed. Like many users I am also on shared hosting and therefore I do not have full control over IIS or the remote machine so I can install or update ASP.NET MVC 3, SQL Server CE 4.0 and other development related stuff. Phil did an excellent post but that works only if you are deploying application with SQL Server as a database. If you are planning to deploy your application with SQL CE as your application backend then here are the steps you need to perform.

I assume that you have your ASP.NET MVC 3 application ready to be deployed with SQL CE 4.0 and EF 4.1. But make sure you have add assembly and for SQL CE 4.0 using NuGet. I recommend you to use NuGet here because it will add all the necessary configurations in Web.config file and also add the correct references to your project. If you have MVC 3 tools update installed then there is no need to add the references for SQL CE 4.0 and for EF 4.1, the default MVC 3 template will do it for you. But there are still some changes to be done in Web.config file.
 
To deploy your application with SQL CE 4.0 you need to make below changes to the web.config file:
 
Comment or delete everything inside the connectionStrings tag. The connection string by default is pointing to your default SQL Server instance and as we are going to deploy our application with SQL CE 4.0 we need to change the value under connectionStrings tag like the one below.
<add name="ContactEntities" connectionString="Data Source=|DataDirectory|DB.sdf" providerName="System.Data.SqlServerCe.4.0" />
Next is to add DbProviderFactories under System.Data tag. If you run the application on your local development server then it will run without any problems, but if you deploy the web application to the hosting web server where SQL CE 4.0 is not installed then you will get the below error.
 
 To avoid this error you need to manually add the DbProviderFactories in the Web.config file. Below in the markup you need to add to your web.config file.
<system.data>
    <DbProviderFactories>
      <remove invariant="System.Data.SqlServerCe.4.0" />
      <add name="Microsoft SQL Server Compact Data Provider 4.0" invariant="System.Data.SqlServerCe.4.0" description=".NET Framework Data Provider for Microsoft SQL Server Compact" type="System.Data.SqlServerCe.SqlCeProviderFactory, System.Data.SqlServerCe, Version=4.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91" />
    </DbProviderFactories>
</system.data>
The best way to do this and to avoid any unnecessary error is to use NuGet. If you use NuGet to deploy SQL CE 4.0 then it will add all necessary configurations to the web.config file, add the correct dependent assembly to the project.
 
Copy all the dependencies to the BIN folder

The question here is how the one knows what are the dependencies and where to find them all so that they can be deployed with the application? To perform this step you should have Visual Studio 2010 Service Pack 1 (VS 2010 SP1) installed on your machine. After installing VS 2010 SP1 there will be an option called Add Deployable Dependencies added when the user right-click the project icon in the solution explorer. When you click this option a dialog box appears which allows you to select the dependencies required for the project.

If you have read Phil's post by now, you might know the difference of all the above options. Here, as we are deploying SQL CE 4.0 database we will also check SQL Server Compact also. Click OK button to add all the required dependencies. As soon as you click OK button you will notice that a new folder named _bin_deployableAssemblies gets added to the solution explorer.

 

After adding all the dependencies you then need to build you web application which then copies all the dependencies to the project's or web application's bin folder. While deploying the application we will place each file with similar directory structure in the BIN folder on the hosting web server where ASP.NET MVC 3, SQL CE 4.0 and EF 4.1 is not installed. Just in case if you are wondering on how to deploy EF 4.1, then there is no other thing to be done to deploy EF 4.1, a DLL named EntityFramework inside the bin folder will do the work for us.

Note: I have made no changes to the directory structure while placing files at the remote hosting server.

Currently rated 5.0 by 1 person

Upload Files In RAZOR With jQuery Uploadify Plugin

16. March 2011 16:35

ASP.NET MVC Jquery 

A Few months back I wrote a post on how to use jQuery plugin Uploadify to upload single/multiple files without postback in ASP.NET. The program works similarly to simple file upload sites in its ease of use. Now a few days back I was working on a demo project which is on MVC 3 Razor and I use the same plugin without any problems. But the files that are being uploaded are uploaded to the root folder instead of the folder I specified to upload the files. After a lot of head scratching, I was unable to find the actual problem as why the file was not being uploaded to the folder of my choice. The answer was hidden in the normal file upload code that I saw in a forum posted by a user. So I gave it a try and it WORKED!! I was about to blog about the usage of uploadify plugin, but before that one of my blog reader asked me a question about uploading the files in Razor, though it was a bit different but this way it is pretty.

How do I do it?

Using the uploadify plugin in MVC 3 is the same as used with web forms, the only difference is that on the server-side we are going to use Controller and not a ASP.NET handler. Client side script is the same and there are only changes in script and folder parameter. Set the multi parameter to true if you wish to upload multiple files. 

<script type="text/javascript">
    $(window).load(
    function () {
        $("#fileuploader").fileUpload({
            'uploader': '/Scripts/uploader.swf',
            'cancelImg': '/Images/cancel.png',
            'buttonText': 'Select Image',
            'script': 'Home/Upload',
            'folder': '/uploads',
            'fileDesc': 'Image Files',
            'fileExt': '*.jpg;*.jpeg;*.gif;*.png',
            'multi': true,
            'auto': true
        });
    }
);
</script>

The script tag specifies the method in the Home Controller which handles the file upload. The Upload method in the Home Controller:

public string Upload(HttpPostedFileBase fileData)
{
            var fileName = this.Server.MapPath("~/uploads/" + System.IO.Path.GetFileName(fileData.FileName));
            fileData.SaveAs(fileName);
            return "ok";
}

Now you can use the uploadify plugin with MVC 3 Razor and upload files in a more effective and efficient way and that too with no postback.

Download: FileUploader.zip (572.92 kb)

Currently rated 4.2 by 30 people