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