Tuesday, 14 October 2014

User friendly CAPTCHA for Asp.Net MVC

In this post I will show you how to add CAPTCHA functionality to a html form in an Asp.Net MVC 4 project. My goal is to make the CAPTCHA problem easy enough for all to solve, like a simple sum operation, and easier to read then the standard CAPTCHA text. An easy to read image is more vulnerable to smart bots that have an ORC system but I prefer to scare less clients then to provide the strongest anti-bot protection. And one more feature, when clicked the image should, change giving the users a new chance to respond correctly.


Implementing CAPTCHA in C# and MVC 4 takes these steps:
  • Create an Action that returns a CAPTCHA image and stores in the user session the right answer
  • Add to your Model a string property named Captcha
  • Add to your View the textbox for Captcha and the image placeholder
  • Validate answer inside your own Action

Render CAPTCHA image
CaptchaController.cs
        public ActionResult CaptchaImage(string prefix, bool noisy = true)
        {
            var rand = new Random((int)DateTime.Now.Ticks);
            //generate new question
            int a = rand.Next(10, 99);
            int b = rand.Next(0, 9);
            var captcha = string.Format("{0} + {1} = ?", a, b);

            //store answer
            Session["Captcha" + prefix] = a + b;

            //image stream
            FileContentResult img = null;

            using (var mem = new MemoryStream())
            using (var bmp = new Bitmap(130, 30))
            using (var gfx = Graphics.FromImage((Image)bmp))
            {
                gfx.TextRenderingHint = TextRenderingHint.ClearTypeGridFit;
                gfx.SmoothingMode = SmoothingMode.AntiAlias;
                gfx.FillRectangle(Brushes.White, new Rectangle(0, 0, bmp.Width, bmp.Height));

                //add noise
                if (noisy)
                {
                    int i, r, x, y;
                    var pen = new Pen(Color.Yellow);
                    for (i = 1; i < 10; i++)
                    {
                        pen.Color = Color.FromArgb(
                        (rand.Next(0, 255)),
                        (rand.Next(0, 255)),
                        (rand.Next(0, 255)));

                        r = rand.Next(0, (130 / 3));
                        x = rand.Next(0, 130);
                        y = rand.Next(0, 30);

                        gfx.DrawEllipse(pen, x – r, y – r, r, r);
                    }
                }

                //add question
                gfx.DrawString(captcha, new Font("Tahoma", 15), Brushes.Gray, 2, 3);

                //render as Jpeg
                bmp.Save(mem, System.Drawing.Imaging.ImageFormat.Jpeg);
                img = this.File(mem.GetBuffer(), "image/Jpeg");
            }

            return img;
        }
If you want to use multiple  CAPTCHAs you can use the prefix to store the answer for each form. Much can be improved regarding the rendered image, for example I could use different font and size for each number in the equation, replace the noise with text distortion.
Include  CAPTCHA validator in Model and View
Models.cs
    public class SubscribeModel
    {
        //model specific fields
        [Required]
        [Display(Name = "How much is")]
        public string Captcha { get; set; }
    }
In the View, beside a label, textbox and validator span you’ll need to add an image placeholder for the CAPTCHA.
Index.cshtml
@*form specific fields*@ <div class="editor-label">
    @Html.LabelFor(model => model.Captcha)
    <a href="@Url.Action("Index")">
        <img alt="Captcha" src="@Url.Action("CaptchaImage")" style="" />
    </a>
</div> <div class="editor-field">
    @Html.EditorFor(model => model.Captcha)
    @Html.ValidationMessageFor(model => model.Captcha)
</div>
Validate CAPTCHA on the server side
Inside your post action where the form submits you can validate the answer by comparing with the session value.
CaptchaController.cs
[HttpPost] public ActionResult Index(SubscribeModel model)
{
    //validate captcha
    if (Session["Captcha"] == null || Session["Captcha"].ToString() != model.Captcha)
    {
        ModelState.AddModelError("Captcha", "Wrong value of sum, please try again.");
        //dispay error and generate a new captcha
        return View(model);
    }
    return RedirectToAction("ThankYouPage");
}

Monday, 29 September 2014

Rest_TimeEntries



Time Entries
Listing time entries
GET /time_entries.xml
Returns time entries.
Showing a time entry
GET /time_entries/[id].xml
Returns the time entry of given id.
Creating a time entry
POST /time_entries.xml
Creates a time entry.
Parameters:
  • time_entry (required): a hash of the time entry attributes, including:
    • issue_id or project_id (only one is required): the issue id or project id to log time on
    • spent_on: the date the time was spent (default to the current date)
    • hours (required): the number of spent hours
    • activity_id: the id of the time activity. This parameter is required unless a default activity is defined in Redmine.
    • comments: short description for the entry (255 characters max)
Response:
  • 201 Created: time entry was created
  • 422 Unprocessable Entity: time entry was not created due to validation failures (response body contains the error messages)
Updating a time entry
PUT /time_entries/[id].xml
Updates the time entry of given id.
Parameters:
  • time_entry (required): a hash of the time entry attributes (same as above)
Response:
  • 200 OK: time entry was updated
  • 422 Unprocessable Entity: time entry was not updated due to validation failures (response body contains the error messages)
Deleting a time entry
DELETE /time_entries/[id].xml
Deletes the time entry of given id.
Insert TimeEntry Code

public string InsertTimeEntries(string host, string key)
 {

  ServicePointManager.ServerCertificateValidationCallback += (sender, cert, chain, error) => true;

var manager = new RedmineManager(host, key);

 TimeEntry timeent = new TimeEntry();

 timeent.Issue = new IdentifiableName { Id = 3175, Name = "Sample Test Issue" };

 timeent.Project = new IdentifiableName() { Id = 88, Name = "Jacobson - SSRS" };

 timeent.SpentOn = DateTime.Now;

 timeent.Hours = 3;

 timeent.Comments = "Testing of the Code";

 timeent.User = new IdentifiableName { Id = 111, Name = "narendra.kushwaha" };

 timeent.Activity = new IdentifiableName { Id = 14, Name = "Coding" };

 manager.CreateObject(timeent);
  }

Thursday, 25 September 2014

View in SQL Server 2008



Introduction

In this article, I describe Views in SQL Server. This is a simple topic. I hope this article will help you just like my Windows Store articles. Please give me your valuable suggestions and feedback to improve my articles.

What is a View

Views are database objects which are like virtual tables that have no physical storage and contains data from one table or multiple tables. A View does not have any physical storage so they do not contain any data. When we update, insert or apply any operation over the View then these operations are applied to the table(s) on which the view was created.

Types Of View
  1. System View
  2. User Define View
User Defined Views are important so I describe only User Defined Views. They are of two types:
  1. Simple View
  2. Complex view
Simple View:

When a View is created on a single Table than it is called a Simple View. We can apply all operations on a Simple View that we can apply on a table.

First of all we create a table on which we create a view.
create table emp(empId int,empName varchar(15),empAdd varchar(15))

Now insert data by the following code.
 
insert into emp
select 1,'deepak','UA'union all
select 2,'Middha','Punjab'union all
select 3,'d','Delhi'union all
select 4,'gourav','Noida'union all
select 5,'deepakia','Laksar'union all
select 6,'Deep','Haridwar'

Table:



Creation of a simple view:
 
create view v1
as
select * from emp

Operation on view:

See all the data of the view:
 
select * from v1

Output:



See the specific data of the view:
 
select * from v1 where empId=4 

Output:

Insertion:
 
insert into v1 values(7,'raj','canada'); 

Output:




Updating:
 
update v1 set empAdd='usa'where empId=7 

Output:


deletion:
 
delete from v1 where empId=7

Output:





Renaming:
 
exec sp_rename 'v1','v11' 

Logic of the View:
exec sp_helptext v1

Output:



Dropping the View:
 
drop view v1 

Encrypted View:
 
create view v1
with encryption
as
select * from emp

Complex view:

Views created on more than one table are called Complex View. We cannot perform all operations of a table on a Complex View.

First of all we create a table and insert some data :
create table empStatus(empId int,empStatus varchar(10))
 
insert into empStatus
select 1,'active'union all
select 2,'inactive'union all
select 4,'active'union all
select 5,'inactive'union all
select 6,'active'

Table:
select * from empStatus

Output:
           


Creation of complex view:
 
create View VComplex
as
select e.empId,e.empName,e1.empStatus from emp e inner join empStatus e1 on e.empId=e1.empId  

See all the records:
 
select * from VComplex

Output:


See specific record:
 
select * from VComplex where empId=4

Output:



If we try insert, update or delete in a complex view then it shows an error as in the following:
 
insert into vcomplex values(11,'d','inactive')

Output:


Encryption of the Complex View:
 
create View VComplex
With encryption
as
select e.empId,e.empName,e1.empStatus from emp e inner join empStatus e1 on e.empId=e1.empId
 
Summary

In this app I described Views in SQL Server. I hope this article has helped you to understand this topic. Please share if you know more about this. Your feedback and constructive contributions are welcome.
 

C# LINQ Joins With SQL

There are  Different Types of SQL Joins  which are used to query data from more than one database tables. In this article, you will learn a...