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.



Thursday, August 25, 2016

Using Ajax to call static method from Asp.net page


I've been working a lot with .NET framework lately and wanted to share some useful knowledge with others human beings (but if you are a robot, you can also use this post for your tasks =) ).
If we want to call a static method from a cshtml file, the best way to do it is by using AJAX. In the project I am working on, I needed to perform some back-end task at some specific moment when user requests it. The back-end function is supposed to return a URL (string) and then use that new URL to update some of my links in the front-end.
We can directly call a static method from cshtml by just calling it, like this:

@MyClass.methodName("abc")

However, with ASP.net, RAZOR code is executed when the page is loaded, so the only way to "control" when to perform this action is by using AJAX.

This is my code using AJAX:

<script>  
        function vaxGUID() {        
        $.ajax({
            type: 'POST',
            url: "/ControllerName/method",
            data: '{"Name":"anything"}',
            contentType: 'application/json; charset=utf-8',
            dataType: 'html',
            success: function (data) {
                $('a.varURL').attr('href', data);                                
                alert("Good response - " + data);
            },
            error: function (data, success, error) {
                alert("Error : " + error);
            }
        });
        return false;
    }
</script>

As we can see in the method, we are making the call with: url: "/ControllerName/method", this means that is we put that URL in our browser (with any parameter if needed) , we should get a response. That is a good way to test it first. "Data" is returned and then we can use it in the way we need it.




Sunday, August 21, 2016

Java Singleton Pattern


Singleton pattern restricts the instantiation of a class and ensures that only one instance of the class exists in the java virtual machine. The singleton class must provide a global access point to get the instance of the class. Singleton pattern is used for logging, drivers objects, caching and thread pool.

For example, if you have a license for only one connection for your database or your JDBC driver has trouble with multi threading, the Singleton makes sure that only one connection is made or that only one thread can access the connection at a time.

Implementing Singletons
  • Private constructor to restrict instantiation of the class from other classes.
  • Private static variable of the same class that is the only instance of the class.
  • Public static method that returns the instance of the class, this is the global access point for outer world to get the instance of the singleton class.
Example:

package com.bigbangcode.constructors;
public class MySingleTon {
     
    private static MySingleTon myObj;
    /**
     * Create private constructor
     */
    private MySingleTon(){
         
    }
    /**
     * Create a static method to get instance.
     */
    public static MySingleTon getInstance(){
        if(myObj == null){
            myObj = new MySingleTon();
        }
        return myObj;
    }
     
    public void getSomeThing(){
        // do something here
        System.out.println("I am here....");
    }
     
    public static void main(String a[]){
        MySingleTon st = MySingleTon.getInstance();
        st.getSomeThing();
    }
}

Another example, Thread Safe Singleton:

The easier way to create a thread-safe singleton class is to make the global access method synchronized, so that only one thread can execute this method at a time.

package com.bigbangcode.singleton;

public class ThreadSafeSingleton {

    private static ThreadSafeSingleton instance;
    
    private ThreadSafeSingleton(){}
    
    public static synchronized ThreadSafeSingleton getInstance(){
        if(instance == null){
            instance = new ThreadSafeSingleton();
        }
        return instance;
    }
    
}




Sunday, July 24, 2016

MySQL Workbench - How to create a Model from existing scripts


When using MySQL Workbench you can create a Model from existing scripts. That is called "Reverse Engineering using a Create Script". Useful tool if you need to visualize and finishing modeling your data base.

Here are the steps:

Open MySQL Workbench, click on File --> Import --> Reverse Engineering MySQL Create Script



On Input and Options screen click on Browse and select your existing script. Then Click on execute...




When on Reverse Engineering Progress screen do no change anything there, just click on Next...
Then on the next screen , just click on Finish...




After clicking on Finish you'll see the EER Diagram screen. Here you just can drag and drop all the tables (on the left side) to the Diagram part (right part)




As soon as you start dragging and dropping tables to the Diagram side, you'll see the tables with their relationships. After that, you can export that diagram in any format you need.

As we can see in general, MySQL Workbench is a very intuitive software with tons of useful tools like this "Reverse Engineering MySQL". Feel free to play around with it and if you have any questions just post a comment or email me....




Monday, July 4, 2016

Google Chrome - ShortCuts for Pros



As we already know, Google knows everything and it is everywhere. Email, blogs, cloud storage, OS + many other things...and of course Google's browser: Chrome.

I have to admit that at first I didn't like Google Chrome. I was using Firefox for so many years that I didn't feel like using another browser (I was lazy, I know). However, one day, my lovely Firefox crashed and suddenly started slowing down my computer, so my only option was migrating to Google Chrome; and actually it was a good idea. Google Chrome, at least for me, seems to be more stable and even faster that other browsers, plus it lets you link some features from others Google products.

And if you are a Chrome-lover, you will enjoy this post. I'm posting the most useful shortcuts for this web-browser. Believe me, you life will change after you learned and start using these commands (just kidding, it won't change a lot, but it help you with your tasks)  =)



SHORTCUT                                                                       KEYS

1.New Window:                                                                  Ctrl+N

2.New Incognito Window:                                                Ctrl+Shift+N

3.New Tab:                                                                         Ctrl+T

4.Close Tab:                                                                        Ctrl+W

5.Close Window:                                                                 Ctrl+Shift+W

6.Add to Bookmarks:                                                         Ctrl+D

7.Show/Hide Bookmarks Bar:                                          Ctrl+Shift+B

8.Downloads:                                                                       Ctrl+J

9.History:                                                                             Ctrl+H

10.Open link in new tab:                                                    Ctrl+Click

11.Open last closed tab:                                                      Ctrl+Shift+T

12.Returns the tab to its original position:                       Press Esc while dragging a tab

13.Switches to the tab at the specified                              Ctrl+1 through Ctrl+8
position number on the tab strip:

14.Switches to the last tab:                                                Ctrl+9


15.Switches to the next tab:                                              Ctrl+Tab or Ctrl+Pg Down 

16.Switches to the previous tab:                                       Ctrl+Shift+Tab or Ctrl+
Pg Up

17. Closes the current window:                                         Alt+F4

18.Closes the current tab or pop-up:                               Ctrl+W or Ctrl+F4