Sunday, September 21, 2014

How to use Enum, Properties and string compare

using System;
using System.Collections.Generic;

namespace Workshop
    public enum Grades
    //class variable or members
    public class Student
        //Define simple properties
        public string Name { get; set; }
        public int TotalMarks { get; set; }
        public string Course { get; set; }
        //read only complex property
        public Grades PassingGrades
                if (TotalMarks >= 80)
                    return Grades.Distinction;
                else if (TotalMarks >= 60)
                    return Grades.FirstClass;
                else if (TotalMarks >= 50)
                    return Grades.Pass;
                    return Grades.Fail;
        //Definte complex properties
    class Program
        static void Main(string[] args)
            //prepare few student objects
            Student st1 = new Student();
            st1.Name = "Adrian";
            st1.Course = "EWS";
            st1.TotalMarks = 80;
            Student st2 = new Student();
            st2.Name = "Ross";
            st2.Course = "AA";
            st2.TotalMarks = 60;
            //simple collection of Student objects
            List allStudents = new List();
            //now print grades of all EWS student
            foreach (var st in allStudents)
                //string compare
                if (st.Course.Equals("EWS"))
                    //this is how we use enum
                    Console.WriteLine(st.Name  + " " + st.PassingGrades);

            //now print AA studets
            //this is simple java like loop
            for (int i = 0; i < allStudents.Count; i++)
                //string compare in differnt way
                if (allStudents[i].Course == "AA")
                    //use enum to print
                    Console.WriteLine(allStudents[i].Name + " " + allStudents[i].PassingGrades);

Friday, January 31, 2014

C# Currency Converter using Google API

//A very simple currency converter using google API.
private decimal GoogleCurrencyConverter(string fromCurrency, string toCurrency)
        WebClient web = new WebClient();

        string url = string.Format("{0}&to={1}", fromCurrency.ToUpper(), toCurrency.ToUpper());

        string response = web.DownloadString(url);

        Regex regex = new Regex("(\\d*.\\d*)");
        var r = regex.Match(response);

        return Convert.ToDecimal(r.Groups[1].Value);

Tuesday, September 03, 2013

Currency Converter via XML web service

//add webservice client = new;
var currencies = client.GetCurrencies();

//Convert the XML result into dataset/table
DataSet ds = new DataSet();
ds.ReadXml(new System.Xml.XmlTextReader(new StringReader(currencies)));

string name = null;
string code = null;

//name & country code.
foreach (DataRow r in ds.Tables[0].Rows)
    name = r["Name"].ToString();
    code = r["CountryCode"].ToString();

    Console.WriteLine(name + " " + code);

Monday, April 08, 2013

How to Send document from website to client C#


<%@ Page Title="Home Page" Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<asp:Content ID="HeaderContent" runat="server" ContentPlaceHolderID="HeadContent">

<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
        Testing opening word document from webpage.
    <asp:Button runat="server" ID="btnStart" Text="Click here" onclick="btnStart_Click"/>

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class _Default : System.Web.UI.Page
    protected void Page_Load(object sender, EventArgs e)
    protected void btnStart_Click(object sender, EventArgs e)
        Response.AddHeader("content-disposition", "attachment;filename=Test.docx");
        Response.ContentType = "application/ms-word";
             //If you have sharepoint path then change here..



Sunday, March 10, 2013

MySql set password for "root" user

How to set password for 'root' users on mysql

  1. Start mysqld with below option
  2. c:> mysqld --defaults-file=c:\mysqlc\my.ini --console --skip-grant-tables

  1. start mysql client
  2. use mysql
  3. update user set password=PASSWORD('newpassword') where user='root"
restart mysqld without --skip-grant-tables option.. thats all

Monday, February 18, 2013

MySql cluster and Java


  • ClusterJ API : ClusterJ is a high level database API that is similar in style and concept to object-relational mapping persistence frameworks such as Hibernate and JPA
  • Requires below jar files
    driver-5.1.10.jar (This is the MySQL JDBC driver)


import com.mysql.clusterj.annotation.Column;
import com.mysql.clusterj.annotation.Index;
import com.mysql.clusterj.annotation.PersistenceCapable;
import com.mysql.clusterj.annotation.PrimaryKey;

//sample code

Properties props = new Properties();
//replace localhost with managment node hostname
props.put("com.mysql.clusterj.connectstring", "localhost:1186");

//replace mydb with your database name.
props.put("com.mysql.clusterj.database", "mydb");


MySQL Cluster on Windows my way

Welcome to crash mysql cluster master page :-)

Lets plan to implement it this way.

NodeIP Address
Management (MGMD) node192.168.0.10
MySQL server (SQL) node192.168.0.20
Data (NDBD) node "A"
Data (NDBD) node "B"

Precautions: Always use forward slashesh or 2 backward slasesh for specifying the paths in config or ini files.

Step 1: Download and install (on sqlnode host or
  • Download Binaries here
  •  Extract the zip to c:\mysql directory. If you put into c drive you will need admin rights to start management console. If you put in c:\users\\mysqlc you dont need admin rights to start anything so choice is yours.
    Note: Basically you need full rights on the directory.
  • Add path c:\mysql\bin to Environment Variable.
  • leave this and come back on step 3
Step 2: Setup management node
  • Create c:\mysql\bin directory
  • copy ndb_mgmd.exe and ndb_mgm.exe in c:\mysql\bin from sqlnode host

    > Note: we just need these executables on management node.
  • Create local configuration file my.ini - this file needs only to supply the location of configuration file

    # options for manangement node process
  • Create configuration file config.ini with below content and save to c:\mysql\bin
[ndbd default]

HostName=               # Hostname or IP address of management node
DataDir=C:/mysql/bin/cluster-logs   # Directory for management node log files

# Options for data node "A":  # (one [ndbd] section per data node)
HostName=           # Hostname or IP address

# Options for data node "B":
HostName=           # Hostname or IP address

# SQL node options:
HostName=           # Hostname or IP address

Step 3: Setup sql node
  •  create c:\mysql\my.ini with below content
# Options for mysqld process:
ndbcluster                      # run NDB storage engine
ndb-connectstring=  # location of management server

#use different port if you already have mysql server running or uncomment below

#provide basedir and datadire if they are not in c:\ drive

Step 4: Setup Data nodes

Follow the below steps on data node hosts.
  • Create c:\mysql and c:\mysql\bin and c:\mysql\bin\cluster-data directory
  • Copy ndbd.exe from ( into c:\bin
    Note: we just need this executable and nothing else for data node.
  • Create my.ini into c:\mysql\my.ini and add below content

    # Options for data node process:
    ndb-connectstring=  # location of management server

Step 4: Start the cluster.
  • 1st start managment nodec:\mysql\bin> ndb_mgmd -f config.ini [--initial]
    Important: management node cashes the configuration data that it reads from config.ini. If you make any changes in configuration you must provide --reload option or --initial option to realod the configuration otherwise the -f config.ini option will be ignored from 2nd run onward
    Note: remove "[" and "]" if you are using the --initial option
    Note: -f or --config-file is same.
    Important: By default cluster create configuration cache in c:\mysql\bin\mysql-cluster directory but you can override with --configdir option.
  • 2nd start data nodesc:\mysql\bin> ndbdNote: as long as you are running the process from bin directory and your my.ini file is in the bin directory you dont need provide any path.
  • Start Node Manager to see what's going on..c:\mysql\bin> ndb_mgmndb_mgm> show ndb_mgm>ALL STATUS
  • finally, start sql nodec:\mysql\bin>mysqld --console

    Note: console option provide more details and can be used for debugging purpose. Again as long as you keep the my.ini in the bin directory you dont need provide any path.

Known Errors & Resolutions.
  • If data nodes are stopping then Start node with --initial parameter, ie. >ndbd --initial
  • If data directory are stored in different location than default binary location
  • The below option "--console" provides debugging information when used with mysqld

    c:\mysql\> mysqld --console


Sunday, February 17, 2013

How to Display time in Different Timezones

Specific Example: How to display current time for Rio De Janeiro?

  1. Find out the timezone abbreviation or name from here
    Timezone abbreviation: BRT – Brasilia time
  2. Find out the mapping of correct standard name for the above timezone.
    065E. South America Standard Time(GMT-03:00) Brasilia
  3. Now we can use the code to set timezone to E. South America Standard Time

here is the code sample.

using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;

namespace Timezone
    class Program
        static void Main(string[] args)
            System.Console.WriteLine("Local time:" + DateTime.Now.ToString());

            var brazilTime = TimeZoneInfo.ConvertTime(DateTime.Now, TimeZoneInfo.FindSystemTimeZoneById("E. South America Standard Time"));
            System.Console.WriteLine("Brazil Time:\t" + brazilTime.ToString());