Showing posts with label ASP.NET MVC 4. Show all posts
Showing posts with label ASP.NET MVC 4. Show all posts

Tuesday, February 14, 2017

How to use log4net in a ASP.NET Web Application

First install log4net in your application using NuGet packages.



Add the following configurations in the web.config file.

<?xml version="1.0"?>
<configuration>

  <configSections>
    <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" />
  </configSections>

  <log4net debug="true">        
    <appender name="RollingLogFileAppender" type="log4net.Appender.RollingFileAppender">
      <file value="logs/log.txt" /> 
      <appendToFile value="true" />
      <rollingStyle value="Size" />
      <maxSizeRollBackups value="10" />
      <maximumFileSize value="10MB" />
      <staticLogFileName value="true" />
      <lockingModel type="log4net.Appender.FileAppender+MinimalLock" />
      <layout type="log4net.Layout.PatternLayout">
        <conversionPattern value="%date [%thread] %-5level %logger [%property{NDC}] - %message%newline" />
      </layout>
    </appender>    

    <root>
      <level value="ALL" />
      <appender-ref ref="RollingLogFileAppender" />
    </root>
  </log4net>

</configuration>
You can find more logging formats here.

logs folders is created on the root directory path of the web application. Inside the folder log.txt file is created.
Log records are appended to the same log.txt file.
When the file size reaches 10MB it'll be renamed to log.txt.1 and it''l continue till log.txt.9.

Sample log records.

2017-02-06 13:36:41,798 [26] INFO WarehouseAPI.TaskService [(null)] - Starting task.
2017-02-06 13:36:41,878 [26] INFO WarehouseAPI.TaskService [(null)] - Completing task.

Example usage.

public class TaskService 
{
    private static readonly log4net.ILog logger =  LogManager.GetLogger(typeof(TaskService));

    public HealthTestResultClient TestHealth()
    {
        logger.Info("Testing API health.");

        return new HealthTestResultClient() { Message = msg , Success = res };
    }
}

Friday, October 7, 2016

Jquery dd/MM/yyyy date format validation ASP.NET MVC 4

download the files from https://github.com/jquery/globalize
include references to relevant .js files (You can also install it with NuGet packages as well, which is the option I have used.)
<script src="~/Scripts/globalize/globalize.js"></script>
<script src="~/Scripts/globalize/cultures/globalize.culture.en-GB.js"></script>

$(document).ready(function () {
        $.culture = Globalize.culture("en-GB");
        $.validator.methods.date = function (value, element) {
            //This is not ideal but Chrome passes dates through in ISO1901 format regardless of locale 
            //and despite displaying in the specified format.

            return this.optional(element)
                || Globalize.parseDate(value, "dd/MM/yyyy", "en-GB")
                || Globalize.parseDate(value, "yyyy-mm-dd");
        }
    });

The anti-forgery cookie token and form field token do not match ASP.NET MVC 4


I resolved the issue by explicitly adding a machine key in web.config.

Note: For security reasons don't use this key. Generate one from https://support.microsoft.com/en-us/kb/2915218#AppendixA. Don't use online one, details,http://blogs.msdn.com/b/webdev/archive/2014/05/07/asp-net-4-5-2-and-enableviewstatemac.aspx

 <machineKey validationKey="971E32D270A381E2B5954ECB4762CE401D0DF1608CAC303D527FA3DB5D70FA77667B8CF3153CE1F17C3FAF7839733A77E44000B3D8229E6E58D0C954AC2E796B" decryptionKey="1D5375942DA2B2C949798F272D3026421DDBD231757CA12C794E68E9F8CECA71" validation="SHA1" decryption="AES" />

Here's a site that generates unique Machine Keys:

Tuesday, August 2, 2016

Using Extension Methods in C#


Following is an example use of an Extension method in C#.

Imagine you have a class written by someone else and you are not allowed to do any modification to the class.

   public class Class1
    {
        public int MyProperty { get; set; }
    }

You have come up with the following calculation and want to have it in the Class1, so that others could use it without rewriting the calculation.

int sum = p.MyProperty * 5;

Now, incomes the extension method.

public static class myextention
    {
        public static int test(this Class1 p)
        {
           
            return p.MyProperty * 5;
        }
    }

After creating the extension method, you can now call the test function as it’s defined in the Class1 itself.

Class1 c = new Class1();

int extensionSum = c.test();

Tuesday, January 21, 2014

How to validate dd/MM/yyyy date format in ASP.NET MVC client validations.

The problem is JQUERY validation does not consider the culture when performing the validation. So that, it will show you "Invalid date format" error message whenever you try to submit a form with a date field, which has the format of dd/MM/yyyy.

To fix the issue we can override the default validation behavior by including JQUERY Globalization plugin.

Right click on the application on in Visual Studio and select Manage NuGet Packages.


Then type globalize on search text box and install the package, which appears on the search results.



Finally, add the below script before the body closing tag on your page.

    <script src="~/Scripts/jquery.validate.min.js"></script>
    <script src="~/Scripts/jquery.unobtrusive-ajax.js"></script>
    <script src="~/Scripts/jquery.validate.unobtrusive.js"></script>
   
    <script src="~/Scripts/globalize/globalize.js"></script>
    <script src="~/Scripts/globalize/cultures/globalize.culture.en-GB.js"></script>

    <script>
        $(document).ready(function () {
            $.culture = Globalize.culture("en-GB");
            $.validator.methods.date = function (value, element) {
                //This is not ideal but Chrome passes dates through in ISO1901 format regardless of locale
                //and despite displaying in the specified format.

                return this.optional(element)
                    || Globalize.parseDate(value, "dd/MM/yyyy", "en-GB")
                    || Globalize.parseDate(value, "yyyy-mm-dd");
            }
        });
    </script>

Tuesday, December 31, 2013

How to enable Client Side Validation for Kendo UI

Recently I was struggling with using Jquery validation in ASP.NET MVC 4 application which used Kendo UI. Except the kendo DropDownLists in a particular view, every other control fired client validations. So it had to be a problem with Kendo libraries. Finally, I added below code snippet and it started working.

Kendo DropDown:

@(Html.Kendo().DropDownListFor(m => m.SiteID)
                            .Name("SiteID")
                            .OptionLabel("Select Below...")
                            .DataTextField("Text")
                            .DataValueField("Value")
                            .Value(Model.SiteID.ToString())
                            .DataSource(ds =>
                            {
                                ds.Read("ToolbarTemplate_Categories", "EnterNewDocumentVendor");
                            })
                        )

Jquery Code:

<script>

    $(document).ready(function () {

        $.validator.setDefaults({
            ignore: ""
        });

        $("#SiteID").kendoValidator();
 
    });
</script>

Following link would be useful for newer versions of Jquery.

http://stackoverflow.com/questions/8466643/jquery-validate-enable-validation-for-hidden-fields

Tuesday, November 19, 2013

Telerik Reports for ASP.NET MVC 4 Caching issue.

I recently used Telerik reports, and i got into a problem where report viewer cached the previous versions other than refreshing the report.

I followed the sample in below link from telerik in order to generate my report.

http://www.telerik.com/help/reporting/mvc-report-viewer-extension-embedding.html

below is the code from my report viewer.

@(Html.TelerikReporting().ReportViewer()
        .Id("reportViewer1")
        .ServiceUrl("/api/reports/")
        .TemplateUrl("/Content/ReportViewer/templates/telerikReportViewerTemplate.html")
        .ReportSource(new TypeReportSource() { TypeName = "MvcReportApplication.MyReport.Report5, MvcReportApplication" })
        .ViewMode(ViewModes.INTERACTIVE)
        .ScaleMode(ScaleModes.SPECIFIC)
        .Scale(1.0)
        .PersistSession(true)
       
)

To disable the report viewer caching just change PersistSession(true) to PersistSession(false) and you are good to go.


Wednesday, July 31, 2013

Access Controls with same id using jquery in ASP.NET MVC

HTML:

@Html.RadioButton("rdoGp_PriTenant", "rdoGp_PriTenantYes", true)<label>Yes</label> @Html.RadioButton("rdoGp_PriTenant", "rdoGp_PriTenantNo", false)<label>No</label>

Let's say you have two radio buttons with same id and you want to disable them.

when you use 

$("#rdoGp_PriTenant")

it selects only the first element with the given ID.

However, when you select by attribute (e.g. id in your case), it returns all matching elements, like so: 

$("[id=rdoGp_PriTenant]").attr('disabled', 'disabled');

Working code using Jquery would be: 

Jquery:

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script> 
<script> 
 $(document).ready(function () { 
   $("[id=rdoGp_PriTenant]").attr('disabled', 'disabled'); 
 }); 
</script>

Monday, July 22, 2013

Get Page URL/Operating System (OS)/User Agent Using Jquery/JavaScript

Current Page URL - $(location).attr('href');

Operating System - navigator.platform

User Agent - navigator.userAgent

Friday, July 19, 2013

How to Use Ajax.BeginForm in ASP.NET MVC

Below example demonstrate an example use of  Ajax.BeginForm. When the user click on the submit button the form will display "Thank You" on result DIV without causing a page reload.

Model:

public class MyViewModel
{
    [Required]
    public string Foo { get; set; }
}

Controller:

public class HomeController : Controller
{
    public ActionResult Index()
    {
        return View(new MyViewModel());
    }

    [HttpPost]
    public ActionResult Index(MyViewModel model)
    {
        return Content("Thank You", "text/html");
    }
}

View:

@model AppName.Models.MyViewModel

<script src="@Url.Content("~/Scripts/jquery.unobtrusive-ajax.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.js")" type="text/javascript"></script>

<div id="result"></div>

@using (Ajax.BeginForm(new AjaxOptions { UpdateTargetId = "result" }))
{
    @Html.EditorFor(x => x.Foo)
    @Html.ValidationMessageFor(x => x.Foo)
    <input type="submit" value="OK" />
}

Tuesday, July 16, 2013

Filter/Allow Roles without using ASP.NET MVC Membership Provider

Following code demonstrate how to filter roles that are allowed to execute an action without using ASP.NET membership provider.

Create a class that inherits from ActionFilterAttribute


public class RoleFilter : ActionFilterAttribute { 

 public override void OnActionExecuting(ActionExecutingContext filterContext) 
 { 
   if (GetCurrentUserRole() != "Admin")// Check the Role Against the database Value 
    { 
     filterContext.Result = new RedirectResult("~/Redirect/NoPermission"); 
     return; 
    } 
   } 
 }

In your controller action add the RoleFilter attribute.

[RoleFilter]//Check the Role, if not allowed redirect to NoPermission view
 public ActionResult Index() 
{ 
   return View(); 
}

That's it. Now only Admin users are allowed to execute the action Index.


Saturday, July 13, 2013

Custom Error Message in ASP.NET MVC

Consider a scenario where you want to customize your error message depending on the value entered by the user.

Model:

namespace Mvc4Test.Models
{
    public class Part
    {
        [AlternateValidation(Suggetion = "Please Use 123 (This is a Suggestion)")]
        public string PartNumber { get; set; }
    }

    public class AlternateValidation : ValidationAttribute
    {
        public string Suggetion { get; set; }
     
        protected override ValidationResult IsValid(object value,ValidationContext validationContext)
        {
            if (value != null)
            {
                if (value.ToString() == "123")
                {
                    return ValidationResult.Success;
                }
                else
                {
                   
                    return new ValidationResult(Suggetion);

                }
            }else
                return new ValidationResult("Value is Null");

        }
    }
}

View:

 @Html.EditorFor(model => model.PartNumber)
 @Html.ValidationMessageFor(model => model.PartNumber)


Tuesday, July 9, 2013

Avoid showing Login page if the user is already logged in - ASP.NET MVC

To avoid showing the login page again if the user is already logged in successfully, you can use the below code in your controller action for the login view.

       [AllowAnonymous]
        public ActionResult Login(string returnUrl)
        {
            ViewBag.ReturnUrl = returnUrl;
            if (Request.IsAuthenticated)//check the user is logged in
            {
                return RedirectToAction("Index", "Home", null);// redirect to home page if authenticated
            }
            else
            return View(); // else show the login page
        }

Tuesday, June 25, 2013

Download an Image from a given URL in ASP.NET MVC

Controller action code.

public FileStreamResult Index()
{

    string aURL = "https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjafp8BY_8P6NkZcQQLgJ7eCcjNfF7sg5fTWkNaNdsb8-LbP1Qo_ZeHPyw5TFafsxqZn7ycgjQliIUYP9N0GuNEEvxJ6i9DubxnsPc0bHl1Ngg1-DYKS0h8dLOfuXd9l2JjOcR1SsATwko/s828/stuff+copycc.jpg";
    Stream rtn = null;
    HttpWebRequest aRequest = (HttpWebRequest)WebRequest.Create(aURL);
    HttpWebResponse aResponse = (HttpWebResponse)aRequest.GetResponse();
    rtn = aResponse.GetResponseStream();
    return File(rtn, "image/jpeg", "Image_1");
}