How to use Log4Net with WCF in DOT NET

May 14, 2016 2 comments

This post will help you to configure LOG4NET with WCF Application , Log4Net is basically a logging engine which have many advanced feature to help you completely in your logging need of your application

So lets break the implementation in step basis.

Step 1.

Download the log4Net from any authorized source like :(https://www.nuget.org/packages/log4net/) or (https://logging.apache.org/log4net/download_log4net.cgi)

after downloading reference your LOG4Net in your project as below

1

Step 2.

Configure your Configuration File (Web.config) as below


 <configSections>
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler"/>
</configSections>
<log4net>
<!-- RollingFile is set to be a File Appender -->
<appender name="RollingFile" type="log4net.Appender.RollingFileAppender">
<file value="log4netLogging.log" />
<appendToFile value="true" />
<maximumFileSize value="1MB" />
<maxSizeRollBackups value="2" />
<datePattern value="yyyyMMdd" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date [%thread] %-5level %-50logger %-20method - %message%newline%newline" />
</layout>
</appender>
<!-- Set root logger level to DEBUG and its only appender to RollingFile -->
<root>
<level value="DEBUG" />
<appender-ref ref="RollingFile" />
</root>

</log4net>
</configuration>

Step 3.
Make a class that will act as base class for your other class wherever you would like to use the logging.


public class ServiceBase
{
private readonly ILog log;
public ServiceBase()
{
//Load log4net Configuration
XmlConfigurator.Configure();
//Get logger
log = LogManager.GetLogger(typeof(ServiceBase));
//Start logging
log.Debug(&amp;amp;quot;ServiceBase Constructor calling&amp;amp;quot;);

}
}

Step 4.

Now Implement above created base class to your service and use the log.


public class Service1 : ServiceBase, IService1
{
private readonly ILog log;
public Service1() : base()
{
//Get logger for Service1
log = LogManager.GetLogger(typeof(Service1));
}

public string GetData(int value)
{
log.Info(&amp;amp;quot;Entering GetValue()&amp;amp;quot;);

return string.Format(&amp;amp;quot;You entered: {0}&amp;amp;quot;, value);
}

}

Now you can run and go to your project , log file will be created there

If you face any issue then you can reach out me at ::https://www.facebook.com/kumar20sujeet

You can  download Source code from my GITHUB Repository from :Here

Categories: WCF Tags:

Why to use entity framework(EF)

March 26, 2014 Leave a comment

As we know that there are numbers of data access technology available these day like ADO.NET , LINQ to SQL and NHIBERNATE that working fine then why does any of us want to adopt new technology , why should I adopt or learn this new technology or rather what problem they sort out that existing technology could not efficiently . So lets explore these technology the way these let us connect and work with database then the answer of why to use EF will come out.

Entity Framework vs ADO.NET

ADO.NET

  1. You write code against Database object like table , store procedure etc.
  2. You managing the connection life like (open, close) to database .
  3. If you change databse in future then you have to change your code specific to that provider .

Entity Framework(EF)

  1. You write data access code against domain object rather than database object
  2. Entity framwork managing the whole things like creating database connection , executing query , processing result , tracking changes to the object so you are totally focusing on you r business logic rather than database things hence amount of code you have to write for database operation is reduced .
  3. In EF , query is written the form of LINQ ,Entity SQL and then it translated by provider to specific back end query syntax so if you change database in future then there are not much impact.

So by going through above comparision between EF and ADO.NET its clear that EF has great potential as data access technology over ADO.NET🙂

Entity Framework vs LINQ to SQL:

LINQ to SQL

  1. LINQ to SQL support only SQL SERVER.
  2. LINQ to SQL class supoprt one-to-one map with database objects like Employee class can be mapped only with Employee table.

Entity Framework

  1. Entity framework has support for full provider .
  2. You can map your domain class with numbers of table using feature TPT , TPH of EF.
  3. There are number of way you can use EF like Database first , Model first, code First.
  4. It is open source and Microsoft soft has long term strategy for this technology.

So if you reading from top top to this line then I think it is clear to you now that WHY we would use Entity framework over other technology .

I would be happy to hear your feedback , correction in this article ,enhancement to this article .

 

Categories: Entity framework Tags:

Strongly-typed Custom HtmlHelper in ASP.NET MVC 4

January 6, 2014 Leave a comment

In this post you are going to see how  we can create Strongly-typed Custom  HtmlHelpers in ASP.NET MVC , you can see simple Custom  HtmlHelpers in ASP.NET MVC here .

So before creating Custom  Strongly-typed HtmlHelpers  , let’s see why we need Strongly-typed HtmlHelpers  if we have HtmlHelpers  in mvc already . So lets see below that use an untyped Html helper.

    <%= Html.TextBox(“Name”) %>

It is working as expected but sometime in future  you changed your class Name property from Name to EmplyeeName and same time you did not update View for this property and now your site is in live as you would be not getting any error about this mismatch between view and model at compile time and user on site experiencing that name is not working properly as this is expected as  EmplyeeName while binding view stuff to model property. So I need a mechanism that gets checked at compile time rather than run time that’s where  Strongly typed Html helper come into the picture.  Now see how Strongly typed HTML helper work and its syntax

 <%= Html.TextBoxFor(model => model.Name) %> //Strongly typed HTML helper

If you using Strongly typed HTML helper and changes Name to EmplyeeName then view compilation will be failed. Now , I think you got typed and untyped HTML Helper and its advantage too, so lets proceed to create Strongly-typed Custom  HtmlHelpers.

To create Strongly-typed Custom  HtmlHelpers , you use two classes

ExpressionHelper — Gets the model name from a lambda expression . This is used as ID and name of the field.
ModelMetadata    —  Gets other information about the lambda expression, including its value

so lets see code for it that will use both ExpressionHelper and ModelMetadata    classes

[sourcecode language="csharp"]
namespace MVC4CustomHelper.Helper
{
    public static class CustomHelper
    {
       public static MvcHtmlString CustomTextBox(this HtmlHelper htmlHelper,string name, string value)
        {
            var builder = new TagBuilder("input");
            builder.MergeAttribute("type", "text");
            builder.MergeAttribute("name", name);
            builder.MergeAttribute("value", value);
            return MvcHtmlString.Create(builder.ToString(TagRenderMode.SelfClosing));
        }
       public static MvcHtmlString CustomTextBoxFor<TModel, TProperty>
                  (this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression)
        {
	    // name and ID for Html output
            var name =     ExpressionHelper.GetExpressionText(expression);

            //value for html control
            var metadata = ModelMetadata.FromLambdaExpression(expression,htmlHelper.ViewData);

            return CustomTextBox(htmlHelper, name, metadata.Model as string);
        }

    }
}
[/sourcecode]

Now take references in View or can take references in web config too

[sourcecode language="csharp"]
<%@ Import Namespace="MVC4CustomHelper.Helper" %>
[/sourcecode]

Using created Custom Html Helper method in view

[sourcecode language="csharp"]
<%= Html.CustomTextBoxFor(model => model.Name )%>
[/sourcecode]

you you like this post then do not forget to like and comments🙂

Categories: ASP.NET MVC Tags:

Custom HTML Helper in MVC 4

January 6, 2014 Leave a comment

If you have worked on MVC before then you must know that there are numbers of built in Html helper method are in MVC  like Html.ActionLink(),Html.RadioButton(),Html.TextArea(),Html.TextBox() etc .So When  a helper method is called in a View using the razor syntax @Html or <%= Html.LabelFor() , Then we actually using  the Html property of the View, which is an instance of the HtmlHelper class.

So to create a custom HTML Helper
— create extension methods for HtmlHelper class.
— System.Web.Mvc.Html contain the extension methods for Html Helper method.
So let’s Create an Custom Html Helper method

Step 1) create extension methods for HtmlHelper class.

namespace MVC4CustomHelper.Helper
{
    public static class CustomHelper
    {
        public static MvcHtmlString CustomTextBox(this HtmlHelper htmlHelper,string name,string value)
        {
            var builder = new TagBuilder("input");
            builder.MergeAttribute("type", "text");
            builder.MergeAttribute("name", name);
            builder.MergeAttribute("value", value);
            return MvcHtmlString.Create(builder.ToString(TagRenderMode.SelfClosing));
        }

    }
}

Step 2) Taking reference in using View and using it

<%@ Import Namespace="MVC4CustomHelper.Helper" %>

Using created Custom Html Helper method

<%= Html.CustomTextBox("Name",Model.Name )%>

you will notice that it give Intellisense for Custom Html Helper method.
If you like this post the do not forget to like or comment on this🙂

Categories: ASP.NET MVC Tags:

Custom Action filter in MVC 3

January 5, 2014 Leave a comment

As we know that there are numbers of attribute based filter are provided by MVC framework , but in case that all does not meet our requirement we can create our own custom filter and resister it in our application.so before proceeding with this blog post i would recommend you to visit my blog post Filter in MVC to have basic understanding of what actually filter is and its scope in MVC .

So to create Custom Action filter

–Create a class that would either inherit from ActionFilterAttribute or implement IActionFilter, IResultFilter
–Then use this class as attribute on action method or Controller class.
–Or you can register it globally using Global.asax that basiccaly called Global Action filter that is new feature of MVC 3

let’s first create a class that would either inherit from ActionFilterAttribute

public class MVC3CustomActionAttribute : ActionFilterAttribute//(IActionFilter, IResultFilter)
    {
        public override void OnResultExecuted(ResultExecutedContext filterContext)
        {

        }
        public override void OnResultExecuting(ResultExecutingContext filterContext)
        {
            ViewResult view = filterContext.Result as ViewResult;
            if (view != null)
            {
                view.ViewBag.Message = "Changed in OnResultExecuting" + view.ViewData["Message"].ToString();
            }
        }
    }

Then use this class as attribute on action method

[MVC3CustomAction]
public ActionResult Index()
{
   ViewBag.Message = "Modify this template to jump-start your ASP.NET MVC application.";
   return View();
}

Or register it globally using Global.asax

public class MvcApplication : System.Web.HttpApplication
    {
        protected void Application_Start()
        {

            RegisterGlobalFilters(GlobalFilters.Filters);

        }
        public static void RegisterGlobalFilters(GlobalFilterCollection filters)
        {

            filters.Add(new MVC3CustomActionAttribute());

        }
    }
}

Do not forget to like or comment🙂

Categories: ASP.NET MVC Tags:

Filter In MVC 3

January 5, 2014 Leave a comment

What is Filter

–As per MSDN “Filters are classes that provide both a declarative and programmatic means to add pre-action and post-action behavior to controller action methods.

–It let perform logic either before an action method is called or after an action method runs.” like before executing an action method of controller you want to process some business logic or some kind validation or checking upon which you determine to excute action method or not or your custome requirements

Kinds of filter in MVC 3

1) Authorization filters
2) Action filters
3) Result filters
4) Exception filters

Note : Filters run in sequence as stated above from 1 to 4

Now lets explore all of them in bit details

1) Authorization filters

–It implement IAuthorizationFilter
–It performe authentication or validate properties of the request.
–The AuthorizeAttribute class and the RequireHttpsAttribute class is example of it ,
–Authorization filters run before any other filter and used as below

[Authorize]
[RequireHttps]
public ActionResult Index()
{
}

2) Action filters

–It implement IActionFilter
–The IActionFilter interface declares two methods: OnActionExecuting and OnActionExecuted.
–OnActionExecuting runs before the action method.
–OnActionExecuted runs after the action method
–OnActionExecuted can do additional processing, like providing extra data to the action method, inspecting the return value, or canceling execution of the action method on which it is applied.

3) Result filters

–implement IResultFilter
–IResultFilter declares two methods: OnResultExecuting and OnResultExecuted
–The OutputCacheAttribute class is one example of a result filter

[OutputCache]
public ActionResult Index()
{
}

4) Exception filters

–It implement IExceptionFilter
–It execute if there is an unhandled exception thrown during the execution of the ASP.NET MVC pipeline
–The HandleErrorAttribute class is one example of an exception filter.

[HandleError]
public class HomeController : Controller
{
}

There are four way you can Create filter

–Override one or more of the controller’s On<Filter> methods.
–Create an attribute class that derives from ActionFilterAttribute and apply the attribute to a controller or an action method.
–Register a filter with the filter provider (the FilterProviders class).
–Register a global filter using the GlobalFilterCollection class.

Categories: ASP.NET MVC Tags:

Custom validation in ASP.NET MVC 3

January 1, 2014 Leave a comment

As you may know that you can implement validation using validation attributes that come in (System.ComponentModel.DataAnnotations namespace) in MVC , although there are numbers of  validation attributes are provided by the framework like  [Required], [Range],  [StringLength], Compare and [RegularExpression]  but it might not fulfill your business requirements, in this case you can write your own validation attribute and use the way you use framework validation attribute so to use custom validation , first write a class that inherit from abstract ValidationAttribute class and  override virtual  IsValid method with your business requirement of this class and then use it as validation attributes.  let’s implement a basic CreditCard custom validation rule .

Step 1  : Writing a class that inherit from ValidationAttribute class

public class CreditCardAttribute : ValidationAttribute
    {
        public override bool IsValid(object value)
        {
            var number = Convert.ToString(value);
            if (String.IsNullOrEmpty(number))
                return true;

            return IsValidCardNumber(number);
        }

        private bool IsValidCardNumber(string cardNumber)
        {
            if (Regex.IsMatch(cardNumber, "^(4)"))
                return cardNumber.Length == 16;
            return false;
        }

        public override string FormatErrorMessage(string name)
        {
            return "The " + name + " field contains an invalid credit card number.";
        }
    }

Step 1 : Putting this as validation attribute

public class User
    {
        [CreditCard]
        public string CreditCard { get; set; }
    }

I hope I could put as simple as possible . Thanks for being around on this post🙂.

Categories: ASP.NET MVC Tags:
Follow

Get every new post delivered to your Inbox.

%d bloggers like this: