Showing posts with label .Net Instrumentation logging. Show all posts
Showing posts with label .Net Instrumentation logging. Show all posts

Fault Exceptions in WCF


Exceptions thrown by WCF service are treated as Fault exceptions. As a developer we should gracefully handle these kind of exceptions. Let's take a look at this by an example/

Service Contract -
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
[ServiceContract]
    public interface IService2
    {
        [OperationContract]
        [FaultContract(typeof(MyException))]
        [DebuggerStepThrough]
        MyException GetData(int value);
    }

    [DataContract]
    public class MyException 
    {
        [DataMember]
        public bool Result { get; set; }

        [DataMember]
        public string ErrorMessage { get; set; }

        [DataMember]
        public Exception MyInnerException { get; set; }

        [DataMember]
        public string ClientMessage { get; set; }
    }


Service Implementation -
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
public class Service1 : IService2
    {
       
        public MyException GetData(int value)
        {
            MyException mx = new MyException();
            try
            {
                double a = 44;
                if (value == 0)
                {
                    throw new DivideByZeroException();
                }
                double res = a / value;
                mx.ClientMessage = "Everything is well";
                mx.Result = true;
                return mx;
            }
            catch (DivideByZeroException dvex)
            {
                mx.Result = true;
                mx.ClientMessage = "Divide by zero";
                mx.MyInnerException = dvex;
                mx.ErrorMessage = dvex.StackTrace;
                throw new FaultException<MyException>(mx, dvex.ToString());
            }                    

        }
    }


Client (aspx.cs page) -

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
try
            {
                FaultContractsDemo.ServiceReference1.Service2Client o = new ServiceReference1.Service2Client();
                MyException data = o.GetData(0);
                if (data.Result)
                    lblMessage.Text = "All is well";
            }
            catch (FaultException<MyException> ex)
            {
                lblMessage.Text = ex.Detail.ClientMessage;
            }


The service layer throws an exception, but client never recieves any. I am getting unhandled exception like,
The underlying connection was closed: The connection was closed unexpectedly.
 WCF does not like serializing the DivideByZeroException or any root exception caused at service layer, which is necessary to get it across the wire. Commenting out this would work as expected.

LINQ update on table having no primary key


I was trying to update a record in a table last night, using LINQ. Everything was fine and running without any errors.
Surpisingly the record was not getting updated. I then attached the modified object to the context. It started giving an exception as,

Can't perform Create, Update or Delete operations on Table because it has no primary key.

Then I realised that there is no primary key assigned to the table. The possible solution was to change the database schema and add primary key 
to that table. But this change was not acceptable.
Further debugging into the code I got the workaround for this. 

When we generate a class file using a tool such as sqlmetal or anything else, certain attributes are associated with the columns of that table.
We can open that class file and manually add IsPrimary= true attribute to any one of the columns.

This will fool the LINQ engine and treat the respective column as a primary key.

Here is an example for the same.
I have generated a class with table as TableWithNoPK. It has 3 columns as Field1, Field2, Field3.
I assigned IsPrimary attribute to field1 as,

[global::System.Data.Linq.Mapping.ColumnAttribute(Name="field1", Storage="_Field1", DbType="VarChar(50)", IsPrimaryKey= true)]
        public string Field1
        {
            get
            {
                return this._Field1;
            }
            set
            {
                if ((this._Field1 != value))
                {
                    this._Field1 = value;
                }
            }
        }


The c# code goes normal as,

var qry = from NoPK in instance.TableWithNoPK
                      select NoPK;

       TableWithNoPK test = qry.FirstOrDefault();
       test.Field3 = "Gud 1";
       instance.SubmitChanges();


Instrumentation

What is Instrumentation ?
It is a process which deals with logging and measuring all the things happening at application level.

Logging Events
There are some situations where a developer cannot predict if anything is going to fail in the application may be at developer end or a customer end. A developer must track such events through some mechanisms to ensure the smooth execution of an application. In order to do this .Net framework provides System.Diagnostics namespace to log events and debug application.

There are 3 default types of event logs as;
  1. Application
  2. Security
  3. System
User can create a custom event log, if required permissions are available for this user. 

Creating an Event log:
EventLog objEventLog = new EventLog("MyApplication");
objEventLog.Source="MyApplication";
objEventLog.WriteEntry("EventLog has been created", EventLogEntryType.Information);

Event sources are registered with windows registry. Hence to write into the event log fully trusted code is required. Partially or no trusted code can cause potential harm to the application as well as user's system .

Deleting an EventLog:
EventLog provides Delete method which removes all the logged events.
EventLog.Delete("MyApplication");

Reading entries from an EventLog:
EventLog stores each event in the form of an entry. EventLogEntry object represents single entry from an EventLog. Below is the code to demonstrate how to read EventLog;
EventLog objEventLog = new EventLog("MyApplication");
objEventLog.Source="MyApplication";
foreach (EventLogEntry objEventLogEntry in objEventLog.entries)
{
      console.WriteLine(objEventLogEntry.Source);
}







Labels

.net .Net Instrumentation logging .net localization Agile amazon amazon elasticache amazon services AppDomain Application Domain architecture asp ASP.Net authentication authentication mechanisms Byte order mark c# cache canvas app cdata certifications class classic mode cloud cloud computing cluster code-behind Combobox compilation Configuration providers configurations connection connectionString constructors control controls contructor CSV CTS .net types conversion database DataGridView DataSource DataTable DataType DBML delegates design pattern dispose double encoding Entity framework Events exception handling expiry fault contracts fault exceptions function pointers functions generics help HostingEnvironmentException IIS inner join instance management integrated mode javascript join left outer join LINQ LINQ join LINQ to SQL memory leak methods microsoft model driven app modes in IIS MSIL multiple catch blocks no primary key Nullable Osmos Osmotic Osmotic communication Osmotic communications page events page life cycle partial class PMI powerapps preserve precision points private contructor ProcessExit Project management properties property protect connectionString providerName providers query regular expression repository Responsive Web Design return type run-time RWD Saas self join session session expiry sessions singelton singleton pattern software as a service source control system SQLMetal string time management time-boxing toolstrip ToolStrip controls ToolStripControlHost tortoise SVN ToString() try catch finally update wcf web application web design web site web.config where-clause xml

Pages