Captcha for MVC

I was working on a MVC4 project in my requirements – use captcha to validate the human vs Robots/spam.

I researched a lot to find the better solution and here are the things I came across that are better.

1) Visual Captcha – unique design which you never seen Demo
2) No Captcha Recaptcha by Google – Read more

Previously google had reCaptcha V1.0 which has some security threats. Their team really put some efforts on that gave us the better outcome out of it with API v2.0

Click here to see the implemetation/example on Visual Captcha.

I looked for ASP.NET MVC implementation for Google reCaptcha API 2.0, but couldn’t find any.

How to implement??

1) 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.

2) Once you have done with registration, the following keys will be generated
reCaptcha2Keys

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

3) As per google documentation we can display widget in 2 different ways.
a.Automatically render the widget
b.Explicitly render the widget

Display Widget

Your code in Index.cshtml view page will look like below
DisplayWidgetinView

4) Verify User’s Response
Once reCAPTCHA is generated and solved by a 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
}

Lets create an response class to verify the user response
public class UserResponse
{
[JsonProperty("success")]
public string Success { get; set; }

[JsonProperty("error-codes")]
public List Codes { get; set; }
}

We will create a POST method in Index action in the Accountcontroller to verify the user response.

[HttpPost]
public ActionResult Validate()
{
var response = Request["g-recaptcha-response"];
//secret that was generated in key value pair
const string secret = "6Lc2bgATAAAAAJG6_OII3tRKH6oLoax";

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(reply);

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

var error = captchaResponse.ErrorCodes[0].ToLower();
switch (error)
{
case ("missing-input-secret"):
ModelState.AddModelError("","Missing User input secret"));
break;
case ("invalid-input-secret"):
ModelState.AddModelError("", "Invalid User input secret"));
break;
case ("missing-input-response"):
ModelState.AddModelError("", "Missing User input response");
break;
case ("invalid-input-response"):
ModelState.AddModelError("", "Invalid User input response");
break;
default:
ModelState.AddModelError("", "Error occured. Please try again");
break;
}
return View(model);
}
else
{ //For Valid
return RedirectToAction("Index", "Account");
}

If you coded right you will see something like below:
reCaptcha2Look

Hope it helps…….

An SPRequest object was not disposed before the end of this thread :SharePoint

I had a problem this morning – Not able to access SharePoint site. When I start debugging with ULS, I see below errors all over the place.

Problem:


—————————————————————————————————————
An SPRequest object was not disposed before the end of this thread.
To avoid wasting system resources, dispose of this object or its parent (such as an SPSite or SPWeb) as soon as you are done using it.
This object will now be disposed.
Allocation Id: {GUID} To determine where this object was allocated, set Microsoft.SharePoint.Administration.SPWebService.ContentService.CollectSPRequestAllocationCallStacks = true.
—————————————————————————————————————
System.AccessViolationException: Attempted to read or write protected memory. This is often an indication that other memory is corrupt.
at Microsoft.SharePoint.Portal.WebControls.LocStringIdLookupTable..cctor()
—————————————————————————————————————

Finding a way to resolve the issue:


If the sites are not working at this point of time, try doing App pool recycle or IIS reset(not recommended in peak hours as it recycles all App pools leading temporary outage).

To simply enable the stack trace below powershell can be used.

[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint")
$contentService = [Microsoft.SharePoint.Administration.SPWebService]::ContentService
$contentService.CollectSPRequestAllocationCallStacks = $true
$contentService.Update()

But, Microsoft suggested best practices should be used to dispose SPWeb and SPSite objects[Any SPRequests]. Most of the time these kind of issues could be because of Custom development.

To find out Any Dispose objects in your dll/exe file use SPDisposeCheck tool.

However installing SPDisposecheck tool is an add-on that can save your time and analyze your Visual Studio Code for non – disposed objects before code is deployed.

Here is a nice article – how to integrate SpDisposeCheck tool

Sharepoint Item Recycle vs Delete

If you delete a list item/document in SharePoint environment using the User Interface, it’s being moved to the Recycle Bin, so that it can be restored if necessary. There are situations when you want to include deleting list items and documents in your custom solutions. The most commonly used approach I have seen is calling the SPListItem.Delete() method. While this does the job, and deletes the item, deletes it permanently instead of moving to the Recycle Bin.

Looking carefully at the SPListItem class, you can find SPListItem.Recycle() method[not that popular]. Its description (Recycles the item and returns the item’s GUID.) is rather cryptic and doesn’t give you much clue on what you could use is for. It turns out that it’s exactly that method that you need to call in order to move a list item/document to the Recycle Bin instead of deleting it permanently.

In general moving items to the Recycle Bin instead of deleting them permanently is what you should do in your custom solutions. It is standard SharePoint behavior and therefore something end users will expect of your solutions as well. You should perform the permanent deletion only if explicitly named in the requirements. Otherwise, let’s just stick to what SharePoint does to leverage the same User Experience.

What is really goin’ on:
Internally there isn’t much difference between the SPListItem.Delete and SPListItem.Recycle methods. Both call an internal SPListItem.Delete method with a different parameter which determines whether an list item/document should be moved to the Recycle Bin or permanently deleted.

The following code shows how to remove all documents from a folder:

int iCount = spFolder.Files.Count;

for (int i = 0; i < iCount; i++)
{
spFolder.Files[i].Delete();
}

Deleting documents with this code will delete permanently without using the recycle bin.
To move the document to the recycle bin use the following code:
spFolder.Files[i].Recycle();

Minimizing the Console Window in C#

1. Introduction.

  • A few days ago, I was developing a console application written in C#.
  • One of the requirements of this application was that it must immediately minimize the console window on startup.
  • For the benefit of readers, I decided to post here the code for minimizing the console window of a managed application.

2. Example Code.

  • The code below demonstrates how this can be done :
  • using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Runtime.InteropServices;
    
    namespace CSConsole
    {
        class Program
        {
            const Int32 SW_MINIMIZE = 6;
    
            [DllImport("Kernel32.dll", CallingConvention = CallingConvention.StdCall, SetLastError = true)]
            private static extern IntPtr GetConsoleWindow();
    
            [DllImport("User32.dll", CallingConvention = CallingConvention.StdCall, SetLastError = true)]
            [return: MarshalAs(UnmanagedType.Bool)]
            private static extern bool ShowWindow([In] IntPtr hWnd, [In] Int32 nCmdShow);
    
            private static void MinimizeConsoleWindow()
            {
                IntPtr hWndConsole = GetConsoleWindow();
                ShowWindow(hWndConsole, SW_MINIMIZE);
            }
    
            static void Main(string[] args)
            {
                MinimizeConsoleWindow();
                Console.ReadKey();
            }
        }
    }
    
  • I basically used the GetConsoleWindow() Windows API to obtain the window handle used by the console associated with the calling process.
  • I then use the ShowWindow() API using the window handle returned from GetConsoleWindow() and with the second parameter set to SW_MINIMIZE (value 6) to minimize the console window.

Access Propert Bag in Sharepoint

There are multiple ways to access Property bag settings. As discussed in my previous post deploy appropriate property bag solution onto your farm to deal with UI version.

3 ways to access Property bag settings:

  • UI Version
  • SharePoint Designer
  • Programatically
  • UI Version:

    Using SharePoint Designer

    (i). Open the site in SP Designer 2010 and click on Site Options.
    (ii). Under Parameters, click on Add and Start Adding Key/Value PairsDesigner1

    Programatically

    To read this MyKey value, just use the below code.

    SPSite siteCollection = new SPSite("https://jagadeesh4sp.wordpress.com");
    SPWeb website = mySite.RootWeb;
    string MyValue = website.AllProperties["MyKey"]);
    

    Use the below code to set the property bags Programatically

    SPSite siteCollection = new SPSite("https://jagadeesh4sp.wordpress.com");
    SPWeb website = mySite.RootWeb;
    website.Properties.Add("MyKey", "MyValue");
    website.Properties.Update
    

    – Property bag Extension class

    public static class PropertyBagExtension
    {
     
        public static void AddProperty(this SPWeb web, string key, string value)
        {
            web.AllowUnsafeUpdates = true;
            web.Properties[key] = value;
            web.AllProperties[key] = value;
            web.Update();
            web.Properties.Update();
        }
     
     
        public static void RemoveProperty(this SPWeb web, string key)
        {
            web.AllowUnsafeUpdates = true;
            web.AllProperties.Remove(key);
            web.Properties[key] = null;
            web.Update();
            web.Properties.Update();
        }
     
     
        public static string GetPropertyValue(this SPWeb web, string key)
        {
            if (web.AllProperties.ContainsKey(key))
                return web.AllProperties[key].ToString();
     
            return null;
        }
    }
    

    Hope it helps some of you folks……