Tuesday, November 8, 2016

How to Programmatically Impersonate Users in SharePoint

Sometimes when creating SharePoint web or console applications, you may need to execute specific code blocks in another user’s context.
Impersonating users in SharePoint will require a couple of things:
  • the account that the web or console app uses has privileges to impersonate other users (typically this would be the system account)
  • specific users’ user tokens

Step 1: Log in as the system account, or get a handle to the system account in your code
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
string siteStr = "http://mysharepointsite/";
 
//we just need to get a handle to the site for us
//to get the system account user token
SPSite tempSite = new SPSite(siteStr);
 
SPUserToken systoken = tempSite.SystemAccount.UserToken;
 
using (SPSite site = new SPSite(siteStr, systoken))
{
   using (SPWeb web = site.OpenWeb())
   {
       //right now, logged in as Site System Account
       Console.WriteLine("Currently logged in as: " +
                        web.CurrentUser.ToString());
 
       //add your code here
   }
}
Step 2: Before you impersonate, get the user token of the user you are switching to. For example:
1
2
3
4
5
6
7
8
9
10
11
//get this current user's user token
SPUserToken userToken = web.AllUsers[user].UserToken;
 
//create an SPSite object in the context of this user
SPSite s = new SPSite(siteStr, userToken);
 
SPWeb w = s.OpenWeb();
Console.WriteLine("Currently logged in as: " +
                  w.CurrentUser.ToString() +
                  "(" + w.CurrentUser.Name + ")"
                 );
Complete code follows:
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
private static void impersonateTest()
{
   string siteStr = "http://mysharepointsite/";
   SPSite tempSite = new SPSite(siteStr);
   SPUserToken systoken = tempSite.SystemAccount.UserToken;
   using (SPSite site = new SPSite(siteStr, systoken))
   {
       using (SPWeb web = site.OpenWeb())
       {
           //right now, logged in as Site System Account
           Console.WriteLine("Currently logged in as: " +
                              web.CurrentUser.ToString());
           switchUser(web, siteStr, "BlackNinjaSoftware/MatthewCarriere");
           switchUser(web, siteStr, "BlackNinjaSoftware/ShereenQumsieh");
           switchUser(web, siteStr, "BlackNinjaSoftware/DonabelSantos");
       }
   }
}
 
private static void switchUser(SPWeb web, string siteStr, string user)
{
   //impersonate somebody else
   SPUserToken userToken = web.AllUsers[user].UserToken;
   SPSite s = new SPSite(siteStr, userToken);
   SPWeb w = s.OpenWeb();
   Console.WriteLine("Currently logged in as: " +
                     w.CurrentUser.ToString() +
                     "(" + w.CurrentUser.Name + ")"
                    );
}

Thursday, November 3, 2016

Protecting SharePoint Server Applications/SharePoint public website penetration testing issue fixes




No Risk Details
1  Version Disclosure (ASP.NET) 
Description:
 This information can be found in HTTP Response Header which can help the attacker to build profile against your site which then they can search for common public issues from sites like “National Vulnerability Database” https://web.nvd.nist.gov/view/vuln/search or for zero-day attacks.

 This information can be helpful in hacking phase but it doesn’t mean your site will be exploited.
 Fix:
  Add the following setting inside the <system.web> element in your application’s Web.config file <httpRuntime enableVersionHeader=”false” />
 References:
 http://www.4guysfromrolla.com/articles/120209-1.aspx
2  Version Disclosure (SharePoint)
 Description:
 Same as point 1.

 Fix:
 It’s not recommended to remove these headers and it’s better to accept the risk in this case because these will affect the SharePoint crawling and other features except you have an anonymous website with limited features.
 References:
 http://www.wictorwilen.se/sharepoint-mythbusting-the-response-header-contains-the-current-sharepoint-version
 http://www.wictorwilen.se/sharepoint-2013-sharepoint-health-score-and-throttling-deep-dive
 http://dirkvandenberghe.com/2011/06/07/remove-http-response-headers-for-internet-facing-sharepoint-sites.html
 http://blog.michelbarneveld.nl/michel/archive/2009/11/08/x-sharepointhealthscore-a-new-sharepoint-2010-http-header.aspx
3  ASP.NET Identified 
Description:
 Same as point 1.

 Fix:
 Add the following setting in your application's Web.config file
<httpProtocol>
<customHeaders>
<remove name="X-Powered-By" />
 References:
 https://ict.ken.be/removing-x-powered-by-aspnet-and-other-version-headers
4  Version Disclosure (IIS) 
Description:
 Same as point 1.

 Fix:
 Create custom HTTP Module as following:
namespace MyNamespace
{
 public class HttpHeadersCleanup : IHttpModule
 {
 public void Init(HttpApplication context)
 {
 context.PreSendRequestHeaders += PreSendRequestHeaders;
 }
 private static void PreSendRequestHeaders(object sender, EventArgs e)
 {
 HttpContext.Current.Response.Headers.Remove("Server");
    public void Dispose()
 {
 }
   }
}
 Then add the following setting in web.config
<system.webServer>
    <modules>
        <add name="HttpHeadersCleanup " 
type="MyNamespace.HttpHeadersCleanup, MyAssembly"/>
    </modules>
 References:
 http://www.frederikvig.com/2010/11/removing-http-headers-for-asp-net-sites/
5 ViewState is not Encrypted 
Description:
 SharePoint doesn’t use Viewstate to store any sensitive data such as user tokens
or other so just give your security department justification and explain that Viewstate
required to be existed in SharePoint because it’s build on top of Asp.Net Web forms.
 Note:
 In case you have custom code using Viewstate , make sure to avoid storing sensitve data in Viewstate because it’s readable and represented by base64 encoding and In case you need to use it then make sure to enable Encryption and MAC encoding for integrity.
6  Cookie Not Marked as HttpOnly 
Description:
 In General, it’s always recommended to set HttpOnly flag to cookies to prevent XSS script risk against these cookies like Auth Token Cookie which then it can be used in hijacking and other attacks. In SharePoint if you are using Form authentication then by default SharePoint flag Auth Token with HttpOnly but there are some cookie in SharePoint not flagged with HttpOnly like “wss_keepsessionauthenticated” .
 Fix:
 Add this setting to web.config
<system.web>
 <httpCookies httpOnlyCookies="true" requireSSL="true" />
 References:
 http://murmurofawebmaster.blogspot.com/2013/07/
wsskeepsessionauthenticated.html 

7  Accessing _layout/ folder 
Description:
 For anonymous SharePoint website , it’s better to prevent users from accessing application pages which exists under _layout folder like /layout/Viewlsts.aspx .By default SharePoint has an enabled feature called “ViewFormPagesLockDown” which prevent anonymous users from accessing these pages.
 Fix:
 In case it’s disable then you can activate it by the following command
  Enable-SPFeature ViewFormPagesLockDown -Url http://youSite
 References:
 http://www.c-sharpcorner.com/uploadfile/Roji.Joy/how-to-secure-external-anonymous-access-to-sharepoint-2010-sites
8  Insufficient Transport Layer Protection
 Description:
 “HTTPs everywhere”, it’s a top priority to protect the information in transit by using TLS/SSL to provide secure communication. Also In case of anonymous site, it’s helpful to you to increase the site rank in Google search engine using HTTPs and by the way HTTPs (represents top layer of TLS/SSL) which provides 3 goals:
  1. Confidentiality to protect the data in transit from sniffing by using tools like fiddler or wireshark , hijacking or MITM attacks (Main goal).
  2. Integrity by protecting the data from tampering during transition so it will reject the request if anyone in the middle of transit modify the packets.
  3. Authenticity by tell and give the visitors assurance about your domain and who you are talking to.
 I will list all best practices to consider when implementing HTTPs in Your SharePoint Site:
  • Configure SSL for SharePoint http://blogs.msdn.com/b/fabdulwahab/archive/2013/01/21/configure-ssl-for-sharepoint-2013.aspx
  • Test its security level, configuration, implementation, key strength … test it with the Qualys Lab tool https://www.ssllabs.com/ssltest/ and fix the issues and try to make the grade “A” As possible.
  • Avoid Self-signed certificate , expired or invalid certificates due to lake of the authenticity.
  • Avoid Mixed content mode because still hacker can steal the session by sniffing HTTP content like image or js requests in HTTPs site.
  • Avoid Redirection from HTTP to HTTPs and also avoid only implementing HTTPs on login page because still hacker can steal the session by sniffing even without username and password.
  • Make sure to use “secure” cookies in case of sensitive cookies like Auth Token in Forms Membership , by using  requireSSL=”true” /> in web.config https://www.owasp.org/index.php/SecureFlag
  • Make sure to have end to end secure channels because in some cases they only implemented the HTTPs to load balance level only and it’s better to include the internal requests
  • Use HTTP Strict Transport Security(HSTS) to force the browser to browse the site to a certain time ( based on Max age value ) in HTTPs without need to send redirection request from HTTP to HTTPs (this header not support it in all browsers). For more information , check https://www.owasp.org/index.php/HTTP_Strict_Transport_Security
 Finally you can start with “StartSSL” for free certificates https://www.startssl.com/?app=1 or “CloudFlare” which add security controls to your site and provide fee SSL https://www.cloudflare.com/features-security
 References:
 http://googlewebmastercentral.blogspot.com.au/2014/08/https-as-ranking-signal.html
 https://www.owasp.org/index.php/Transport_Layer_Protection_Cheat_Sheet
 http://www.troyhunt.com/2011/11/owasp-top-10-for-net-developers-part-9.html
9  Separation of duties 
Description:
 Separation of Duties is a security principle which the process of separate sharing of more than one individual in one single task to prevent fraud and error. In case of anonymous websites this policy it can be very important and it can applies in SharePoint in many ways for examples:
10  Stack Trace and Errors Disclosure (ASP.NET) 
Description:
 It’s recommended to stop disclosing information because of unhandled errors,
trace and debug .With easy steps , you can prevent leaking these information which might help an attacker to gain more information and potentially focus on the development of further attacks.
 Fix:
 Change these settings in web.config 

  • Set <customErrors mode=”On” on web.config
  • Remove <trace enabled=”false” (by default is not enabled)
  • Set <compilation debug=”false” />
  • Set <SafeMode CallStack=”false”
Also do the same in web.config file in _layout folder.
 
11  _vti_inf.html , _vti_bin , _vti_pvt and _vti_bin/spsdisco.aspx
Description:
 If your SharePoint application is anonymously accessible then it’s recommended to consider implementing authorization rule to restrict access to web services , or resources under _vti_bin, _vti_pvt , /_vti_bin/spsdisco.aspx …
to at least prevent attacker from accessing these resources to gain information like SharePoint version or FrontPage configuration information … etc
 Fix:
 Add this setting to web.config
<location path="_vti_inf.html">
 <system.web>
  <authorization>
   <deny users="?" />
   <allow users="*" />
  </authorization>
 </system.web>
</location>
<location path="_vti_pvt">
 <system.web>
  <authorization>
   <deny users="?" />
   <allow users="*" />
  </authorization>
 </system.web>
</location>
<location path="_vti_bin">
 <system.web>
  <authorization>
   <deny users="?" />
   <allow users="*" />
  </authorization>
 </system.web>
</location>
 References:
 http://thuansoldier.net/?p=4267
 http://thuansoldier.net/?p=4298
12  Clickjacking
 Description:
 It’s recommended to prevent clickjacking risk on your website and you can find more details about it in this article – Clickjacking in OWASP https://www.owasp.org/index.php/Clickjacking
 Fix:
 The easiest fix for this risk to add this header X-Frame-Options to HTTP Response but remember this way is not supported in all browsers.
 Configure IIS to add an X-Frame-Options header to all responses for a given site, follow these steps:
  1. Open Internet Information Services (IIS) Manager.
  2. In the Connections pane on the left side, expand the Sites folder and select the site that you want to protect.
  3. Double-click the HTTP Response Headers icon in the feature list in the middle.
  4. In the Actions pane on the right side, click Add.
  5. In the dialog box that appears, type X-Frame-Options in the Name field and type SAMEORIGIN in the Value field.
  6. Click OK to save your changes.
 Note: By default SharePoint 2013 configured with this header
 References:
 http://blog.kotowicz.net/2009/12/5-ways-to-prevent-clickjacking-on-your.html
 https://www.owasp.org/index.php/Clickjacking
 https://support.microsoft.com/en-us/kb/2694329
 http://styledpoint.com/blog/including-sharepoint-2013-in-an-iframe-without-x-frame-options-error/ 
13  ASP.NET Security Vulnerability 
 Description:
 Any security vulnerabilities apply to Asp.net, it will be applied to SharePoint because SharePoint built on top of Asp.Net technologies.
 The below are the Common security vulnerabilities:
 Padding oracle vulnerability: (Asp.Net v1.0 to v3.5), most probably this vulnerability exists in non-patched SharePoint 2010 and older version. To know about this vulnerability you can check http://weblogs.asp.net/scottgu/important-asp-net-security-vulnerability or http://www.troyhunt.com/2010/09/fear-uncertainty-and-and-padding-oracle.html
 Fix:
 Update your SharePoint with the latest new version of CU to address this and other issues or you can install the direct fix https://technet.microsoft.com/library/security/ms10-070
 Hash DoS vulnerability: (resolved with the release of .NET 4.5)
 Allows an attacker to make a POST request with a very large number of parameters constructed to cause hash collisions when parsed by ASP.NET. To know about this vulnerability you can check http://www.troyhunt.com/2011/12/has-hash-dos-patch-been-installed-on.html
 Fix:
 Update your SharePoint with the latest new version of CU to address this and other issues or you can install the direct fix https://technet.microsoft.com/library/security/ms11-100
 Note: you can test your SharePoint site if it has the above vulnerabilities using the following link https://asafaweb.com (I recommended you to use this site for testing and also read all things written by the owner of this site Mr.Troy Hunt http://troyhunt.com)
14  Validation Request 
 Description:
 Request validation, a feature of ASP.NET since version 1.1, prevents the server from accepting content containing un-encoded HTML. This feature is designed to help prevent some script-injection attacks whereby client script code or HTML can be unknowingly submitted to a server, stored, and then presented to other users.
 Fix:
 SharePoint like other .NET content management systems which has a lot of places where rich text needs to be submitted to the server so By default Microsoft disable ValidateRequest in web.config and if you try to enable it then you will not able to create pages with Html editors contents.In this case you need to accept the risk and keep this feature disable but take care for your SharePoint and make sure it’s patched with up to date fixes and In case you have custom code , make sure to validate and encode the input at the client and server sides using libraries like AntiXSS and others.
 References:
 https://msdn.microsoft.com/en-us/library/hh882339(v=vs.110).aspx
 http://www.asp.net/whitepapers/request-validation
 http://www.troyhunt.com/2010/03/request-validation-dotnetnuke-and.html
 https://www.nuget.org/packages/AntiXss/
15  Critical Security Updates
Description:
 SharePoint is prone to exploitation since new threats are discovered so there is a need to fix the vulnerabilities and security problems.
 SharePoint patches can be in three form:
  1. Service Pack: include previous and new fixes and also may has new features
  2. Cumulative Update(CU): include fixes that have been reported by customer in context of support cases(monthly release)
  3. Hot fix , Public Update or Quick Fix engineering(QFE):include security fixes or fixes for problems affected by a certain customers
 Patching process needs to be planned and it will cause to bring your farm down so it’s recommended to have DR farm and also consider the below best practices when patching your SharePoint farm:
16  Max Upload Document / Max Request length
 Description:
 It’s recommended to decrease the amount in these settings “Maximum Upload Size” and “maxRequestLength” to limit the impacts of the load, response time and data capacity in the server especially in case of DoS attacks.
 Fix:
 You can follow steps in the following link https://support.microsoft.com/en-us/kb/925083 and make sure these values meet your business requirements.
 References:
 https://technet.microsoft.com/en-us/library/ee424404(office.14).aspx#Section3c
 17  Search Misconfiguration
 Description:
 Exclude Allitems.aspx
 Some contents like http://*allitems.aspx should not be accessed by a public user in the SharePoint search result
 Fix:
 We can create Crawl Rules to hide them from search result and It’s recommended to create the following crawl rules:
 http://*allitems.aspx
 http://*editform.aspx
 http://*dispform.aspx
 http://*my-sub.aspx
 http://*mod-view.aspx
 http://*itemsonhomepage.aspx
 http://*thumbnails.aspx

 References:
 https://technet.microsoft.com/en-us/library/jj219686.aspx
 Default content access account
 This account that the SharePoint Search service uses by default for crawling the contents. Avoid Grant this service account Full Control.
 Fix:
 This service account needs full read access to each web application. Under “User Policy” of a Web application , make sure this account only has “Full Read” permission.
 References:
  Persistent XSS flaw in SharePoint 2013
 Description:
This particular vulnerability, CVE-2015-2522, is caused by insufficiently sanitizing user-supplied
input in a number of input points like notes, keywords, and comments.
 For more details you can check this link
 
http://blog.fortinet.com/post/sharepoint-2013-xss-vulnerability-discovered
 Fix:
 Update your SharePoint with the latest new version of CU to address this and other issues.
 Note: Only SharePoint 2013 with version build 15.0.4571.1502 and before should update as soon as possible.
 19  Disable loopback check
 Description:
 The feature prevents access to a web application using a fully qualified domain name (FQDN) if an attempt to access it takes place from a machine that hosts that application. The end result is a 401.1 Access Denied from the web server and a logon failure in the event log.People go around this issue by wrong way (even me) because Microsoft consider this as a security feature.
 Fix:
 Don’t use “DisableLoopbackCheck” and instead of that fix it using the following registry key “BackConnectionHostNames“. You can follow the steps in this post https://support.microsoft.com/en-us/kb/896861 [First Method]
Note: You can go with “DisableLoopbackCheck” option in the development and testing servers.
 References:
 http://blogs.technet.com/b/sharepoint_foxhole/archive/2010/06/21/disableloopbackcheck-lets-do-it-the-right-way.aspx
 20  Health Check(Security)
 Description:
SharePoint Health Analyzer is a feature that enables administrators to schedule regular, automatic 
checks for potential configuration, performance, and usage problems in the server farm. 
SharePoint has four Health check rules related to Security as following:
  1. Accounts used by application pools or service identities are in the local machine Administrators group.
  2. Business Data Connectivity connectors are currently enabled in a partitioned environment.
  3. Web Applications using Claims authentication require an update.
  4. The server farm account should not be used for other services.
 Fix:
 Most of the below rules are best practices so fix these issues which has detected by the SharePoint Health Analyzer and in case you want to ignore them then make sure to have a good reason.
  1. Fix for Point 1 https://technet.microsoft.com/en-us/library/hh344224.aspx
  2. Fix for Point 2 https://technet.microsoft.com/en-us/library/jj891123.aspx
  3. Fix for Point 3 https://technet.microsoft.com/en-us/library/ff686815.aspx
  4. Fix for Point 4 https://technet.microsoft.com/en-us/library/ff805056(v=office.14).aspx
 References:
 21  DR + Documentation  Description:
 Fix:
 22  The server farm account should not be used for other services.
 Description:
 The account used for the SharePoint timer service and the central administration site, is highly
 privileged and should not be used for any other services on any machines in the server farm.
 In SharePoint Health Analyzer you could find similar warning like Accounts used by application
pools or service identities are in the local machine Administrators group or others warnings and
all related to inappropriate setup service accounts.
 Fix:
 To install SharePoint ,you have to have appropriate administrative and service accounts on servers running SharePoint and SQL Server.
 Plan for administrative and service accounts in SharePoint 2013 https://technet.microsoft.com/en-us/library/cc263445.aspx
 References:
 https://technet.microsoft.com/en-us/library/cc678863.aspx
 https://technet.microsoft.com/EN-US/library/hh377944.aspx
 23   TCP/IP Ports of SharePoint 2013
 Description:
 Learn about security hardening for SharePoint web server, application server, and database server roles,including specific hardening requirements for ports, protocols, and services.
 References:
 https://technet.microsoft.com/en-us/library/cc262849.aspx#PortProtocolService
 http://blog.blksthl.com/2013/02/21/tcpip-ports-of-sharepoint-2013/ 
 24  Require Use Remote Interfaces permission
 Description:
 It’s recommended to prevent Anonymous user from accessing Client Object Model interfaces. When this option is checked, it simply means that the user must possess the Use Remote Interfaces permission which allows access to SOAP, Web DAV and Client Object Model.
 Note:By default this option is checked in SharePoint 2013

 References:
 http://blogs.msdn.com/b/kaevans/archive/2013/10/24/what-every-developer-needs-to-know-about-sharepoint-apps-csom-and-anonymous-publishing-sites.aspx
 25  Enable Client Integration?
 Description:
 It’s recommended to disable Client integration in case of anonymous site but it will effectively block SharePoint from being a useful collaboration tool, and block all Office client interaction with SharePoint and also prevent you to work with SharePoint Designer and using Windows Explorer View.
 Note: Don’t go with this option except you evaluate the client business requirements and you extend the SharePoint site to work with SharePoint Designer and other client features.

 References:
 https://support.microsoft.com/en-us/kb/2758444
 https://support.microsoft.com/en-us/kb/981223


Monday, October 31, 2016

ASP.Net MVC Server-Side Validation

This article explains the basics of ASP.NET MVC server-side validation using the Data Annotation API. The ASP.NET MVC Framework validates any data passed to the controller action that is executing, It populates a ModelState object with any validation failures that it finds and passes that object to the controller. Then the controller actions can query the ModelState to discover whether the request is valid and react accordingly.

I will use two approaches in this article to validate a model data. One is to manually add an error to the ModelState object and another uses the Data Annotation API to validate the model data.

Approach 1: Manually Add Error to ModelState object

I create a User class under the Models folder. The User class has two properties "Name" and "Email". The "Name" field has required field validations while the "Email" field has Email validation. So let's see the procedure to implement the validation. Create the User Model as in the following:
namespace ServerValidation.Models
{
   
public class User    {
       
public string Name { get; set; }
       
public string Email { get; set; }       
    }
}

After that I create a controller action in User Controller (UserController.cs under Controllers folder). That action method has logic for the required validation for Name and Email validation on the Email field. I add an error message on ModelState with a key and that message will be shown on the view whenever the data is not to be validated in the model.
using System.Text.RegularExpressions;using System.Web.Mvc; namespace ServerValidation.Controllers
{
   
public class UserController : Controller    {       
       
public ActionResult Index()
        {           
           
return View();
        }
        [
HttpPost]
       
public ActionResult Index(ServerValidation.Models.User model)
        {
           
if (string.IsNullOrEmpty(model.Name))
            {
                ModelState.AddModelError(
"Name", "Name is required");
            }
           
if (!string.IsNullOrEmpty(model.Email))
            {
               
string emailRegex = @"^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}" +
                                        
@"\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\" +
                                           
@".)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$";
               
Regex re = new Regex(emailRegex);
               
if (!re.IsMatch(model.Email))
                {
                    ModelState.AddModelError(
"Email", "Email is not valid");
                }
            }
           
else            {
                ModelState.AddModelError(
"Email", "Email is required");
            }
           
if (ModelState.IsValid)
            {
                ViewBag.Name = model.Name;
                ViewBag.Email = model.Email;
            }
           
return View(model);
        }
    }
}

Thereafter I create a view (Index.cshtml) for the user input under the User folder.
@model ServerValidation.Models.User@{    ViewBag.Title = "Index";} @using (Html.BeginForm()) {
   
if (@ViewData.ModelState.IsValid)
    {
       
if(@ViewBag.Name != null)
        {
           
<b>                Name : @ViewBag.Name<br />                Email : @ViewBag.Email
           
</b>        }
    }     
   
<fieldset>        <legend>User</legend>
       
<div class="editor-label">            @Html.LabelFor(model => model.Name)
       
</div>        <div class="editor-field">            @Html.EditorFor(model => model.Name) 
           
@if(!ViewData.ModelState.IsValid)
            {       
               
<span class="field-validation-error">@ViewData.ModelState["Name"].Errors[0].ErrorMessage</span>
            }            
       
</div>
       
<div class="editor-label">            @Html.LabelFor(model => model.Email)
       
</div>        <div class="editor-field">            @Html.EditorFor(model => model.Email)
           
@if (!ViewData.ModelState.IsValid)
            {       
                
<span class="field-validation-error">@ViewData.ModelState["Email"].Errors[0].ErrorMessage</span>
            }         
       
</div>        <p>            <input type="submit" value="Create" />        </p>    </fieldset>}
Run the application and test in various ways

  1. When all fields are empty:

    Figure 1.1: Validation Message when both fields are empty
     
  2. When the Name field is empty but Email is not valid:

    Figure 1.2 : Validation Message when Email is not valid
     
  3. When both fields are valid:

    Figure 1.3 All Fields are valid
Approach 2: Specifying Business Rules with Data Annotation

While the first approach works quite well, it does tend to break the application's separation of concerns. Namely, the controller should not contain business logic such as, the business logic belongs in the model.

Microsoft provides an effective and easy-to-use data validation API called Data Annotation in the core .NET Framework. It provides a set of attributes that we can apply to the data object class properties. These attributes offer a very declarative way to apply validation rules directly to a model.

First create a model named Student (Student.cs) under the Models folder and applies Data Annotation attributes on the properties of the Student class.
using System.ComponentModel.DataAnnotations;namespace ServerValidation.Models
{
   
public class Student    {
        [
Required(ErrorMessage = "Name is Requirde")]
       
public string Name { get; set; }
        [
Required(ErrorMessage = "Email is Requirde")]
        [
RegularExpression(@"^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}" +
                           
@"\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\" +
                           
@".)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$",
                            ErrorMessage=
"Email is not valid")]
       
public string Email { get; set; }
    }
}
Now create an action method in the controller (StudentController class under the Controllers folder) that returns a view with a model after the post request.
using System.Web.Mvc;using ServerValidation.Models;namespace ServerValidation.Controllers
{
   
public class StudentController : Controller    {
       
public ActionResult Index()
        {
           
return View();
        }
        [
AcceptVerbs(HttpVerbs.Post)]        public ActionResult Index(Student model)
        {
           
if (ModelState.IsValid)
            {
                ViewBag.Name = model.Name;
                ViewBag.Email = model.Email;
            }
           
return View(model);
        }
    }
}

After that I created a view (Index.cshtml) to get student details and show an error message if the model data is not valid.
@model ServerValidation.Models.Student @{    ViewBag.Title = "Index";} @if (ViewData.ModelState.IsValid)
    {
       
if(@ViewBag.Name != null)
        {
           
<b>                Name : @ViewBag.Name<br />                Email : @ViewBag.Email
           
</b>        }
    } 
@using (Html.BeginForm()) {
   
@Html.ValidationSummary(true)
   
<fieldset>
       
<legend>Student</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.Email)
       
</div>        <div class="editor-field">            @Html.EditorFor(model => model.Email)
           
@Html.ValidationMessageFor(model => model.Email)
       
</div>
       
<p>            <input type="submit" value="Create" />        </p>    </fieldset>}

Image noise comparison methods

 1. using reference image technique     - peak_signal_noise_ratio (PSNR)     - SSI 2. non-reference image technique     - BRISQUE python pac...