Showing posts with label C#. Show all posts
Showing posts with label C#. Show all posts

Monday, February 6, 2017

Controlling Session Behavior in ASP.Net MVC

Introduction

ASP.NET MVC supports session state. As we know sessions are used to store data used across requests. ASP.NET MVC manages session data whether or not we store data in the session. Now with MVC, we can disable the session for the controller. This concept is called a sessionless controller.

Sessionless Controller

It is possible to disable the session for a controller. It may be that some of the controllers of our application do not use the session state feature. We can disable the session for those controllers using the SessionStateAttribute (set session state Behavior to Disabled) and we can get a slight performance improvement for our application.

Example
[SessionState(System.Web.SessionState.SessionStateBehavior. Disabled)]
public class HomeController : Controller
{
          ……
          ……
}
If we mark our controller as sessionless and we still try to access a session within the controller then it throws the exception “Object reference not set to an instance of an object”.

Example code
[SessionState(System.Web.SessionState.SessionStateBehavior. Disabled)]
public class HomeController : Controller
{
   
 public ActionResult Index()
    {
        ViewBag.Message =
 "Welcome to ASP.NET MVC!";
        Session[
"test"] = "Session less controller test";
       
 return View();
    }
}
Output


Session State Behavior

The SessionState attribute in MVC provides more control over the behavior of the session state by specifying the value of the behavior property (this is a read-only property but we can set it using a parameterized contractor of the SessionStateAttribute).

Enumeration Value
Description
Default
The default ASP.NET logic is used to determine the session state behavior for the controller.
Required
Full read and write session state behavior is enabled for the request.
ReadOnly
Read-only session state is enabled for the request. In other words we can read the data from the session but we cannot write the data into the session.
Disabled
Session State is disabled for the current request.
Session less controller and TempData

TempData in MVC uses session state internally to store the data. So when we disable the session state for the controller, it will throw the exception as below.
[SessionState(System.Web.SessionState.SessionStateBehavior.Disabled)]
public class HomeController : Controller
 
   
 public ActionResult Index()
    {
        ViewBag.Message =
 "Welcome to ASP.NET MVC!";
        TempData[
"test"] = "session less controller test";
       
 return View();
    }
}
Output
 Conclusion

The SessionState attribute specifies the session state behavior at the controller level. This attribute is a class level attribute so we cannot use it in a method (or at an action level). This attribute is very useful when we require specific behavior of session state for a specific controller. For example, for any controller, we do not want to use a session state; at this time we can mark this controller with the SessionState attribute and the behavior is disabled.




Reference ; http://www.c-sharpcorner.com/UploadFile/ff2f08/controlling-session-behavior-in-Asp-Net-mvc/

Sunday, January 22, 2017

WCF REST Error Handling And Custom Header

REST, or Representational State Transfer represents an architectural style for building distributed applications. When applied to the world of web services, REST is most commonly used to refer to the transmission of XML over HTTP, and the identification of XML resources via URIs. According to REST, HTTP, XML and URIs provide all the infrastructure for building robust web services, and most developers can therefore safely skip over the pain of learning SOAP and WSDL. If you are new to REST, check out Paul Prescod’s excellent REST articles on xml.com.

A major element of web services is planning for when things go wrong, and propagating error messages back to client applications. However, unlike SOAP, REST-based web services do not have a well-defined convention for returning error messages. In fact, after surveying a number of REST-based web services in the wild, there appear to be four different alternatives for handling errors. Below, I outline the four alternatives, and then provide my opinion on which option or combination of options is best.

Option 1: Stick to HTTP Error Codes

In this scenario, the web service propagates error messages via standard HTTP Error Codes. For example, assume we have the following URL:

http://www.example.com/xml/book?id=1234&dev_token=ABCD1234

This service expects a single parameter: id indicating a book ID. The service extracts the idparameter, does a database look-up and returns an XML representation of the specified book. If the URL specifies an invalid or obsolete id parameter, the service returns an HTTP 404 Not Found Error Code.

Option 2: Return an Empty Set

In this scenario, the web service always returns back an XML document which can have 0 or more subelements. If some error occurs, an XML document with zero elements is returned. The O’Reilly Meerkat news service currently uses this approach. For example, the following URL connects to Meerkat and requests all Linux related articles from the past two days, and formats the results in RSS 0.91:

http://www.oreillynet.com/meerkat/?c=cat10&t=2DAY&_fl=xml

Now, try specifying an invalid category. For example, set c =ten, like this:

http://www.oreillynet.com/meerkat/?c=ten&t=2DAY&_fl=rss


In this case, Meerkat returns an RSS document with zero item elements. This indicates that there are no matching results, but it does not indicate whether this is a valid category ID which contains no news items, or an invalid category ID.

Option 3: Use Extended HTTP Headers

In this scenario, the web service always returns an HTTP 200 OK Status Code, but specifies an application specific error code within a separate HTTP Header. The Distributed Annotation System (DAS) currently uses this alternative approach. For example, the following URL requests sequence data from Human Chromosome 1 from the Ensembl DAS Server:

http://servlet.sanger.ac.uk:8080/das/ensembl1533/sequence?segment=1:100000,100100

Now, try issuing this request for Human Chromosome 30 (there is no human chromosome 30!):

http://servlet.sanger.ac.uk:8080/das/ensembl1533/sequence?segment=30:100000,100100


If you click on the link above, you will see an empty page. However, if you have network sniffer, you can see the following HTTP response:

HTTP/1.1 200 OK
Server: Resin/2.0.5
Content-Encoding: gzip
X-DAS-Version: 1.5
X-DAS-Server: DazzleServer/0.98 (20030508; BioJava 1.3)
X-DAS-Capabilities: dsn/1.0; dna/1.0; types/1.0;
stylesheet/1.0; features/1.0; encoding-dasgff/1.0;
encoding-xff/1.0; entry_points/1.0; error-segment/1.0;
unknown-segment/1.0; component/1.0; sequence/1.0
X-DAS-Status: 403
Content-Type: text/plain
Content-Length: 10
Date: Sun, 30 Nov 2003 21:02:13 GMT


As you can see, the DAS server has returned an HTTP 200 OK Status code and a required X-DAS-Status code. In this case, the code 403 refers to a DAS Specific error code: “Bad reference object (reference sequence unknown)”.

Option 4: Return an XML Error Document

In this scenario, the web service always returns an HTTP Status Code of 200, but also includes an XML document containing an application specific error message. The XooMLeapplication currently uses this approach (XooMLe provides a RESTful API wrapper to the existing SOAP based Google API). For example, the Google API requires that you specify a valid developer token. If you specify an invalid token, XooMLe returns an XML error document. As the XooMLe documentation puts it, “If you do something wrong, XooMLe will tell you in a nice, tasty little XML-package.” For example, try this URL:

http://xoomle.dentedreality.com.au/search/?hl=en&ie=ISO-8859-1&key=&q=oreilly+php

The request does not include a Google developer token. Hence, XooMLe returns back the following XML document:
<?xml version="1.0" ?>
<xoomleError>
 <method>doGoogleSearch</method>
 <errorString>Invalid Google API key supplied</errorString>
 <arguments>
  <hl>en</hl>
  <ie>ISO-8859-1</ie>
  <key></key>
  <q>oreilly php</q>
 </arguments>
</xoomleError>

The Amazon.com web services API also follows this approach, and each returned XML document can specify an ErrorMsg element. For example, see the Amazon.com Dev-Lite Schema.

Best Practices for REST Error Handling

Assuming you are busy implementing a REST-based web service, which error handling option do you choose? I don’t believe there are (yet) any best practices for REST error handling (for an overview of other best REST practices, see Paul Costello’s REST presentation, in particular [Side 59].)

Nonetheless, here are my votes for most important criteria:


  • Human Readable Error Messages: Part of the major appeal of REST based web services is that you can open any browser, type in the right URL, and see an immediate response — no special tools needed. However, HTTP error codes do not always provide enough information. For example, if we take option 1 above, and request and invalid book ID, we get back a 404 Error Code. From the developer perspective, have we actually typed in the wrong host name, or an invalid book ID? It’s not immediately clear. In Option 3 (DAS), we get back a blank page with no information. To view the actual error code, you need to run a network sniffer, or point your browser through a proxy. For all these reasons, I think Option 4 has a lot to offer. It significantly lowers the barrier for new developers, and enables all information related to a web service to be directly viewable within a web browser.
  • Application Specific Errors: Option 1 has the disadvantage of not being directly viewable within a browser. It also has the additional disadvantage of mapping all HTTP error codes to application specific error codes. HTTP status codes are specific to document retrieval and posting, and these may not map directly to your application domain. For example, one of the DAS error codes relates to invalid genomic coordinates (sequence coordinate is out of bounds/invalid). What HTTP error code would we map to in this case?
  • Machine Readable Error Codes: As a third criteria, error codes should be easily readable by other applications. For example, the XooMLe application returns back only human readable error messages, e.g. “Invalid Google API key supplied”. An application parsing a XooMLe response would have to search for this specific error message, and this can be notoriously brittle — for example, the XooMLe server might simply change the message to “Invalid Key Supplied”. Error codes, such as those provided by DAS are important for programmatic control, and easy creation of exceptions. For example, if XooMLe returned a 1001 error code, a client application could do a quick lookup and immediately throw an InvalidKeyException.

Based on these three criteria, here’s my vote for best error handling option:

  • Use HTTP Status Codes for problems specifically related to HTTP, and not specifically related to your web service.
  • When an error occurs, always return an XML document detailing the error.
  • Make sure the XML error document contains both an error code, and a human readable error message. For example:

    <?xml version="1.0" encoding="UTF-8" ?>
    <error>
      <error_code>1001</error_code>
      <error_msg>Invalid Google API key supplied</error_msg>
    </error>
    


By following these three simple practices, you can make it significantly easier for others to interface with your service, and react when things go wrong. New developers can easily see valid and invalid requests via a simple web browser, and programs can easily (and more robustly) extract error codes and act appropriately.
What is the best option for propagating error messages from REST-based web services? Are there other options beyond the four described here?


Create Custom Header  
Reference : Adding Custom Http Header To All WCF Requests

Thursday, November 6, 2014

Interface vs Abstract Class

  • interfaces can have no state or implementation
  • a class that implements an interface must provide an implementation of all the methods of that interface
  • abstract classes may contain state (data members) and/or implementation (methods)
  • abstract classes can be inherited without implementing the abstract methods (though such a derived class is abstract itself)
  • interfaces may be multiple-inherited, abstract classes may not (this is probably the key concrete reason for interfaces to exist separately from abtract classes - they permit an implementation of multiple inheritance that removes many of the problems of general MI).


Reference : http://stackoverflow.com/questions/761194/interface-vs-abstract-class-general-oo

Wednesday, August 27, 2014

XML Deserialize Throw "xml was not expected."

Today i get error when deserialize xml string from my partner

XML

          string xmlRaw = "";
            xmlRaw += "<?xml version=\"1.0\"?>";
            xmlRaw += "<PartnerResponse xmlns=\"http://example.com\">";
            xmlRaw += "<ResultCode>00000</ResultCode>";
            xmlRaw += "<Description>Success</Description>";
            xmlRaw += "</PartnerResponse>";


Error 

{"<PartnerResponse xmlns='http://example.com'> was not expected."}




Problem
I'm not define any default name space in my class

   /// <summary>
    /// Response - Generic Response
    /// </summary>
    public class PartnerResponse
    {
        [XmlElement]
        public string ResultCode { get; set; }
        [XmlElement]
        public string Description { get; set; }
    }


Solution

Either define namespace or ask partner remove xmls from xml string.

Friday, September 27, 2013

Collection Count Or Any in C#

During my daily development I have to deal with IEnumerables quite often. Old habits takes time to go but now I try to use LINQ to Objects as much as possible in my code while dealing with IEnumerables. LINQ to Objects or LINQ in general is one of the best thing that have been added in C# in past couple of years in my personal opinion.

As I said, old habits take time to go, one habit which I am trying to get rid of these days is to avoid using Count property. At countless places in my code I have used this piece of code and I am sure many of you would have done same

   1:  if(SomeCollection.Count == 0)
   2:      DoSomething();
   3:  else
   4:      DoSomethingElse();

In above piece of code you just want to know whether the collection contains any item or not and based on that you will perform some operation. Problem is that to find this yes or no you are traversing the whole list when you use Count. Let's say your collection contain 1000 element. You are traversing whole list just to find out whether there is any item in the list or not. Which doesn't make any sense at all. Instead what we can use is a simple LINQ method 'Any'.

   1:  if(SomeCollection.Any())
   2:      DoSomething();
   3:  else
   4:      DoSomethingElse();

Use of 'Any' will make your code much faster because instead of traversing whole collection 'Any' will return as soon as it finds that there is an element in your collection or even in case there isn't any at all. This is just one example I am sure there will be many more examples in my daily development which can be simplified using LINQ to Objects.

Note that "if you are starting with something that has a .Length or .Count (such as ICollection<T>, IList<T>, List<T>, etc) - then this will be the fastest option, since it doesn't need to go through the GetEnumerator()/MoveNext()/Dispose() sequence required by Any() to check for a non-empty IEnumerable<T> sequence. For just IEnumerable<T>, then Any() will generally be quicker, as it only has to look at one iteration. However, note that the LINQ-to-Objects implementation of Count() does check for ICollection<T> (using .Count as an optimisation) - so if your underlying data-source is directly a list/collection, there won't be a huge difference. In general with IEnumerable<T> : stick with Any()."


Reference Here



Thursday, September 12, 2013

CorFlags Check 32/64 Bit

The flags interpretation:
Any CPU: PE = PE32 and 32BIT = 0
x86: PE = PE32 and 32BIT = 1
64-bit: PE = PE32+ and 32BIT = 0

ILONLY flag 
For example :
The System.Data.SQLite.dll file you are using is a mixed-mode assembly, which means it is not a pure .NET code (see also the “ILONLY : 0” flag), it contains also unmanaged machine code, which cannot be “Any CPU”. So, as the DLL contains 32-bit native code, it can be loaded only into 32-bit process, 

Monday, April 15, 2013

GzipStream To Byte Array

public static string Compress(this string s)
    {
        byte[] bytesToEncode = Encoding.UTF8.GetBytes(s);
        return Convert.ToBase64String(bytesToEncode.Compress());
    }

public static byte[] Compress(this byte[] bytesToEncode)
    {
        using (MemoryStream input = new MemoryStream(bytesToEncode))
        using (MemoryStream output = new MemoryStream())
        {
            using (System.IO.Compression.GZipStream zip = new System.IO.Compression.GZipStream(output, System.IO.Compression.CompressionMode.Compress))
            {
                input.CopyTo(zip);
            }
            return output.ToArray();
        }
    }



public static string Explode(this string s)
    {
        byte[] compressedBytes = Convert.FromBase64String(s);
        return Encoding.UTF8.GetString(compressedBytes.Explode());
    }

public static byte[] Explode(this byte[] compressedBytes)
    {
        using (MemoryStream input = new MemoryStream(compressedBytes))
        using (MemoryStream output = new MemoryStream())
        {
            using (System.IO.Compression.GZipStream zip = new System.IO.Compression.GZipStream(input, System.IO.Compression.CompressionMode.Decompress))
            {
                zip.CopyTo(output);
            }
            return output.ToArray();
        }
    }

Tuesday, April 9, 2013

Sql Server ConnectionTimeout vs CommandTimeout


ConnectionTimeout a property of Connection class in ADO.NET, is the time you would wait, for connecting to a given database, before flagging a connection failure. Default value is 30 seconds.
new SqlConnection().ConnectionTimeout = 10;
CommandTimeout a property of the Command class in ADO.NET, is the time you would wait, for a command (query, stored procedure, etc.) to return result set, before flagging an execution failure. Default value for CommandTimeout too is 30 seconds.
new SqlConnection().CreateCommand().CommandTimeout = 10;
Unlike ConnectionTimeout which are part of connection string, command timeouts are defined separately (hardcoded or as appSettings). Setting both of them to 0 (zero) would result in indefinite wait period which is generally considered a bad practice. You ideally want to set both of them to in accordance to your performance SLAs. Though at times, while running data heavy background jobs / workflows you may want to set your CommandTimeout to a larger value.


Thursday, November 22, 2012

C# Get IPV4 ipaddress


Option 1 :  

public static string GetIP4Address()
{
    string IP4Address = String.Empty;

    foreach (IPAddress IPA in Dns.GetHostAddresses(Dns.GetHostName()))
    {
        if (IPA.AddressFamily == AddressFamily.InterNetwork)
        {
            IP4Address = IPA.ToString();
            break;
        }
    }

    return IP4Address;
}


 Option 2 :  
 /// <summary> 
/// This utility function displays all the IP (v4, not v6) addresses of the local computer. 
/// </summary> 
public static void DisplayIPAddresses() 

    StringBuilder sb = new StringBuilder(); 

    // Get a list of all network interfaces (usually one per network card, dialup, and VPN connection) 
    NetworkInterface[] networkInterfaces = NetworkInterface.GetAllNetworkInterfaces(); 

    foreach (NetworkInterface network in networkInterfaces) 
    { 
        // Read the IP configuration for each network 
        IPInterfaceProperties properties = network.GetIPProperties(); 

        // Each network interface may have multiple IP addresses 
        foreach (IPAddressInformation address in properties.UnicastAddresses) 
        { 
            // We're only interested in IPv4 addresses for now 
            if (address.Address.AddressFamily != AddressFamily.InterNetwork) 
                continue; 

            // Ignore loopback addresses (e.g., 127.0.0.1) 
            if (IPAddress.IsLoopback(address.Address)) 
                continue; 

            sb.AppendLine(address.Address.ToString() + " (" + network.Name + ")"); 
        } 
    } 

    MessageBox.Show(sb.ToString()); 
}

Thursday, October 4, 2012

WCF REST: Get the requested URL

Finding the Request.Url is a lot different from standard web work when working in a WCF REST context. It can be quite difficult to find the URL of the request in your WCF REST service.

?
var context = OperationContext.Current;
var requestedUrl =  context.IncomingMessageHeaders.To.PathAndQuery;


Friday, September 14, 2012

Enable WCF tracing



Tracing mechanism in Windows Communication Foundation is based on the classes that resides in System.Diagnostic namespace.Important classes are Trace, TraceSource and TraceListener.

Following are the steps to enable tracing in WCF:

1. Configuring WCF to emit tracing information/Define Trace Source, we have the following options:
  • System.ServiceModel 
  • System.ServiceModel.MessageLogging 
  • System.ServiceModel.IdentityModel
  • System.ServiceModel.Activation 
  • System.Runtime.Serialization 
  • System.IO.Log
  • Cardspace
      In configuration file, we will define a source to enable this configuration as follows:
      <source name="System.ServiceModel.MessageLogging">
2. Setting Tracing Level, we have the following available options, we need to set this tracing level to available options other than default "Off":
  • Off
  • Critical
  • Error
  • Warning
  • Information
  • Verbose
  • ActivityTracing
  • All
      In configuration file, we can choose above values for switchValue attribute as follows:
      <source name="System.ServiceModel.MessageLogging"
                               switchValue=”Information”>

3. Configuring a trace listener
    For configuring a trace listener, we will add following to config file.
     <listeners>
                 <add name="messages"
                 type="System.Diagnostics.XmlWriterTraceListener"
                 initializeData="d:\logs\messages.svclog" />
      </listeners>

4. Enabling message logging
      <system.serviceModel>
         <diagnostics>
            <messageLogging
                    logEntireMessage="true"
                    logMalformedMessages="false"
                    logMessagesAtServiceLevel="true"
                    logMessagesAtTransportLevel="false"
                    maxMessagesToLog="3000"
                    maxSizeOfMessageToLog="2000"/>
         </diagnostics>
    </system.serviceModel>
logEntireMessage: By default, only the message header is logged but if we set it to true, entire message including message header as well as body will be logged.
logMalformedMessages: this option log messages those are rejected by WCF stack at any stage are known as malformed messages.
logMessagesAtServiceLevel: messages those are about to enter or leave user code.
logMessagesAtTransportLevel: messages those are about to encode or decode.
maxMessagesToLog: maximum quota for messages. Default value is 10000.
maxSizeOfMessageToLog: message size in bytes.

Putting all this together, configuration file will appear like this.
--------------------------------------------------------------------------- 
    <system.diagnostics>
    <sources>
      <source name="System.ServiceModel.MessageLogging">
        <listeners>
          <add name="messagelistener"
               type="System.Diagnostics.XmlWriterTraceListener" initializeData="d:\logs\myMessages.svclog"></add>
        </listeners>
      </source>
    </sources>
  </system.diagnostics>
    <system.serviceModel>       
      <diagnostics>
        <messageLogging logEntireMessage="true"
                        logMessagesAtServiceLevel="false"
                        logMessagesAtTransportLevel="false"
                        logMalformedMessages="true"
                        maxMessagesToLog="5000"
                        maxSizeOfMessageToLog="2000">         
        </messageLogging>
      </diagnostics>
    </system.serviceModel>
---------------------------------------------------------------------------

Note: In this case, information will be buffered and not published to file automatically, So, we can set the autoflush property of the trace under sources as follows:
<trace autoflush ="true" />