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
     




Monday, May 30, 2016

Cross-site Scripting (XSS)


XSS is the insertion of malicious Javascript code in a webpage, that can steal your session cookie, or do something malicious (make the page do something else than it is meant to).

Now, the way you inject your javascript depends on that particular site. There is no mechanism involved, except than to going through the painful process of reading hundreds of lines of code on their client end and hoping that they made mistake. You can find XSS vulnerabilities by using trial and error method on small profile websites but for corporate websites, they are usually secured against such trial and error methods, that means you have to go through the source code and find the programming mistakes.

Definitely, XSS or Cross-Site Scripting is a hot topic. Sometimes, when I'm bored and have nothing to do (which usually doesn't happen too often), I start looking for websites and try to see if they have some kind of vulnerability. I do it just because I like to learn from others and helps me to understand how to protect my websites. Of course, I don't cause any problem or harm anyone, it is just for educational purposes. (Believe me, I'm being honest, lol)

However, it is not "super easy" to find vulnerabilities in websites, and if you want to learn how to work and apply XSS you should go to:  http://www.insecurelabs.org/

insecurelabs.org is an educational website which was build intentionally insecure for XSS, great, right!? So if you find XSS flaws, good for you.

Being on this website, you can start testing your scritps, For example, after the URL http://www.insecurelabs.org/ just add this script:

Search.aspx?Query=<script>alert('CSS Vulnerable - found it by BigBangCode')</script>

and hit enter key.





You'll see a dialog box with the text you entered. Of course, the website didn't mean to do that, but you just forced it to do it, feels good, right? lol

Other example,

Imagine you are somewhere in the internet and find this:

http://www.insecurelabs.org/Search.aspx?Query=%3Cscript%3Ewindow.open(%22http://bigbang-code.blogspot.com/%22)%3C/script%3E

at first sight, if you are not careful, just by looking at the first part of the URL (insecurelabs.org) you would think that the link will take you to that website. However, once you clicn on it, you will be redirected to my blog instead (look at the end of the URL). With this technique, taking advantage of this vulnerability we can redirect traffic to our website by fooling poeple. Easy, right?

Wait, wait we are not done, =)

Now, paste this code in your browser and hit enter key:


http://www.insecurelabs.org/Search.aspx?Query=%3Chtml+xmlns%3D%27http%3A%2F%2Fwww.w3.org%2F1999%2Fxhtml%27%3E++++%3Chead+%3E+++++++%3Cmeta+http-equiv%3D%27Content-Type%27+content%3D%27text%2Fhtml%3B+charset%3Dutf-8%27%2F%3E+++++++%3Ctitle+%3EPlease+let+me+steal+your+private+information%3C%2Ftitle%3E++++%3C%2Fhead%3E+%3Cbody%3E+%3Ch1%3EPlease+let+me+steal+your+private+information%3C%2Fh1%3E+++%3Cform+id%3D%27sampleform%27+method%3D%27post%27+action%3D%27%27+%3E++++%3Cp%3E++++Name%3A+%3Cinput+type%3D%27text%27+name%3D%27Name%27+%2F%3E++++%3C%2Fp%3E++++%3Cp%3E++++Email%3A+%3Cinput+type%3D%27text%27+name%3D%27Email%27+%2F%3E++++%3C%2Fp%3E++++%3Cp%3E++++pass%3A+%3Cinput+type%3D%27text%27+name%3D%27pass%27+%2F%3E++++%3C%2Fp%3E++++%3Cp%3E++++SSN%3A+%3Cinput+type%3D%27text%27+name%3D%27ssn%27+%2F%3E++++%3C%2Fp%3E+++++%3Cp%3E++++%3Cinput+type%3D%27submit%27+name%3D%27Submit%27+value%3D%27Submit%27+%2F%3E++++%3C%2Fp%3E+%3C%2Fform%3E+++%3C%2Fbody%3E+%3C%2Fhtml%3E






Voila!!... It looks like the webiste has some page with a form that we can fill out with our private and critical information. Of course, it is FAKE!, Some people would think is real because seems to be part of insecurelabs.org . That is why it is so important to look at the URL and make sure we are providing our information to only secure websites. Do we see any "https"? or does it look legit or real? why this website is asking for SSN or credit card info? Alsways ask those kind of questions when sunrfing the internet.

Even if you have 200 years of experience with computers, if you do not have common sense, you can be a victim of cybercrime.





Friday, May 6, 2016

Spring Framework - MVC Architecture


The Spring web MVC framework provides model-view-controller architecture and ready components that can be used to develop flexible and loosely coupled web applications. The MVC pattern results in separating the different aspects of the application (input logic, business logic, and UI logic), while providing a loose coupling between these elements.
  • The Model encapsulates the application data and in general they will consist of POJO.
  • The View is responsible for rendering the model data and in general it generates HTML output that the client's browser can interpret.
  • The Controller is responsible for processing user requests and building appropriate model and passes it to the view for rendering.

Spring provides a front controller servlet named DispatcherServlet. To build an application, you construct the following components:
  • One or more controllers that invoke business logic and create a ModelAndView object
  • A visualization component such as a JSP
  • XML or annotation configuration to wire the components together
Spring provides various controllers for you to use as base classes for creating your own controllers, depending on your needs. Among them are ones that:
  • Redirect to static views
  • Provide basic servlet-like functionality
  • Process commands
  • Process shared actions
  • Handle forms
  • Provide wizard-like functionality to process multipage forms
If you really want to learn and implement Spring MVC in your Java projects, I recommend you to have you Eclipse IDE ready and watch "Spring MVC Tutorial for Beginners" YouTube video. That tutorial will guide you step by step in a very easy and detailed way. So far, one of the best tutorials. 







Saturday, April 23, 2016

CHUCK NORRIS plugin for Jenkins


Jenkins is a server-based software that helps you build and test your Software Projects continuously. It makes your life easier when integrating any changes to your projects. Once you have Jenkins configured , it is soooo easy to build and deploy new code, just a couple clicks and Jenkins will do the rest. You can even schedule builds and deploys, it is awesome.

I've been working with Jenkins for over a year, but just a couple months ago I noticed that there is a Chuck Norris plugin, yeap, now you can have Chuck Norris in your daily builds/deploys.

You can install the Chuck Norris Plugin for some humor. Once installed the plugin using the plugin manager, you can activate it on the job configuration page. Select "Add post-build action" -> "Activate Chuck Norris".


This plugin adds an absolutely delightful feature to Jenkins: depending if your build succeeds, fails, or is unstable, it will show a picture of Chuck Norris auto-adapting (that’s right, computer science it is!) to the build result!





and just in case you didn't know:

  • Chuck Norris can delete the Recycling Bin