Nov 25, 2011

Change IP using a script or command line in windows


Try This out:

@echo off

REM # Created by Thilina  Piyasundara.

set /P asda=Do you want to change the IP (y/n) : 

if "%1" == "yes" (
 ECHO Setting IP Address
 netsh int ip set address name = "Local Area Connection" source = static addr = 192.168.1.2 mask = 255.255.255.0

 ECHO Setting Gateway
 netsh int ip set address name = "Local Area Connection" gateway = 192.168.2.250 gwmetric = auto

 ECHO Setting Primary DNS
 netsh int ip set dns name = "Local Area Connection" source = static addr = 192.168.2.1
 
 GOTO SETSETTINGS
)

if not "%1" == "yes" (
 ECHO Nothing happened.
)

:SETSETTINGS
netsh int ip show config
:end
 
pause

Use the netsh commands to do the same thing in the command line.

Login error when installing MSSQL 2008

I try to instal MSSQL 2008 server on Windows XP SP3.
Installation is fine but at the end it prompts an error like this.

"           ' ' is not a valid login or you do not have permission.               " 

I use "NT Authentication\System" and I add the current user to the SQL server administrators section.

Then I read some forums and found my "user name" and "pchost name" are same. It appears like "myname\myname". It may be the issue. I created a new admin user with a different name and try to re-install the server again.

There were no errors. Finally I realize, if I try the default Administrator account to install SQL server it will not create an unnecessary account.

My opinion is :-

  • Remove the SQL server.
  • Log out from the user.
  • Then press two times Alt+Ctrl+Del.
  • Then type "administrator" as the username and press enter (If you have setup the password to the administrator account you need to give it.)
  • Start the installation.
  • Use NT Authentication\System.
  • Give a password to the SA (default) account.
  • Add current user.
  • And continue.

Nov 13, 2011

Socket Programming with Python - Echo server

This is a basic socket program. You need to run the server first and then run the client.

Echo server (pechoserver.py)
#!/usr/bin/python

import socket

s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
s.bind(("",5200)) # server is running on Port 5200
s.listen(1)

while 1:
 conn, addr = s.accept()
 print 'Connected IP ' , addr
 data = conn.recv(1024)
 if not data:
  break
 conn.send(data)
 conn.close()


Echo client (pechoclient.py)
#!/usr/bin/python

import socket
import sys

if (len(sys.argv)<1):
        print 'usage : pechoclient.py "message"'
        exit(0)
else:
        msg=sys.argv[1]
        s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
        s.connect(("localhost",5200))
        s.send(msg)
        data=s.recv(1024)
        s.close()
        print "Recived : " ,data


Run the server ;
$ pyhton pechoserver.py &

Run the client ;
$ python pechoclient "Hello World."

Run client and server in different terminals to get a clear understanding of the output.

For more : http://docs.python.org/library/socket.html
                 http://docs.python.org/howto/sockets.html

Nov 10, 2011

Log your Python script - Python Logging Hello World

This is a basic logging script used in python.




#!/usr/bin/python

import sys
import logging

if (len(sys.argv)==2):
 loglevel=sys.argv[1]
else:
 loglevel="WARNING"

logging.basicConfig(filename='./mylogging.log',\
 format='%(levelname)s : %(asctime)s - %(message)s',\
 level=loglevel)
logging.debug('Logging started.')
logging.warning('Logging started.')

print "Hello World."
logging.debug("Print :- Hello World.")

logging.debug("End.")
logging.warning("End.")
exit(0)


Here I'm using a library called "logging" to do the logging for me. You can statically give the log level without passing it as an argument. And also there are many log levels you can use according to your need.

For more details :-  http://docs.python.org/library/logging.html

Your suggestions are welcome.

Jun 22, 2011

Enable/Disable LAN interface by command prompt in Windows XP

First thing you need to check "devcon" is working in your XP version.
Go to command prompt and type
C:\>devcon

If it gives an error, download this utility (an exe) from microsoft website.
http://download.microsoft.com/download/1/1/f/11f7dd10-272d-4cd2-896f-9ce67f3e0240/devcon.exe

Extract that into a known place and change your command prompt path to that folder where the .exe file exist.

Now if you type condev it should give a help details.

Now you need to get the Ethernet name from that command. To do that type;

C:\devcon_folder> devcon hwids "PCI\*"  >pcidevname.txt

This will print all PCI devices hardware details into that text file. So go through that text file and get the ID of your ethernet card. (Use Ctrl+F and key word "Ethernet")

It will be like this.


PCI\VEN_10EC&DEV_8139&SUBSYS_10451043&REV_10\4&2966AB86&0&38A4
    Name: Realtek RTL8139/810x Family Fast Ethernet NIC
    Hardware ID's:
        PCI\VEN_10EC&DEV_8139&SUBSYS_10451043&REV_10
        .......
    Compatible ID's:
        PCI\VEN_10EC&DEV_8139&REV_10
        PCI\VEN_10EC&DEV_8139 ......


Get your ID equal to "PCI\VEN_10EC&*"

Then type to disable;

C:\devcon_folder>devcon disable "PCI\VEN_10EC&*"

To enable

C:\devcon_folder>devcon enable "PCI\VEN_10EC&*"

Jun 18, 2011

Why do we need two address types to communicate via a network?

Think that we need to go to USA, from Sri Lanka. But assume there is no direct flight to USA. So what we will do…? If there are direct flights from Sri Lanka to Singapore and from Singapore to USA, we can go to USA. In such a scenario we have two types of destinations. One is a long destination (LD) which is from Sri Lanka to USA and the other is short destinations (SD) which are Sri Lanka to Singapore and Singapore to USA. If we can achieve all the short destinations in a correct order, ultimately we can reach to our long destination. So, when we are in Sri Lanka LD is SL-USA but SD is SL-SIN. Then we travel to Singapore. In Singapore LD is SL-USA but SD is SIN-USA. Now we are in USA. Note that when we reach to Singapore we change the SD but we haven’t change the LD, because our ultimate goal is to go to USA.

Click on the image to maximize

A collection of interconnected devices are called as a network. When the number of devises gets bigger and bigger, the single network will divide into manageable sub networks. In a network all devices are recognized by its MAC (Media Access Control) address. IP address is a logical address that assigned to device in a way that human can remember, but it’s limited to a single network. The network is identified by the subnet mask. Default gateway is used as an access point to go to another network.

Think you are using the C1 Computer. You need to copy a file in S1 (4.4.4.4) server. So how C1 will communicate with S1? To do a copy you need to specify an IP address of the server. In this scenario it is 4.4.4.4. When you enter that IP address your machine will tally it with its IP address and the subnet mask. C1s subnet mask is 255.255.255.0, so its network address is 192.168.1.0. The requested IP 4.4.4.4 is not in the range of 192.168.1.0 – 192.168.1.255, or else its no in the same network. Then your computer will try to move the request to the default gateway which is specified as 192.168.1.1.

Computer will broadcast a ARP message to the network and only the corresponding interface will reply for that. Now the computer knows the MAC address of the default gateway. So it will create a packet with Source IP (S-IP) 192.168.1.1, Destination IP (D-IP) as 4.4.4.4. Source MAC address (S-MAC) is aaaa:aaaa:aaaa . But C1 doesn’t know the MAC address of the S1, and its now decided to forward the packet to the default gateway. Therefore, destination MAC address (D-MAC) will be bbbb:bbbb:bbbb.
Now the packet is in the R1 router. It will check the packets D-MAC address and feel it’s for the router R1. When it checks the D-IP address router realize that it’s not for the router but it need to go through the router to some were else. Now the router checks its routing table and realizes that the required network is not connected to it. But the router is capable of knowing neighbor route; therefore R1 will try to move the packet to the next best router. To do that R1 modify the packets S-MAC to cccc:cccc:cccc and D-MAC dddd:dddd:dddd. But it wont change the S-IP (but NAT will do a small change) and D-IP.
So this is like we travelling form SL to SIN in the example. This process will happen in all the routers which are in the path for the network 4.4.4.4.

When the packet comes to R3, it also checks the D-MAC and D-IP. When R3 checks the D-IP, it knows that it has connected to that requested network. So it moves the packet to the switch which will map D-IP to its MAC and forward it to the S1. So in this whole process MAC works as a temporary address, but IP works as the permanent address. So that’s why we need two addresses to communicate over a network.

Jun 17, 2011

Add Syntax Highlighter To Blogger

We can use a syntax highlighter to display source code syntax in different colours. It will create a user friendly environment to read the source code.
I'm going to use google-code-prettify to do this task.

First thing you need to add a java script and a css to your blog. It should be placed after the <head> tag. To do this you must go to settings -> design -> edit html.
Press "Ctrl+f" and type " <head" , it will help to find the head tag. Then add the Javascripts and css like this.

<head>
<link href='http://google-code-prettify.googlecode.com/svn/trunk/src/prettify.css' rel='stylesheet' type='text/css'/> 
<script src='http://google-code-prettify.googlecode.com/svn/trunk/src/prettify.js' type='text/javascript'/>

Then you need to modify the "<body>" tag. It should be like this.

<body onload="prettyPrint()" ... >

Then you can write your code within <pre$gt;</pre$gt; or <code$gt; </code$gt;. But to add the colours you need to add the class as,

<pre class="prittyprint">
   <!-- Your code comes here. -->
</pre>

Note: - First use "Compose" to add the coding then go to "Edit HTML" to add the pre tag with class. There is an effect between <> and &lt;&gt; .

This is a sample java program.

class HelloWorldApp {
    public static void main(String[] args) {
        System.out.println("Hello World!"); // Display the string.
    }
}

Jun 16, 2011

Visual Studio and C# (Some Useful Code Samples)

Creating MDI Forms (Multiple Document Interface).

Add 2 new Forms (Form1, Form2) to the solute on. Form1 will be the main frame and Form2 will be inside the first one. So in the first one we must make it as a MDIParent form. To do that, select the Form1 and go to its properties. In that list you will see a property called “IsMdiContainer”. Set it to TRUE. Now you will see that the form has been changed. Then go to the code behind of the Form1. In the constructor of the class, you should write this code in order to view the Form2 inside the Form1.

Note: - You can use a toolStrip instead of writing the code in the constructor.
public Form1()
{
        InitializeComponent(); // This is an auto generated code.
        // start of our code.
        Form2 fm = new Form2();
        Fm.MdiParent = this;
        Fm.Show();
        // end of our code.
}
These 3 lines of code will do the trick. Think if you need to open another form (Form3) by clicking a button in Form2, so you need to modify the 2nd line of this code to,
Fm.MdiParent = this.Parent;
This will set the MdiParent for Form3, by the parent of Form2. It means that it will use the Form1 as the parent of the Form3.



Connect your .NET Application to MySQL Database.

Most of the time .Net applications will use MSSQL database. But here is a sample code to connect your application to MySQL database.

First of all you need to install MySQL connecter for .NET environment. It can be freely download from this link. (For windows and MONO project.)

http://dev.mysql.com/downloads/connector/net/

Note: - Close Visual Studio before you start installing the connector.

I will not going to create a DbAccess class here, just simply tell how to use it.

First of all you need to add a reference called “MySql.Data” to your project. Then you need to add namespace,
Using MySql.Data; 
After that I will use a button click event to get data from the MySQL database.
private void button1_Click(object sender, EventArgs e)
{        
   string result = null;

   InitializeComponent();
   string ConString = "User Id=user;"+ 
                      "password=password;"+
                      "Persist Security Info=True;"+
                      "server=localhost;"+
                      "database=test";

   MySqlConnection conn = new MySqlConnection(ConString);

   MySqlCommand cmd = conn.CreateCommand();
   cmd.CommandText = "Select * from test";
   conn.Open();

   MySqlDataReader reader = cmd.ExecuteReader();
   while (reader.Read())
   {
      result += reader["name"].ToString() + " \n ";
   }
   conn.Close();
   MessageBox.Show(result);
}


Use configuration files in Visual Studio.

In the previous sample code I hard code the MySQL connection string. But that is not a good practice. Because some configurations like the password will rapidly change. So if we hard code these settings, we need to compile the application each and every time after changing the password. So to avoid that overhead we use a configuration file called “App.Conf”. You can add this file to your project by going to add new item.

This is an XML file. So to add the MySQL connection string data, you need to modify this XML file into something like this.
<?xml version="1.0" encoding="utf-8" ?>
<configuration>  
    <configSections>
    </configSections>
    <connectionStrings>
        <add name="MySQLConStr" 
             connectionString="User Id=user; 
                               password=password; 
                               Persist Security Info=True; 
                               server=localhost; 
                               database=test"
             providerName="MySql.Data.MySqlClient" />
    </connectionStrings>
</configuration>

Then go to your C# code and modify the connection string to something like this. To do this you may need to add a namespace,
using System.Configuration;

string ConString = ConfigurationManager.ConnectionStrings["MySQLConStr"].ToString();
Note: - Give the same name to both <add name="" ... > and ConnectionString[""].

May 28, 2011

Form validation - Javascript client side programming

When we are developing a web based software we must think about 2 things. One is server side and the other is client side. In the server side it will host the logic of the software and maybe the data storage. But all user interactions will be happen in the client side. If a user need to input some values, (maybe filling a form) each submit will send a http message to the server. Then according to the message it will give the response (maybe storing values in a database).

So why form validation? Forms are the main method that used to get inputs from a user. Users can input what ever he/she wants. So we can not think that a user will only fill the form according to the requirement or he/she may miss an important field. If something happens like this, it will harm the software. So to avoid such a thing we use validation.

To do the validation we get user input and check whether user inputs are according to the needs of the software. As an example, if the software need an 3 digit number, in the validation process it will check if the user had input a 3 digit number or something else. If the validation pass (user had input exactly a 3 digit number) software will continue its process(maybe storing in a database). But if the validation process fails (user had input something else), software will stop its process and it must request to re-enter the information correctly. So this request will cost some extra http requests. More http requests will cost more network usage and more network traffic. If the user enter wrong information for several times this will be worse.

To avoid this overhead we must move the validation part to the client side. From this approach we will only get valid information from the client side. So it will reduce unnecessary http requests. We can use Javascript, a client side programing language to do this.

<form action="process.php" method="POST">
<input type="text" name="myinput" id="myinput"  maxlength="5" >
<input type="submit" value="Submit" onClick="return validate()" />
</form>


<script type="text/javascript">
function validate()
{
var ret=true;
var input=document.getElementById("myinput").value;
if( input==null || input=="" )
{
  alert("Field is empty.");
  ret=false;
}
return ret;
}
</script>

This is a basic validation form. In this forms input field you can see something like " maxlength="5" ". It is a attribute in input tag. It can limit the number of input characters to 5. Then in the other input field (Submit button) you can see something like " onClick="return validate()" ". This is the most important part of the form. When a user click the submit button, it will trigger the "onClick" event. According to this form onClick event will call a function called " validate() ". This function will return true or false. So after user click the submit button it will be like onClick="return true" or onClick="return false". If the onClick event returns true, form will send the http request to the server. If the onClick event returns false, it will not send a http request and we can inform about the error by giving a popup like in this code.

Note:-
Although this reduce unnecessary http requests, it will add some extra code in to the html page. And also you must validate the inputs in the server side again though you validate it in the client side. There are ways to hack this client side validation process easily.

Jan 5, 2011

vaadin clojure app (coding onlly)

This is a simple app which get two numeric values and give its sum as a message.

(ns myapp.core
 (import (com.vaadin.ui Layout)))

(defn getSum [tf1 tf2]
(let [a  (Double/parseDouble (. (. tf1 getValue) toString))
      b  (Double/parseDouble (. (. tf2 getValue) toString))
      c (+ a b)]
      (. c toString))
)

(defn main [args]
  (proxy [com.vaadin.Application] []
    (init []
      (let [app this
            l1  (new com.vaadin.ui.Label "My Application")
            tf1 (new com.vaadin.ui.TextField "Input value one :")
            tf2 (new com.vaadin.ui.TextField "Input value two :")]
        (.setMainWindow this
          (doto (new com.vaadin.ui.Window "Welcome to myapp")
            (.addComponent l1)
            (.addComponent tf1)
            (.addComponent tf2)
            (.addComponent
              (doto (new com.vaadin.ui.Button "Click Me")
                (.addListener (proxy [com.vaadin.ui.Button$ClickListener] []
                   (buttonClick [event]
                       (. (. app (getMainWindow)) (showNotification "The Sum is :" (getSum tf1 tf2)  )))))))
           ))))))
To get the real output you need to view the previous post.

Jan 4, 2011

Writin a Vaadin app using Clojure

First of all you need Clojure with leiningen environment. Vaadin jar file.

Setup the leiningen environment and create a new project.
lein new myapp

Then change the directry to myapp and there you can see some flies. Edit the file src/myapp/core.clj file to your vaadin app. After editing it will be like this.

(ns myapp.core)

(defn main [args]
  (proxy [com.vaadin.Application] []
    (init []
      (let [app this]
        (.setMainWindow this
          (doto (new com.vaadin.ui.Window "Test application")
            (.addComponent
              (new com.vaadin.ui.Label "Hello Vaadin/LISP user!"))
            (.addComponent
              (doto (new com.vaadin.ui.Button "button")
                (.addListener (proxy [com.vaadin.ui.Button$ClickListener] []
                                (buttonClick [event] (. (. app (getMainWindow)) (showNotification "test")))))))))))))

Note the (ns **** ).

Then edit the project.clj file.

(defproject myapp "1.0.0-SNAPSHOT"
  :description "FIXME: write"
  :dependencies [[org.clojure/clojure "1.2.0"]
                 [org.clojure/clojure-contrib "1.2.0"]
                 [com.vaadin/vaadin "6.4.8"]]
  :dev-dependencies [[uk.org.alienscience/leiningen-war "0.0.1"]]
  :aot [myapp.core])

In this you can see there is a   :dev-dependencies [[uk.org.alienscience/leiningen-war "0.0.1"]] and   :aot [myapp.core]. First one is a plugin which can createa WAR file. The second one is to create the servlet class from the clojure file.

Now we need to write the web.xml file.

<?xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp_ID" version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
        <display-name>testVaadin</display-name>
        <context-param>
                <description>Vaadin production mode</description>
                <param-name>productionMode</param-name>
                <param-value>false</param-value>
        </context-param>
        <servlet>
                <servlet-name>Lisp</servlet-name>
                <servlet-class>org.thilina.Servlet</servlet-class>
                <init-param>
                        <param-name>script-name</param-name>
                        <param-value>myapp.core</param-value>
                </init-param>
                <init-param>
                        <param-name>package-name</param-name>
                        <param-value>myapp.core</param-value>
                </init-param>
                <init-param>
                        <param-name>function-name</param-name>
                        <param-value>main</param-value>
                </init-param>
        </servlet>
        <servlet-mapping>
                <servlet-name>Lisp</servlet-name>
                <url-pattern>/*</url-pattern>
        </servlet-mapping>
</web-app>

Vaadin http handling is little bit different so we neet to some additional task. You need to compile above java code and place those classes in the class directory.

package org.thilina;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import clojure.lang.RT;
import com.vaadin.Application;
import com.vaadin.terminal.gwt.server.AbstractApplicationServlet;

public class Servlet extends AbstractApplicationServlet {

 @Override
 protected Class<? extends Application> getApplicationClass()
   throws ClassNotFoundException {
  return Application.class;
 }

 @Override
 protected Application getNewApplication(HttpServletRequest request) throws ServletException {
  try { //load script, with name provided as a servlet's parameter
   RT.load(getServletConfig().getInitParameter("script-name"), true);

   //run Lisp function
   return (Application)RT.var(getServletConfig().getInitParameter("package-name"),
                 getServletConfig().getInitParameter("function-name")).invoke(new String[0]);
  }
  catch (Exception e) {
   throw new ServletException(e);
  }
 }
}

You need clojure.jar and vaadin.jar in order to compile this java file.

Now you can compile the project and get a WAR file.
lein deps
lein compile
lein uberwar

Then put this *.war file to tomcat/webapps directory.


References :-

https://github.com/technomancy/leiningen
http://dev.vaadin.com/wiki/Articles/ClojureScripting