Friday, September 30, 2016

Send data by post method in C#


If you need to POST some data (XML) in a particular URL using C#, you just need to perform the next steps:

  • Create a request to the url
  • Put required request headers
  • Convert the request XML message to a stream (or bytes)
  • Write the stream of bytes (our request xml) to the request stream
  • Get the response and read the response as a string

I know it looks complicated, but once you see the code, you will clarify your ideas...
namespace HttpPostRequestDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            string xmlMessage = "<?xml version=\"1.0\" encoding=\"utf-8\" ?>\r\n" +
            "construct your xml request message as required by that method along with parameters";
            string url = "http://XXXX.YYYY/ZZZZ/ABCD.aspx";
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);


            byte[] requestInFormOfBytes = System.Text.Encoding.ASCII.GetBytes(xmlMessage);
            request.Method = "POST";
            request.ContentType = "text/xml;charset=utf-8";
            request.ContentLength = requestInFormOfBytes.Length;
            Stream requestStream = request.GetRequestStream();
            requestStream.Write(requestBytes, 0, requestInFormOfBytes.Length);
            requestStream.Close();


            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            StreamReader respStream = new StreamReader(response.GetResponseStream(), System.Text.Encoding.Default);
            string receivedResponse = respStream.ReadToEnd();

            Console.WriteLine(receivedResponse);
            respStream.Close();
            response.Close();
        }
    }
}
Now, if the XML message is formed well, everything should be fine....



Programming Joke

Q:  Why do Java programmers have to wear glasses?
A:  Because they don't C#. (see sharp)

because, they are Visually Basic, uh?

=)



Wednesday, September 14, 2016

Redirect to login page when session state time out is completed in asp.NET MVC


If you are working in asp.NET and need your application to redirect users to login page when session timeout is completed, you just need to implement 3 simple steps, and today is your lucky day because I'll show you how to do it...

1. Set the session timeout:
In AccountController.cs find you login method and find where SignStatus is success and place this line:

Session.Timeout = 20;  //put any number, remember this is in minutes

2. Script in _Layout.cshtml
In your Shared folder, open _Layout.cshtml and place this code:

<script>
    //session end 
    var sessionTimeoutWarning = @Session.Timeout- 1;

    var sTimeout = parseInt(sessionTimeoutWarning) * 60 * 1000;
    setTimeout('SessionEnd()', sTimeout);

    function SessionEnd() {
        document.getElementById('logoutForm').submit();
    }
</script>
What we are doing here is is just calling SessionEnd() method 1 minute before session expires.


As you see, we just need a few steps to perform this event. It is recommended to set a timeout for our apps because increase security, but of course, all depends on kind of project we are working on

Tuesday, September 6, 2016

Stack trace and how to use it to debug your applications...


If you are a developer, you know how important is to debug your application correctly. Knowing how to handle exceptions is a must. We always need to pay attention to the logs generated by our code in order to identify those bugs....evil bugs!
What is a Stacktrace?
A stacktrace is a very helpful debugging tool. It shows you the call stack (meaning, the stack of functions that were called up to that point) at the time an uncaught exception was thrown (or the time the stacktrace was generated manually). This is very useful because it doesn't only show you where the error happened, but also how the program ended up in that place of the code. This leads over to the next question:
What is an Exception?
An Exception is what the Runtime Environment uses to tell you that an error occurred. Popular examples are NullPointerException, IndexOutOfBoundsException or ArithmeticException. Each of these are caused when you try to do something that is not possible. For example, a NullPointerException will be thrown when you try to dereference a Null-object.

Simple Example
With the example given in the question, we can determine exactly where the exception was thrown in the application. Let's have a look at the stack trace:
Exception in thread "main" java.lang.NullPointerException
        at com.example.myproject.Book.getTitle(Book.java:16)
        at com.example.myproject.Author.getBookTitles(Author.java:25)
        at com.example.myproject.Bootstrap.main(Bootstrap.java:14)
This is a very simple stack trace. If we start at the beginning of the list of "at ...", we can tell where our error happened. What we're looking for is the topmost method call that is part of our application. In this case, it's:
at com.example.myproject.Book.getTitle(Book.java:16)
To debug this, we can open up Book.java and look at line 16, which is:
public String getTitle() {
    System.out.println(title.toString()); <-- line 16
    return title;
}
This would indicate that something (probably title) is null in the above code.

Example with a chain of exceptions
Sometimes applications will catch an Exception and re-throw it as the cause of another Exception. This typically looks like:
try {
....
} catch (NullPointerException e) {
  throw new IllegalStateException("A book has a null property", e)
}
This might give you a stack trace that looks like:
Exception in thread "main" java.lang.IllegalStateException: A book has a null property
        at com.example.myproject.Author.getBookIds(Author.java:38)
        at com.example.myproject.Bootstrap.main(Bootstrap.java:14)
Caused by: java.lang.NullPointerException
        at com.example.myproject.Book.getId(Book.java:22)
        at com.example.myproject.Author.getBookIds(Author.java:35)
        ... 1 more
What's different about this one is the "Caused by". Sometimes exceptions will have multiple "Caused by" sections. For these, you typically want to find the "root cause", which will be one of the lowest "Caused by" sections in the stack trace. In our case, it's:
Caused by: java.lang.NullPointerException <-- root cause
        at com.example.myproject.Book.getId(Book.java:22) <-- important line
Again, with this exception we'd want to look at line 22 of Book.java to see what might cause the NullPointerException here.

So, just to summarize, To understand the name: A stack trace is a a list of Exceptions( or you can say a list of "Cause by"), from the most surface Exception(e.g. Service Layer Exception) to the deepest one (e.g. Database Exception). Just like the reason we call it 'stack' is because stack is First in Last out (FILO), the deepest exception was happened in the very beginning, then a chain of exception was generated a series of consequences, the surface Exception was the last one happened in time, but we see it in the first place.