Hiteshagja.com
Knowledge is power
Show MenuHide Menu

Category Archives: General

Geographical SVG Map With Example

April 6, 2013

In web if you want to provide any geographical svg map related solution then consider map as some random shape. Every map is nothing but a random shape. And in web if you want to draw any shape SVG is the best option. SVG stands for Scalable Vector Graphics.

But to draw shape like this will require lot of skill and time. So, I find one website which gives us almost all countries detailed map in different formats like GIF, PDF, SVG and many other.

Please visit d-maps.com

I have taken India map from d-maps.com. This is SVG map.

Rest is depending upon your logic. :)

Apply Culture In Silverlight Application

September 1, 2012

Culture In Silverlight Application plays a very important role. Silverlight application always sits on client browser and works as a plug-in. So you always need to keep in mind that control panel setting of different user might be different especially regional and language settings. Different user on different countries uses different date, time and number formats so while building Silverlight application you have to consider this fact and build your application accordingly and you need to make sure that you have applied culture in Silverlight application.

Recently I come across issue where application uses M/d/yy format date throughout application and it worked fine till user had not changed anything from regional settings. When user changed short date time format from control panel > regional and language settings application started giving errors of bad date and time. So I needed to apply default en-US culture in my application to resolve this issue. What I have done is I have applied en-US culture in current thread on application startup i.e. app.xaml.cs.

Here is the code for the same.

private void Application_Startup(object sender, StartupEventArgs e)
{
System.Globalization.CultureInfo c = new System.Globalization.CultureInfo("en-US");
c.DateTimeFormat.LongDatePattern = "dddd, MMMM dd, yyyy";
//YOU NEED TO PROVIDE ESCAPE SEQ IF YOU ARE USING SLASH IN YOUR FORMAT
c.DateTimeFormat.ShortDatePattern = "M\\/d\\/yyyy";
System.Threading.Thread.CurrentThread.CurrentCulture = c;
System.Threading.Thread.CurrentThread.CurrentUICulture = c;
}

I hope this will help others to solve the same problem.

JSON in Javascript Explained

August 15, 2012

What is JSON in Javascript?

JSON stands for Javascript Object Notation. JSON is nothing but an object which contains key value pairs. Advantage of JSON over other data format is it is lightweight. JSON is platform independent as well as language independent data exchange format.

JSON object example

Example:

var jsonObj = {id:1,name:”hiteshagja”};

In this example Keys are id and name and Values are 1(typeof int), hiteshagja(typeof string).

So If you write alert(jsonObj.name) in javascript you will get alert containing text hiteshagja. Isn’t this so amazing about JSON.

Add New Property(key) to already existing JSON object.

Example 1:

jsonObj.email=”hiteshagja24@gmail.com”;

Or

jsonObj[“email”]= ”hiteshagja24@gmail.com”;

This will add new key email to already existing jsonObj. You don’t need to write anything else other than this.

But if you write like

Example 2:

jsonObj.name=”hiteshagja.com”;

Or

jsonObj[name]=”hiteshagja.com”;

This will only update our JSON object key value from hiteshagja to hiteshagja.com.

JSON currently supports

String
Number
Object
Array
Boolean
Data types and
Null value

Get JSON object’s keys count

Object.keys(jsonObj).length

will return number of keys in given JSON object. In our case this will return 3(id,name and email).

Delete key

delete jsonObj[“email”]

this will remove email key value pair from jsonObj. Delete is a keyword which will accomplish this task.

String to JSON object

Example:

var jsonStr=’{“id”:”1”,”name”,”hiteshagja”}’;

Let’s say you have string value just like shown above and you want to convert it into JSON object.

var

jsonObj=JSON.parse(jsonStr);

Or

var jsonObj=eval(jsonStr);

will convert JSON string into object.

JSON object to String

In some cases you will be needed converting JSON object into string there you can use conversion like shown below.

Example:

var jsonStr= JSON.stringify(jsonObj);

This will convert jsonObj into string.

JSON Array

Till now you have seen how to create single JSON object. Now in some cases we will need to store data as an array. Let’s see how we can do so.

Example 1:

var jsonObj={id:1,name:”hiteshagja”,phone:[1111111111,2222222222]};

Here as you can see I have written phone value as an array.

You can access phone number using jsonObj.phone[0] just like you are accessing other array objects.

Example 2:

var jsonObj={

Products:[ {name:”Product1”

color:”Red”

code:1},

{name:”Product2”

color:”Green”

code:2},

{name:”Product3”

color:”Blue”

code:3}]

};

Example 2 is real time scenario where you will have array of products. jsonObj is array of products which contains 3 products in our example.

If you want to access product 2 then you can simple write

Products[1][Key].

I will keep updating this post whenever I will find anything interesting about JSON.

Silverlight – Listbox Scrollbar Problem

June 23, 2011

Recently I have observed that listbox scrollbar has virtualization problem when we re-bind listbox. Let me explain this with an example.

I have added 50 items into listbox control programmatically. Here is the screenshot for the same.

Image after 50 Items bound to listbox

Normal Listbox Binding

Re-bind listbox

Re-bind button click without scroll bar move

As you can see I have added two buttons to Reset and to Re-bind listbox again.

If I click on any of the button everything will work as expected but real problem is when we move scroll bar to bottom of the listbox and we re-bind listbox data.

See what kind of problem you shall face.

Problem displaying data

Solution :

Use scrolltoview function after assigning ItemsSource to listbox. See code snippet below.

[sourcecode language="csharp"] List<ListBoxItem> a=GetItemsList(txt,count);

listbox1.ItemsSource = a;

if(a.Count()>0)

{

listbox1.UpdateLayout();

listbox1.ScrollIntoView(a[0]);

}

[/sourcecode]

Dealing with DateTime Formats in C#

June 8, 2011

Dealing with datetime formats in C# is very easy if you use framework functions properly. Recently I come across very ugly error which makes my application crashed. Actually it was problem converting DateTime for specific format. You should make your DateTime conversion independent of client computer’s culture setting. This thought in mind I am going to present this post.

1.       Convert String  to DateTime

Let’s take an example:

Suppose you have

[sourcecode language="csharp"] String strDate = "10/23/2011"; [/sourcecode]

Which is in MM/dd/yyyy format and you want to convert it in DateTime variable then you should write like

[sourcecode language="csharp"] DateTime dt = Convert.ToDateTime(strDate,System.Globalization.CultureInfo.InvariantCulture); [/sourcecode]

You could write above code if you are sure that the format is in MM/dd/yyyy. If the format is in say dd/MM/yyyy then DatTime.ParseExact is the perfect option for you.

Code above can be rewritten as

[sourcecode language="csharp"] DateTime dt = DateTime.ParseExact(strDate, "dd/MM/yyyy", System.Globalization.CultureInfo.InvariantCulture); [/sourcecode]

In all above code lines I have mentioned System.Globalization.CultureInfo.InvariantCulture parameter, which will make date format, culture independent.

2.       Convert Datetime to Specific Format

Let’s say you have

[sourcecode language="csharp"] DateTime dt = DateTime.Now; [/sourcecode]

and you want to convert it in different format. 

Example : Format : dd-mmm-yyyy

[sourcecode language="csharp"] String s = dt.ToString("dd/MMM/yyyy"); [/sourcecode]

But this will be overridden by current culture.

So you should do something like this

[sourcecode language="csharp"] String s = dt.ToString("dd/MMM/yyyy", System.Globalization.CultureInfo.InvariantCulture); [/sourcecode]

In short, CultureInfo parameter plays an important role.

Run Executable (exe/bat) file from Web Page

August 22, 2010

To run an exe from your web page is quite easy process. I have used simple JavaScript to accomplish this task. Have a look at the code listed below.

[code lang="javascript"]
function WriteToFile() {

var fso, s,folderName;

fso = new ActiveXObject("Scripting.FileSystemObject");

if (!fso.FolderExists("C:\HITESH"))

{

folderName=fso.CreateFolder("C:\ HITESH ");

}

if (!fso.FileExists("C:\ HITESH \LaunchApp.bat")){

s = fso.OpenTextFile("C:\ HITESH \LaunchApp.bat" , 8, 1, -2);

s.writeline("IF EXIST d:\hitesh GOTO LABEL1”);

s.writeline("IF EXIST k:\hitesh GOTO LABEL2”);

s.writeline(":LABEL1”);

s.writeline("D: ”);

s.writeline("D:\hitesh\AppTest.EXE”);

s.writeline("EXIT”);

s.writeline(":LABEL2”);

s.writeline("K: ”);

s.writeline("K:\hitesh\AppTest.EXE”);

s.writeline("EXIT”);

s.Close();

}

}

function LaunchApp() {

WriteToFile();

var oShell = new ActiveXObject("WScript.Shell");

var prog = "C:\ HITESH \LaunchApp.bat";

oShell.run ('"'+prog+'"',1);

}
[/code]

This javascript will create an object of WScript.Shell and will execute DOS based batch file. In addition with this I have also created LaunchApp.bat file programmatically if it does not exist on the client side (So you don’t need to worry about whether file exist or not J). This file will execute EXE depending upon conditions specified in the LaunchApp.bat. LaunchApp() is the starting point.

Populate data in Gridview using jQuery AJAX

August 9, 2010

I search a lot in Google for a whole day but didn’t find any perfect example to populate data in gridview using jquery ajax. Then I have decided to do it myself and I find it easy at the end of the day.

In the example which I illustrated below follows the flow:

  1. On document ready method it initiates jQuery AJAX call.
  2. Response will be redirected to the ASPX page and in tern server will respond with JSON data.
  3. jQuery AJAX call back success method used to generates HTML Table with data.
  4. Add HTML to DIV.

Here is the code:

Default.aspx

[code lang="html"]
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">

<head runat="server">

<title>Untitled Page</title>

<script type="text/javascript" src="js/jquery-1.4.2.min.js"></script>

<script src="js/commons.js" type="text/javascript"></script>

</head>

<body>

<form id="form1" runat="server">

<div id="divperson">

<strong>[Newly generated HTML will seat here]</strong>

</div>

</form>

</body>

</html>
[/code]

Default.aspx.cs

[sourcecode language="csharp"]
public partial class _Default : System.Web.UI.Page

{

protected void Page_Load(object sender, EventArgs e)

{

if (!IsPostBack)

{

if (Request.QueryString["id"] == "person")

GetString();

}

}

public void GetString()

{

JavaScriptSerializer _serializers = new JavaScriptSerializer();

string _personJSON = _serializers.Serialize(Person.GetPersonDetails());

Response.Clear();

Response.Write(_personJSON);

Response.End();

}

}

<strong>//Person Class and Members</strong>

public class Person

{

public string Name { get; set; }

public string State { get; set; }

public string PhoneNumber { get; set; }

public Person(string name, string state, string phone)

{

Name = name;

State = state;

PhoneNumber = phone;

}

public static List<Person> GetPersonDetails()

{

List<Person> _person = new List<Person>();

_person.Add(new Person("Hitesh", "Gujarat", "123"));

_person.Add(new Person("Urvish", "Maharastra", "345"));

_person.Add(new Person("Deepak", "Madhya Pradesh", "456"));

return _person;

}

}
[/sourcecode]

I just created Person class, created some properties and a static method to generate list of Person class objects. You need to include System.Collections.Generic and System.Web.Script.Serialization name space for List Class and JavaScriptSerializer class respectively.

In Page_Load method, based on the querystring value the GetString() method will call and JSON response will be generated and submitted as response. You need to catch this response on client side to retrive values within JSON formatted data.

commons.js (a separate JS file)

[code lang="javascript"]
$('document').ready(function(){

$.ajax({

type: "GET",

data:({id:"person"}),

url: "Default.aspx",

dataType: "json",

success:function(resultdata){

var person;

var _html='<table border="1">';

_html += '<tr>';

_html += '<th>Name</th>';

_html += '<th>State</th>';

_html += '<th>Phone</th>';

_html += '</tr>';

for(index in resultdata)

{

_html +='<tr>' ;

_html +='<td>' + resultdata[index].Name + '</td>';

_html +='<td>' + resultdata[index].State + '</td>';

_html +='<td>' + resultdata[index].PhoneNumber + '</td>';

_html +='</tr>' ;

}

_html +='</table>' ;

$('#divperson').html(_html);

}

});

});
[/code]

Nothing fancy, using jquery.ajax method I made a GET request to Default.aspx page with some data. Page has return JSON data which I parsed in jquery.ajax success method.

Before you attempt to run this code in your app, make sure you have included jquery-1.4.2.min.js file.

Encode Text Message to PDU

June 27, 2010

Encode Text Message to PDU before submitting it to network. [Note: this is applicable if you are going to send SMS in PDU mode]. In this post I am going to explain how you can do this, but before that please download sample code from Planet Source code. This code contains Convert, Sending and Receiving modules. Frankly speaking I have got encoding/decoding logic from this code and it works perfectly for me. Only thing missing in this code is Padding Bit logic. Code is quite simpler and easily understandable. Please go through it and tell me if you have problem encoding text message into PDU.

How to add Padding bit for multipart SMS PDU?
Open the code > go to Convert Module > Find “CharHex”  Method.
Do replace this function with the code shown below.

Public Function CharHex(ByVal Txt As String, ByVal bit As Integer, ByVal PaddingBit As Boolean)
Dim i As Integer, bin As String, nbin As String, n As String
Dim bil As Integer, sisa As Integer, lbin As Integer, nol As String
bin = ""
nbin = ""
If bit = 7 Then
For i = 1 To Len(Txt) Step 2
n = Mid(Txt, i, 2)
bin = HexToBin(n) & bin
Next
bil = Len(bin) bit
sisa = Len(bin) Mod bit
For i = 1 To (Len(bin) - sisa) Step bit
' MsgBox Chr$(HexToDec(BinToHex(Mid(bin, i + Sisa, bit))))
nbin = Chr$(HexToDec(BinToHex(Mid(bin, i + sisa, bit)))) & nbin
Next
Else
For i = 1 To Len(Txt)
n = Mid(Txt, i, 1)
bin = Biner(Asc(n)) & bin
Next
If PaddingBit = True Then
bin = bin + "0"
End If
sisa = Len(bin) Mod bit
If sisa > 0 Then
For i = 1 To bit - sisa
nol = nol & "0"
Next
End If
bin = nol & bin
bil = Len(bin) bit
For i = 1 To bil
nbin = nbin & BinToHex(Mid(bin, Len(bin) + 1 - bit * i, bit))
Next
End If
CharHex = nbin
End Function

That’s it !!
Do let me know if you have any problem encoding text to PDU.

Update:

I am getting lot of queries regarding Message PDU for single message and concatenated message. So What I have done is I have created a quick sample to generate PDU for single message and for multipart SMS.

Download Sample (Generate SMS PDU)

MySQL With .Net 2.0/3.0/3.5

September 19, 2009

MySQL is open source database. We had always seen MySQL with PHP. Generally we know MySQL is database engine for PHP. It’s true because .net does not have inbuilt support for MySQL database. We need to install other tools to make it work perfectly. In order to work with MySQL in .net you need to install MySQL Server and MySQL Connector. You can create function and procedure in MySQL version 5.1 and later. At the same time you will get great user interface to manage database. You will get interface just like MS SQL server management studio. MySQL Connector is used to add database connectivity support in Visual Studio. Download Connector depending upon the .net framework you use and Visual studio you work on.  Version 5.1 GA (Generally Available) and later is recommended for .net framework 2.0 and higher.

Problems I faced:

  1. Syntax of MySQL is very different from MS SQL server.
  2. Error console of MySQL is not that user friendly.
  3. Migration of MS SQL Database to MySQL is quite difficult.
  4. Because it’s not Microsoft product you won’t find any inbuilt programming level support. Ex. It’s really hard to work use LINQ if your backend is MySQL.

Download Latest MySQL Database Server and Connector (Click Here).

Six Useful tips To Earn Money With Google Adsense

June 6, 2009

I recently went through different articles written under AdSense Help Section. All articles are worth reading if you are interested in earning good income with Google AdSense. I found some interesting tips  in this section

  1. Ad Type : 336×280 Large Rectangle, 300×250 Medium Rectangle and the 160×600 Wide Skyscraper this are the good performer. 
  2. Text + Image : Always prefer or give a try to Text and image ad combination.  
  3. Positioning Ads : Ad just above the website content or just below the end of the content tends to perform well.  Also, ads placed in between the content are also a good performer. If are you running a blog then the case may be different. In case of blog the add unit on the right hand side and add unit just below each post is very good money making machine.     
    Reference : https://www.google.com/adsense/support/bin/answer.py?answer=43869 https://www.google.com/adsense/support/bin/answer.py?answer=17954 
  4. Wider ad formats tend to be more reader-friendly. 
  5. Try putting as many ads you can in page. Right now you can place only 3 ads per page.  
  6. Colour : Change link colour, ad content colour and title colour depending upon your webpage colour scheme.  The impact of using this technique is user would have difficult to understand that whether it’s google ad your website link.

 Reference : https://www.google.com/adsense/support/bin/answer.py?answer=17957

 Click on the link below to find out all the useful tips given by the google for adsense.

https://www.google.com/adsense/support/bin/static.py?page=tips.html

Note : I have just try to summarise whatever is written in Google Adsense help section. All credit for this goes to Google Adsense Team.