Sunday, March 13, 2016

Common Gotchas

                                                                   
                                                               Common Gotchas



1)   Extra character in Certificate Thumbprint – Go to Windows MMC, add the certificates snap-in (Ctrl M), select any certificate properties and copy-paste its thumbprint in notepad to see it.


2)     Enterprise library Semantic logging (out-of-process) service not logging anything – Restart the service.

3)     Enterprise library Semantic logging will not write anything if any one of the parameter passed is null. Example  -
this.WriteEvent(2, FirstName, LastName, EncSSN, City);
will not write if anything if just “City” is null. 

4) While configuring Quartz.NET scheduler with AdoNetJobStore (needed for clustered scenario), make sure no other instance of Quartz.NET scheduler is pointing to the same job store (database). Example - SIT Env Quartz.NET jobstore might be pointing to UAT Env. jobstore.

5) Sharing a folder in Windows will update the existing ACL list of the children folder. For example - Sharing the inetpub > "wwwroot" folder with read-only permissions for some colleagues removed "NetworkService" and "IIS_IUSRS" users from all its virtual directories physical folders. 

ReSubmitting messages from ServiceBus Deadletter queue



ReSubmitting messages from ServiceBus Deadletter queue


Resubmitting messages, which do not require any change, from deadletter queue is straightforward and can be done using Service Bus Explorer tool.

However if the messages need change (say for example – because of bug – there is a special character which needs to be stripped off from the messages), ServiceBusExplorer would not do it. This can be done by using a custom tool/program to retrieve the messages from deadletter queue, store it somewhere, do the necessary modification and push the message back to the service bus. (Note – The earlier deadletter messages should be deleted (received)).
The sample code for reading messages from deadletter queue can be taken the open source ServiceBusExplorer tool itself. Program below –


class Program
    {
        private static int MaxBufferSize = 262144; // 256 KB

        static void Main(string[] args)
        {

            Uri uri = new Uri(@"sb://" + ConfigurationManager.AppSettings["SbHost"] + "." + ConfigurationManager.AppSettings["Domain"] + "/" + ConfigurationManager.AppSettings["Namespace"]);
            TokenProvider tokenProvider = TokenProvider.CreateSharedAccessSignatureTokenProvider(ConfigurationManager.AppSettings["KeyName"], ConfigurationManager.AppSettings["SharedAccessKey"]);
            MessagingFactory factory = MessagingFactory.Create(uri, tokenProvider);

            SubscriptionClient subsClient = factory.CreateSubscriptionClient(ConfigurationManager.AppSettings["Topic"], ConfigurationManager.AppSettings["Subscription"] + "/$DeadLetterQueue");

            var listMessages = subsClient.PeekBatch(Convert.ToInt32(ConfigurationManager.AppSettings["PeekMessageCount"]));           

            foreach (var bm in listMessages)
            {
                string messageText = null;
                Stream stream = bm.GetBody<Stream>();
                var element = new BinaryMessageEncodingBindingElement
                {
                    ReaderQuotas = new XmlDictionaryReaderQuotas
                    {
                        MaxArrayLength = int.MaxValue,
                        MaxBytesPerRead = int.MaxValue,
                        MaxDepth = int.MaxValue,
                        MaxNameTableCharCount = int.MaxValue,
                        MaxStringContentLength = int.MaxValue
                    }
                };
                var encoderFactory = element.CreateMessageEncoderFactory();
                var encoder = encoderFactory.Encoder;
                var stringBuilder = new StringBuilder();
                var message = encoder.ReadMessage(stream, MaxBufferSize);
                using (var reader = message.GetReaderAtBodyContents())
                {
                    var settings = new XmlWriterSettings { Indent = true };
                    using (var writer = XmlWriter.Create(stringBuilder, settings))
                    {
                        writer.WriteNode(reader, true);
                    }
                }
                messageText = stringBuilder.ToString();
                Console.WriteLine(messageText);
                stream.Dispose();
                File.WriteAllText(ConfigurationManager.AppSettings["PathToStoreMessages"] + bm.MessageId + ".txt", messageText);
            }



        }


    }

Thursday, February 11, 2016

Exception handling while using Entity Framework

Taken from - https://blogs.infosupport.com/improving-dbentityvalidationexception/

Use the code snippet below either by applying in each dataaccess method or via partial class for DBEntites -


public partial class NorthwindEntities
{
    public override int SaveChanges()
    {
        try
        {
            return base.SaveChanges();
        }
        catch (DbEntityValidationException ex)
        {
            // Retrieve the error messages as a list of strings.
            var errorMessages = ex.EntityValidationErrors
                    .SelectMany(x => x.ValidationErrors)
                    .Select(x => x.ErrorMessage);

            // Join the list to a single string.
            var fullErrorMessage = string.Join("; ", errorMessages);

            // Combine the original exception message with the new one.
            var exceptionMessage = string.Concat(ex.Message, " The validation errors are: ", fullErrorMessage);

            // Throw a new DbEntityValidationException with the improved exception message.
            throw new DbEntityValidationException(exceptionMessage, ex.EntityValidationErrors);
        }
    }
}

if the above approach is not used - simply printing ex.Message will not give the full error information and will make diagnosing tougher.

Disposing WCF clients


Taken from

http://web.archive.org/web/20100703123454/http://old.iserviceoriented.com/blog/post/Indisposable+-+WCF+Gotcha+1.aspx


OrderServiceClient proxy = null;
bool success = false;
try
{
  proxy = new OrderServiceClient();
  proxy.PlaceOrder(request);
  proxy.Close();
  success = true;
}
finally
{
  if(!success)
  {
    proxy.Abort();
  }
}



If you do not want to clutter your code with the above code all the places, use the following approach-

Service<IOrderService>.Use(orderService=>
{
  orderService.PlaceOrder(request);
}

=====================Implementation of Service class========

public delegate void UseServiceDelegate<T>(T proxy);

public static class Service<T>
{
    public static ChannelFactory<T> _channelFactory = new ChannelFactory<T>("");

    public static void Use(UseServiceDelegate<T> codeBlock)
    {
        IClientChannel proxy = (IClientChannel)_channelFactory.CreateChannel();
        bool success = false;
        try
        {
            codeBlock((T)proxy);
            proxy.Close();
            success = true;
        }
        finally
        {
            if (!success)
            {
                proxy.Abort();
            }
        }
    }
}

Friday, November 27, 2015

Website and WebServices load testing using JMeter


JMeter can be used to load test web application and Web services (SOAP/REST). Following steps and screenshots will help you configure JMeter (assuming you have JRE installed and class path set)

      For Website with a typical scenario of opening a homepage and logging in using username/pwd,         the following steps needs to be done.

a)       Add the “Thread group” (virtual users). Ramp up time is – It will take that amount of time to load specified max. number of the threads (users). Example – 100 users in 5 seconds.
b)       Add “Http Request Default” to set the server name and port etc (information which is independent of the other steps)
c)        Add “Http Cookie Manager” if your site uses cookies.
d)       Add the step to open the homepage. (HTTP Request)
e)       For a site which uses anti-forgery token, we need to retrieve the token from the hidden field. This can be done using the Regular Expression Extractor on the response of the step-d.
f)        Add the step to login. (HTTP Request) with the form fields. The form fields could be found using fiddler, (if not already known).
g)       For results, add “View Result Tree” and “Aggregate graph”.

h)       Press Ctrl + E to clear the results.



For web services, similar setup needs to be done (no need of “HTTP cookie manager”). Instead of “HTTP Request”, we add the “SOAP/XML-RPC Request” where we specify the full request body (SOAP) .
Then we add the “HTTP Header Manager” (to pass soap action and content type) and  “Response Assertion” to check the response value and compare.



Below are the links to JMeter files (jmx files) for load testing web sites and webservices


JMeter file for Webservice loadtesting

--------------------------------------------------------------------------------------------------


Example of simple regular expression extractor – 























Case – when you need different input for each request.
You can use CSV data config element as shown below – 
















 

Jmeter when asked to run more than 500 threads can crash because the default heap size can be exceeded. This can be fixed by starting jMeter (inside jMeter.bat) with a high heap size (upto 80 % of system’s RAM).

Below, I have commemted default settings and added new (for a 32GB RAM machine) –

rem set HEAP=-Xms512m -Xmx512m
set HEAP=-Xms22528m -Xmx22528m


jMeter when used in GUI mode can take lot of resources. You can use the following command line to run jMeter in non-GUI mode.

C:\Apache-Jmeter-2.13\bin>jmeter -n -t "C:\MyDir\MyJMX.jmx" –l "C:\MyDir\Results\resultsfile.jtl"

To jMeter running in non-GUI mode, run stoptest/shutdown.cmd in a separate command prompt.

The resulting jtl can be opened in jMeter by adding listeners like “View Results tree”, “Aggregate graph” and clicking on “browse” button to load the jtl file.

By default in the non-GUI mode, the request and response are not logged. To enable this, you have add a few options to the jMeter command line.

C:\Apache-Jmeter-2.13\bin>jmeter -Jjmeter.save.saveservice.samplerData=true -Jjmeter.save.saveservice.response_data=true -Jjmeter.save.saveservice.output_format=xml  -n -t " C:\MyDir\MyJMX.jmx " -l " C:\MyDir\Results\resultsfile.jtl "


Using jMeter for a flat load of (say 20 users) for 20 mins can be done using scheduler as shown below.

This is needed for soak test. Remember – A system can touch a peak load of 1000 users without any errors but when subjected to a low load (of 20 users) but for several minutes can take the system down.