Tuesday, February 14, 2017

How to use log4net in a ASP.NET Web Application

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>
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 };
    }
}

Tuesday, December 6, 2016

How To Fire Child Web Control Event in Parent Web Control in ASP.NET

Consider two web parts "BooKTicket.ascx" (Parent web part) and "Passenger.ascx" (Child web part). Passenger.ascx has a RadioButtonList and on selected index changed event of that control, I need to perform some activity in the parent web part.

<%-- Passenger.ascx --%>
<div class="passenger-number-holder row form-group" style="padding-top:5px">
        <div class="col-md-3">
            <asp:Label ID="lblBoardingPass" runat="server" Text="Boarding Assistance Required" AssociatedControlID="ddlTravelPass" />
        </div>
        <div class="col-md-6">
            <asp:RadioButtonList ID="rdoListBoardingAssistance" runat="server" RepeatDirection="Horizontal" AutoPostBack="true" OnSelectedIndexChanged="rdoListBoardingAssistance_SelectedIndexChanged" OnPreRender="rdoListBoardingAssistance_PreRender">
                <asp:ListItem Value="1">Yes</asp:ListItem>
                <asp:ListItem  Selected="True" Value="0">No</asp:ListItem>

            </asp:RadioButtonList>
        </div>

    </div>

//Passenger.ascx.cs

//Create a Event Handler
public event EventHandler rdoUpdated;

//Call the evnt handler on SelectedIndexChanged event of RadioButtonList
 protected void rdoListBoardingAssistance_SelectedIndexChanged(object sender, EventArgs e)
 {
    rdoUpdated(this, EventArgs.Empty);
 }
<%-- BookTicket.ascx --%>
<%@ Control Language="C#" AutoEventWireup="true" CodeFile="BookTickets.ascx.cs" Inherits="Day3.VLine.Website.WebParts.CMSWebParts_VLine_JourneyPlanner_BookTickets" %>
<%@ Register Src="~/CMSWebParts/VLine/JourneyPlanner/Passengers.ascx" TagPrefix="line" TagName="Passengers" %>

<asp:UpdatePanel ID="udpUpdate" runat="server" ChildrenAsTriggers="false" UpdateMode="Conditional">
  <ContentTemplate>
    <%-- Hook up the event OnrdoUpdated --%>
    <line:Passengers runat="server" ID="Passengers" OnrdoUpdated="Passengers_rdoUpdated"  />
    <asp:Button ID="btnNext" runat="server" Text="Next"/>
  </ContentTemplate>
</asp:UpdatePanel>
//Add this method in BookTicket.ascx.cs
protected void Passengers_rdoUpdated(object sender, EventArgs e) { UpdateButtonTextOnChange("passenger"); } private void UpdateButtonTextOnChange(string sender) { if(sender == "passenger") { btnNext.Text = "Next - Updated Text"; udpUpdate.Update(); } }

Monday, December 5, 2016

C++ Link List Questions and Answers

 
1. Following Link List shown in Diagram A needs to be converted to the Link List given in   Diagram B. Show all the steps needed to do the conversion using the given Link object pointers.


Answer-01  
    
    P3 = P3→Next
    P3→Next = First→Next
    First→Next = P3
    P2 = P2→Next
    P2→Next = NULL


2. The following ordered Link List is given to you, write a method called orderedInsert to insert a Link at the correct position.(Hint: Ordered list is a Link List where the elements are sorted in either Ascending or Descending order)


Answer

void LinkedList::orderedInsert(int value)
    {
        Link *previous = first, *current = first;
        while (current!=NULL)
        {
            if (value < current→dData)
            {
               break;   
            }
            else
            {
                previous = current;
                current = current→next; 
            }
        }
           Link *newLink = new Link(value);
        NewLink→next = current;
        if (current == first)
           first = newLink; 
        else 
           previous→next = newLink;
    }

3. Implement a destructor for the LinkedList class.

LinkList::~LinkList()
   {
      cout << "Destructor called";
      Link *current = first;       // start at beginning of list
      Link *previous = current;
      while(current != NULL)      // until end of list,
      {
         previous = current;
         current = current->next;  // move to next link
         delete previous;

      }
   }

4. Show step by step how binary search would search for the following items from the data array given below.

(a) Search for 67
(b) Search for -90
(c) Search for 89

Data Array

0 1 2 3 4 5 6 7 8 9
        10   20    40     67 78 79 85 90 95 125
↑                                                                        ↑
bottom                                                          top





Sunday, December 4, 2016

ASP.NET - Read/Order Cookies by Expiration Date

The Short Answer - You cannot read the cookie's expiration date and time.

The browser is responsible for managing cookies, and the cookie's expiration time and date help the browser manage its store of cookies. Therefore, although you can read the name and value of a cookie, you cannot read the cookie's expiration date and time. When the browser sends cookie information to the server, the browser does not include the expiration information. (The cookie's Expires property always returns a date-time value of zero.)
You can read the Expires property of a cookie that you have set in the HttpResponse object, before the cookie has been sent to the browser. However, you cannot get the expiration back in the HttpRequest object.

If you really want to get the expiration, then you'd have to store it in the cookie itself:
Set
DateTime exp = DateTime.Now.AddDays(1);
HttpCookie PreferredCookie = new HttpCookie("PreferredCookie");
PreferredCookie.Values.Add("cookieType", "Zref");
PreferredCookie.Values.Add("exp", exp.ToString());
PreferredCookie.Expires = exp;
Response.Cookies.Set(PreferredCookie);
Get
HttpCookie PreferredCookie = Request.Cookies["PreferredCookie"];
if (PreferredCookie != null)
{
    CookieLiteral.Text = "Value = " + PreferredCookie["cookieType"] + "<br>";
    CookieLiteral.Text += "Expires = " + PreferredCookie["exp"];
}
else
{
    CookieLiteral.Text = "No Cookie";
}