martes, 10 de enero de 2012

Controles de selección

Que tal,

trabajando en algunas interfaces encontré que existen similitudes en los casos de selección como listas muy largas, selecciones restringidas, entre otras.

Estuve mirando este plugin (libreria) que utiliza jQuery no se si conozcan algo parecido o que opinión tengan acerca de el.

http://harvesthq.github.com/chosen/

Espero sus comentarios.

miércoles, 4 de enero de 2012

Crear secciones personalizadas en el archivo de configuración


Are you tired of seeing your configuration settings as an endless list of key value pairs?
<add key="key0" value="value0" />
<add key="key1" value="value1" /> 
<add key="key2" value="value2" />
... 
Would you rather see something more like this?
<MySetting
  fileName="c:\temp"
  password="pencil"
  someOtherSetting="value" />
Join the club. Not only is the first approach prone to typos (AppSettings["tire"]or AppSettings["tier] anyone?), too many of these things all bunched together can cause your eyes to glaze over. It is a lot easier to manage when settings are grouped in logical bunches.
A while back Craig Andera solved this problem with the Last Configuration Section Handler he’d ever need. This basically made it easy to specify a custom strongly typed class to represent a logical group of settings using Xml Serialization. It led to a much cleaner configuration file.
But that was then and this is now. With ASP.NET 2.0, there’s an even easier waywhich I didn’t know about until Jeff Atwood recently turned me on to it.
So here is a quick run through in three easy steps.

Step one - Define your Custom Configuration Class

In this case, we’ll define a class to hold settings for a blog engine. We just need to define our class, inherit from System.Configuration.ConfigurationSection, and add a property per setting we wish to store.
using System;
using System.Configuration;

public class BlogSettings : ConfigurationSection
{
  private static BlogSettings settings 
    = ConfigurationManager.GetSection("BlogSettings") as BlogSettings;
        
  public static BlogSettings Settings
  {
    get
    {
      return settings;
    }
  }

  [ConfigurationProperty("frontPagePostCount"
    , DefaultValue = 20
    , IsRequired = false)]
  [IntegerValidator(MinValue = 1
    , MaxValue = 100)]
  public int FrontPagePostCount
  {
      get { return (int)this["frontPagePostCount"]; }
        set { this["frontPagePostCount"] = value; }
  }


  [ConfigurationProperty("title"
    , IsRequired=true)]
  [StringValidator(InvalidCharacters = "  ~!@#$%^&*()[]{}/;’\"|\\"
    , MinLength=1
    , MaxLength=256)]
  public string Title
  {
    get { return (string)this["title"]; }
    set { this["title"] = value; }
  }
}
Notice that you use an indexed property to store and retrieve each property value.
I also added a static property named Settings for convenience.

Step 2 - Add your new configuration section to web.config (or app.config).

<configuration>
  <configSections>
      <section name="BlogSettings" type="Fully.Qualified.TypeName.BlogSettings,   
      AssemblyName" />
  </configSections>
  <BlogSettings
    frontPagePostCount="10"
    title="You’ve Been Haacked" />
</configuration>

Step 3 - Enjoy your new custom configuration section

string title = BlogSettings.Settings.Title;
Response.Write(title); //it works!!!
What I covered is just a very brief overview to get you a taste of what is available in the Configuration API. I wrote more about configuration in the book I’m cowriting with Jeff AtwoodJon Galloway, and K. Scott Allen.
If you want to get a more comprehensive overview and the nitty gritty, I recommend reading Unraveling the Mysteries of .NET 2.0 Configuration by Jon Rista.

Captcha


Captcha

As a web developer we know what is captcha is. It’s way to confirm users as they are human.Following is captcha definition perWikiPedia.
CAPTCHA (play /ˈkæpə/) is a type of challenge-response test used in computing as an attempt to ensure that the response is generated by a person. The process usually involves one computer (a server) asking a user to complete a simple test which the computer is able to generate and grade. Because other computers are assumed to be unable to solve the CAPTCHA, any user entering a correct solution is presumed to be human. Thus, it is sometimes described as areverse Turing test, because it is administered by a machine and targeted to a human, in contrast to the standard Turing test that is typically administered by a human and targeted to a machine. A common type of CAPTCHA requires the user to type letters or digits from a distorted image that appears on the screen.
You can find more details about that on following link.

Google ReCaptcha Service:

Google provide Recaptcha service free of charge to confirm users whether they are human or computer. We can directly use the recaptcha service with there api. You have to create a private key for that and that key will validate domains against it. Even we can create the global key for all the keys. You can find more information about it from below link.

ReCaptcha Web helpers in ASP.NET MVC 3:

As per I have also written in my previous post. ASP.NET Web helpers from Microsoft comes inbuilt with tools update. If you not installed it then you have to download NuGet package for it. You can refer my previous post for this.
Now we have all things ready its time to write ReCaptcha code in ASP.NET MVC. First we have create key for recaptcha service. I have created it via following link. It’s very easy.
Now let’s start coding. Recaptcha web helper renders a captcha control in your web form so you can validate this. Following is code which will render captcha control.
?
1
@ReCaptcha.GetHtml(theme: "red")
It's take four argument
  1. Theme- theme specify the color and look for ReCaptcha control. You can have to put theme name over there
  2. Language- You need to specify the captcha challenge language
  3. TabIndex- Tab Index for this control
  4. PublicKey- A unique public key which we have created for our domain.
Following is a code how to use above code in real time. I have updated standard logon control template for ASP.NET MVC.
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
@model CodeSimplifiedTest.Models.LogOnModel
 
@{
    ViewBag.Title = "Log On";
    ReCaptcha.PublicKey=@"6LedqMcSAAAAAJgiIjKlyzzV2czbGOPvij1tc39A";
}
 
<h2>Log On</h2>
<p>
    Please enter your user name and password. @Html.ActionLink("Register", "Register") if you don't have an account.
</p>
 
<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>
<script src="@Url.Content("~/Scripts/jquery-1.5.1.min.js")" type="text/javascript"></script>
@Html.ValidationSummary(true, "Login was unsuccessful. Please correct the errors and try again.")
 
@using (Html.BeginForm()) {
    <div>
        <fieldset>
            <legend>Account Information</legend>
 
            <div class="editor-label">
                @Html.LabelFor(m => m.UserName)
            </div>
            <div class="editor-field">
                @Html.TextBoxFor(m => m.UserName)
                @Html.ValidationMessageFor(m => m.UserName)
            </div>
 
            <div class="editor-label">
                @Html.LabelFor(m => m.Password)
            </div>
            <div class="editor-field">
                @Html.PasswordFor(m => m.Password)
                @Html.ValidationMessageFor(m => m.Password)
            </div>
 
            <div class="editor-label">
                @Html.CheckBoxFor(m => m.RememberMe)
                @Html.LabelFor(m => m.RememberMe)
            </div>
 
            <p>
               @ReCaptcha.GetHtml(theme: "red")
            </p>
            
        </fieldset>
    </div>
}
As you can see in above code for recaptcha public key and Recaptcha.GetHtml part. Now its time to captcha validation in server side code in controller. As I have used standard logon template for this.I have modified Logon Action Result in Account controller like following.
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
[HttpPost]
public ActionResult LogOn(LogOnModel model, string returnUrl)
{
    if(!ReCaptcha.Validate(privateKey:"6LedqMcSAAAAAJgiIjKlyzzV2czbGOPvij1tc39A"))
    {
        return Content("Failed");
    }
   
    if (ModelState.IsValid)
    {
        if (Membership.ValidateUser(model.UserName, model.Password))
        {
            FormsAuthentication.SetAuthCookie(model.UserName, model.RememberMe);
            if (Url.IsLocalUrl(returnUrl) && returnUrl.Length > 1 && returnUrl.StartsWith("/")
                && !returnUrl.StartsWith("//") && !returnUrl.StartsWith("/\\"))
            {
                return Redirect(returnUrl);
            }
            else
            {
                return RedirectToAction("Index", "Home");
            }
        }
        else
        {
            ModelState.AddModelError("", "The user name or password provided is incorrect.");
        }
    }
 
    // If we got this far, something failed, redisplay form
    return View(model);
}
Here I have validated the captcha control with public key and if validation failed then it will sent failed message. Now it’s time to run that in browser and let’s see output.
RecapthaControlOuput
That’s it. Its easy to integrate. Hope you like it..Stay tuned for more.. Till then Happy Programing..Namaste!!