Wednesday, December 19, 2012

LOG 4 NET

Configutation in We..config file for Email Service for Exceptions


<configuration>
<!-- Log4Net Configuration Begin -->
<configSections>
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler,Log4net"/>
</configSections>
<log4net>
<root>
<level value="DEBUG"/>
<appender-ref ref="LogFileAppender"/>
<appender-ref ref="SmtpAppender"/>
</root>
<appender name="LogFileAppender" type="log4net.Appender.RollingFileAppender">
<param name="File" value="Logs\logFile.txt"/>
<param name="AppentToFile" value="true" />
<rollingStyle value="Date" />
<datePattern value="yyyyMMdd"/>
<staticLogFileName value="true" />
<layout type="log4net.Layout.PatternLayout">
<param name="ConversionPattern" value="%-5p%d{yyyy-MM-dd hh:mm:ss} -%m%n" />
</layout>
</appender>
<appender name="SmtpAppender" type="log4net.Appender.SmtpAppender">
<to value="abc@gmail.com" />
<from value=" abc@gmail.com " />
<subject value="UI Exception Log" />
<smtpHost value="AT-MX-01.gmial.intranet" />
<bufferSize value="512" />
<lossy value="true" />
<evaluator type="log4net.Core.LevelEvaluator">
<threshold value="WARN"/>
</evaluator>
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%newline%date [%thread] %-5level %logger [%property{NDC}] - %message%newline%newline%newline" />
</layout>
</appender>
</log4net>
<!-- Log4Net Configuration End -->
<!--Connection String-->
<connectionStrings>
<add name="connectionString" connectionString="server=BBB;user id=XXX;password=yyy;database=AAAA; persist security info=false;Connection TimeOut=3000; "/>
<add name="connectionString1" connectionString="zkJ3K6ITxu/eNIw295f1Xbw4mmXB4pSD/BhqyRLiSvKsvT/dxZVIWgSv+YeXQ2bfhV2MTMGeDx6geog4kLCqbZE5v8zVQ5Fhxb14VD3DPNTSZQbRwgenHrnOOUCqt8yyACC1YMrsF/bH/aRp8u5Z1/rNstyu7UkT+xE6l4BnFAkn0bq87L9h6vBB6yKTCViWhex9pknNbotUsCsvPd2/gpZJm0o1R6L6HyChlmA4wS4hH3Gvf6xGNzWCsTCV4kYEBdet2Tmb7Gr9VaqA5xEX73JSwOwo0HFed4SOksfcU0i73mDbPg9Nc3NMxMyh3lFdR11KI3QOLMhG0Q0SVNeNE8SZofY1dJTEukzoQ87rlsdY/auMPRkOG7N5bZzISW+HhdgS+knhqVMN4z57U6N9Bicxv/imR3sjGbMrN3hhVV+XHg34TPhS17Pkwa0Y04AFV8+MwWNQzfVFOnLIqSmdP9wtIxgJ0kkbvw/wO/DFI5YKWZvj4eF1qXfTCgHf1yNwWvW4XSluMV8UZuvaEkQqJNJnIpbZdEuDijjISPZrdnMPx2Jjn9EaXMdYJvVAxalLkFMrSFMHhLRJRqvKfpINXUrAVwaJKSCiiXlMLlbMou8+UudO7vK9RCUuluHprJnoCn6wLoXK1geYl3zY9/Mb7SS9J4o7xNSamQHu9+MBs76AT5y2p5lTGFUTqX6f0nHSATg3MKMU6p/Z21X7Q0d+Iw=="/>
</connectionStrings>
<!—End Connection String-->
</configuration>


2) add Reference for log4net.dll andCreate a Class File named clsLog4netUI and  write as follows
in clas file

using System.Web;
using log4net;
using log4net.Config;
using log4net.Core;
using log4net.Appender;
using log4net.Repository.Hierarchy;
using log4net.Layout;

namespace MyProjectName
{
    public class clsLog4netUI
    {
        protected static readonly ILog logger = LogManager.GetLogger(typeof(clsLog4netUI));
        public clsLog4netUI()
        {
            log4net.Config.XmlConfigurator.Configure();
        }

        public void Debug(string ex)
        {
            logger.Debug(ex);
        }
        public void Info(string ex)
        {
            logger.Info(ex);
        }
        public void Error(string ex)
        {
            logger.Error(ex);
        }
        public void Fatel(string ex)
        {
            logger.Fatal(ex);
        }
    }
}


3) In aspx.cs file create an object for clsLog4netUI 

        clsLog4netUI objLog = new clsLog4netUI();

in
try             
{
}
catch (Exception ex)
 {
    objLog.Error(ex.ToString());
 }

Thats it with proper Configuration in web.config it will send an email to the Email address given in we.config file

we can implemete this same thing in WCF Service and UI also where we can get exceptions.. 


Tuesday, July 10, 2012

WCF REST Service Consuming the Methods and Error Handling


private void Method3()
{
try
{
string URL = "http://Bookservices.intranet/Services/LibraryBookService.svc/insertBook";
string xmlTemplate = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>"
+ "<BookOrders>"
+ "<BookID>xxxx</BookID>"
+ "<BookName>215786</BookName>"
+ "<CustomerID>175254</CustomerID>"
+ "<RequestedDate>12/12/12</RequestedDate>"
+ "<Title>One</Title>"
+ "<Description>Two</Description>"
+ "</BookOrders>";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(@URL);
request.Method = "POST";
byte[] byteArray = Encoding.UTF8.GetBytes(xmlTemplate);
request.ContentType = "application/xml";
request.ContentLength = byteArray.Length;
Stream dataStream = request.GetRequestStream();
dataStream.Write(byteArray, 0, byteArray.Length);
dataStream.Close();

HttpWebResponse response = (HttpWebResponse)request.GetResponse();
StreamReader reader = new StreamReader(response.GetResponseStream());
string xmlString = reader.ReadToEnd();
}
catch (Exception ex)
{
string xmlErrorTemplate = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>"
+ "<ErrorDetails>"
+ "<HtmlStatusCode>HtmlStatusCode</HtmlStatusCode>"
+ "<StatusDescription>StatusDescription</StatusDescription>"
+ "</ErrorDetails>";
string request;
XmlDocument xDoc = new XmlDocument();
xDoc.LoadXml(xmlErrorTemplate);
XmlNodeList xNodeList = xDoc.SelectNodes("/ErrorDetails");
foreach (XmlNode xn in xNodeList)
{
xn["HtmlStatusCode"].InnerText = HttpContext.Current.Response.StatusCode.ToString();
xn["StatusDescription"].InnerText = "Method Name is not Correct..";
request = xn.OuterXml;
Label1.Text = request;

}
}


}

Wednesday, July 4, 2012

WCF With Rest Service Configuration


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

<system.web>
<compilation debug="true" targetFramework="4.0" />
</system.web>
<connectionStrings>
<add name="connectionString" connectionString="server=XXX;user id=zzz;password=aaaa;database=DBNAME; persist security info=false;Connection TimeOut=3000; " />
</connectionStrings>
<system.serviceModel>
<services>
<service name="TestRestService.Service1" behaviorConfiguration="XmlServiceBehaviour" >
<endpoint address=""
binding="webHttpBinding"
contract="TestRestService.IService1"
behaviorConfiguration="web"></endpoint>
</service>
</services>
<!--END OF CHANGE #1-->
<bindings />
<client />
<behaviors>
<serviceBehaviors>
<!--CHANGE #2-->
<behavior name="XmlServiceBehaviour">
<!--END OF CHANGE #2-->
<!-- To avoid disclosing metadata information, set the value below to false and remove the metadata endpoint above before deployment -->
<serviceMetadata httpGetEnabled="true"/>
<!-- To receive exception details in faults for debugging purposes, set the value below to true. Set to false before deployment to avoid disclosing exception information -->
<serviceDebug includeExceptionDetailInFaults="false"/>
</behavior>
</serviceBehaviors>
<!--CHANGE #3-->
<endpointBehaviors>
<behavior name="web">
<webHttp/>
</behavior>
</endpointBehaviors>
<!--END OF CHANGE #3-->
</behaviors>
<serviceHostingEnvironment multipleSiteBindingsEnabled="true" />
</system.serviceModel>
<system.webServer>
<modules runAllManagedModulesForAllRequests="true"/>
</system.webServer>
</configuration>


Note:

<!--CHANGE #1-->
<!-- Name: TestRestService.Service1 is the NameSpace/Class
Behaviour Config: XmlServiceBehaviour is UserDefined
Contract: TestRestService.IService1 is NameSpace/Interface-->
<!-- IN Change #2 Change #2 behavior name=Change #1 behaviorConfiguration

I.e, Name=BehaviourConfig-->


and In Interface

[ServiceContract]
public interface IService1
{
[OperationContract]
//attribute for returning JSON format
[WebInvoke(Method = "GET",
ResponseFormat = WebMessageFormat.Json,
BodyStyle = WebMessageBodyStyle.Wrapped,
UriTemplate = "ListJson/{UserID}")]
string ListJson(string UserID);
}


Monday, July 2, 2012

XML Converstions in ASP.net


XmlDocument xDoc = (XmlDocument)JsonConvert.DeserializeXmlNode(EntityIDList);
            //string xNode = xDoc.OuterXml;
            if (EntityIDList != null && EntityIDList != "")

                ObjListBO.EntityIdList = xDoc.OuterXml.Replace("<RootXML>", "").Replace("</RootXML>", "");

Converting the DataSet Details into XML Format of String in ASP.Net
---------------------------------------------------------------


Public string GetDetails(int UserID, int Psw)
{
DataSet ds = new DataSet();

SqlParameter[] sqlParam = new SqlParameter[2];
try
{
sqlParam[0] = new SqlParameter("@UserID", SqlDbType.Int) { Direction = ParameterDirection.Input, Value = UserID };
sqlParam[1] = new SqlParameter("@Psw", SqlDbType.Int) { Direction = ParameterDirection.Input, Value = Psw };
ds = SqlHelper.ExecuteDataset(myConn, CommandType.StoredProcedure, "SP_GetUser", sqlParam);
xmlDoc = new XmlDocument();
XmlDocument xDoc = new XmlDocument();
if (ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
{
xmlDoc.LoadXml(ds.GetXml());
XmlNodeList xnList = xmlDoc.SelectNodes("/NewDataSet/Table");
outResultXml = "<Root>";
foreach (XmlNode xn in xnList)
{
outResultXml += "<User>";
outResultXml += xn.InnerXml;
outResultXml += "</User>";
}
outResultXml += "</Root>";
}
}
catch (Exception ex)
{
throw ex;
}
return outResultXml;
}