Tuesday, September 8, 2009

calculating distance between two points whihc is from longitude and latitude

Here I am going to discuss the how to calculate the distance between two points using the longitude and latitude points.

Brief history: Latitude and Longitude are imaginary lines on the globe to measure the time difference and distance difference between two points.

Latitudes are horizontal lines and Longitudes are vertical lines. By using Longitude we can easily find out the time of any place with respect to standard time GMT.
While coming to distance calculation between two points, there is a necessity to take the latitude and longitude information.

It’s better to take the values as much as possible accurately, why becz earth is not perfect round shape. There is a 45 Kms between equatorial to poles, actually this is angular difference. So, we need to consider this factor while design the GIS kind of applications.

I am going to explain the things from the program..

The program take the latitude/longitude points in the form of decimal format.

It’s calculate the radiant value from the decimal inputs.

After we need to calculate the central spherical value(it’s accurate calculation for angular difference between locations)

Return the value in the kilometers


public string distanceinKms(double Latitude1, double Longitude1, double Latitude2, double Longitude2)
{
//mention the constant values
double C_RADIUS_EARTH_KM = 6371.1;
double C_RADIUS_EARTH_MI = 3958.82;
double C_PI = 3.14159265358979;

//actual story begins
double Lat1;
double Lat2;
double Long1;
double Long2;
long X;
double Delta;


X = 1;

//convert to decimal degree
Lat1 = Latitude1 * X;
Long1 = Longitude1 * X;
Lat2 = Latitude2 * X;
Long2 = Longitude2 * X;

//convert to radians: radians = (degrees/180) * PI
Lat1 = (Lat1 / 180) * C_PI;
Lat2 = (Lat2 / 180) * C_PI;
Long1 = (Long1 / 180) * C_PI;
Long2 = (Long2 / 180) * C_PI;

//get the central spherical angle
Delta = ((2 * ArcSin(Math.Sqrt(Math.Pow(Math.Sin((Lat1 - Lat2)/2),2) + Math.Cos(Lat1) * Math.Cos(Lat2) * Math.Pow(Math.Sin((Long1 - Long2) / 2),2)))));

//return the distance in kilo meters
return (Delta * C_RADIUS_EARTH_KM).ToString();

}

public double ArcSin(double X)
{
//ArcSin function. Improvise.
return Math.Atan(X / Math.Sqrt(-X * X + 1));
}




Observation:

First Location Values:
Country: PORT LOUIS
Latitufe: 20-08'S= -20.133333
Longitude: 57-29'E= 57.483333

Second Location Values:
Country: SAINT DENIS
Latitufe: 20-52'S= -20.866667
Longitude: 55-28'E= 55.466667

It’s required to pass the parameters like this

string sdskm = distanceinKms(-20.133333, 57.483333, -20.866667, 55.466667);


The output will be become 225.315719359445

Thursday, March 5, 2009

Windows Indexing by .Net

Here I am going to discuss about the Windows Indexing services. It's maintain search catalog information in the form of meta data. With the meta data we can access the search meta data information.

see the code fragment below:


using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Data.OleDb;
using System.Xml;
using System.Xml.Xsl;
using System.Text;
using System.IO;
public partial class Web_AdvQuery : System.Web.UI.Page
{
DataView results = null;
string TheQuery = "";
public static string ddlFolderName = "";
protected void Page_Load(object sender, EventArgs e)
{
btnExecute.Attributes.Add("onClick", "testEnterKey();");
if (!IsPostBack)
{
bindData();
fillFolderNameData();
}

}
protected void btnExecute_Click(object sender, EventArgs e)
{
bindData();
}
protected void btnClear_Click(object sender, EventArgs e)
{
SearchString.Text = "";
FileNameRestriction.Text = "";
DocAuthorRestriction.Text = "";
FSRestOther.Text = "";
FMModDate.Text = "";
resultsDataGrid.Visible = false;
}
protected void resultsDataGrid_PageIndexChanged(object source, DataGridPageChangedEventArgs e)
{
resultsDataGrid.CurrentPageIndex = e.NewPageIndex;
bindData();
}

public void bindData()
{
string fileTypes = "\".doc\" OR \".rtf\" OR \".txt\" OR \".pdf\"";
string freeTextQuery = BindDataFreeText();
string queryAppend = BinddataThroughQuery();
string DS = null;
if (IsPostBack)
{
string query = "SELECT DocTitle,Filename,size,path,rank,write,url from SCOPE() WHERE " + freeTextQuery + " CONTAINS(Filename, '" + fileTypes + "') ";
query += queryAppend.ToString() + " ORDER BY rank DESC, write DESC";
if (ddlFolderName.Equals("") == false)
DS = ddlFolderName.ToString();
else
DS = "KMSLOCAL";

OleDbConnection cn = new OleDbConnection("Provider= \"MSIDXS\"; Data Source=\"" + DS.ToString() + "\";");
OleDbDataAdapter cmd = new OleDbDataAdapter(query, cn);
DataSet data = new DataSet();
DataTable record = new DataTable();
DataTable dt = new DataTable();
DataRow dr;
cmd.Fill(record);
dt.Columns.Add(new DataColumn("#", typeof(string)));
dt.Columns.Add(new DataColumn("DocTitle", typeof(string)));
dt.Columns.Add(new DataColumn("Filename", typeof(string)));
dt.Columns.Add(new DataColumn("size", typeof(string)));
dt.Columns.Add(new DataColumn("path", typeof(string)));
dt.Columns.Add(new DataColumn("rank", typeof(string)));
dt.Columns.Add(new DataColumn("write", typeof(string)));
dt.Columns.Add(new DataColumn("url", typeof(string)));
int totalRecord = record.Rows.Count;
for (int i = 0; i < totalRecord; i++)
{
dr = dt.NewRow();
int j = i + 1;
dr[0] = j;
dr[1] = record.Rows[i]["DocTitle"];
dr[2] = record.Rows[i]["Filename"];
dr[3] = record.Rows[i]["size"];
dr[4] = record.Rows[i]["path"];
dr[5] = record.Rows[i]["rank"];
dr[6] = record.Rows[i]["write"];
dr[7] = record.Rows[i]["url"];
dt.Rows.Add(dr);
}
data.Tables.Add(dt);
results = new DataView(data.Tables[0]);
resultsDataGrid.DataSource = results;
resultsDataGrid.DataBind();
}
}


public string BindDataFreeText()
{
if (SearchString.Text.Equals("") == false)
{
string freeText = SearchString.Text.Trim().ToString();
freeText = freeText.Replace("'", "''");
return "FREETEXT('" + freeText + "') AND";
}
return null;
}
public void fillFolderNameData()
{
XmlDocument doc = new XmlDocument();
doc.Load(Server.MapPath("KMSLocal.xml"));
SortedList lstFolderName = new SortedList();
XmlNodeList elements = doc.SelectNodes("//myRoot/folder");
foreach (XmlElement element in elements)
{
string label = Convert.ToString(element.GetAttribute("label"));
if (lstFolderName.Contains(label) == false)
lstFolderName.Add(label, label);
//for creating new catalog
string rootFolder = this.Server.MapPath(ConfigurationManager.AppSettings["rootfolder"]);
rootFolder = rootFolder.Replace("\\Web", "");
string folderpath = rootFolder + "\\" + label;
CreateNewCatalog(label, folderpath);
}
FolderName.DataSource = lstFolderName;
FolderName.DataValueField = "Key";
FolderName.DataTextField = "Value";
FolderName.DataBind();
FolderName.Items.Insert(0, new ListItem("[--Select Folder Name--]", "any"));
}
public string fillthefolderItem()
{
XmlDocument doc = new XmlDocument();
doc.Load(Server.MapPath("KMSLocal.xml"));
string folderName = FolderName.SelectedItem.Text.Trim();
XmlNodeList elements = doc.SelectNodes("//folder");
foreach (XmlElement element in elements)
{
string labelText = Convert.ToString(element.GetAttribute("label"));
if (labelText.Equals(folderName) == true)
{
string xPathExpression = "//folder[@label='" + labelText + "']/file";
XmlNodeList FileLabel = doc.SelectNodes(xPathExpression);
StringBuilder fileNameList = new StringBuilder();
string FilelabelText = "";
foreach (XmlElement fileElement in FileLabel)
{
FilelabelText = Convert.ToString(fileElement.GetAttribute("label"));
fileNameList.Append("'" + FilelabelText + "'");
fileNameList.Append(",");
}
int length = fileNameList.Length;
return Convert.ToString(fileNameList.Remove(length - 1, 1));
}
}
return null;
}
public string BinddataThroughQuery()
{
string Composer = " AND ";
if (SearchString != null)
{
if (FSRestVal.SelectedValue.Equals("any") == false)
{
if (FSRestVal.SelectedValue.Equals("other") == false)
TheQuery = Composer + "size" + FSRest.SelectedValue.ToString() + FSRestVal.SelectedValue.ToString() + "" + TheQuery;
else
TheQuery = Composer + "size" + FSRest.SelectedValue.ToString() + FSRestOther.Text + "" + TheQuery;
}
if ((DocAuthorRestriction.Text).Equals("") == false)
TheQuery = Composer + "CONTAINS(DocTitle,'" + DocAuthorRestriction.Text.ToString() + "')" + TheQuery;

if (FMMod.SelectedValue.Equals("any") == false)
{
if (FMMod.SelectedValue.Equals("since") == false)
//TheQuery = Composer + "(write > " + FMMod.SelectedValue.ToString() +" AS VT_FILETIME"+") " + TheQuery;
TheQuery = Composer + "CONTAINS(write,'" + FMMod.SelectedValue.ToString() + "')" + TheQuery;
else
TheQuery = Composer + "(write > " + Convert.ToDateTime(FMModDate.Text.ToString()) + ") " + TheQuery;
//TheQuery = Composer + "CONTAINS(write,'" + FMModDate.Text.ToString() + "')" + TheQuery;
}
if ((FileNameRestriction.Text.Equals("") == false) && (FileNameRestriction.Text.Equals("any") == false))
TheQuery = Composer + "CONTAINS(Filename,'" + FileNameRestriction.Text.ToString() + "')" + TheQuery;
//TheQuery = Composer + "CONTAINS(Directory ,'" + FolderNameText() + "')" + TheQuery;
}

return TheQuery;
}
protected void ShowFile(object sender, CommandEventArgs Args)
{
System.Text.StringBuilder sb = new System.Text.StringBuilder();
sb.Append(Args.CommandName.ToString());
string[] splt = sb.ToString().Split('\\');
string queryString = sb.Replace(splt[0], "").ToString();
queryString = sb.Replace(splt[1], "").ToString();
queryString = sb.Remove(0, 2).ToString();
Prereview(queryString.ToString());
}

public void Prereview(string filepathString)
{
string filepath = Server.MapPath("~/" + filepathString);
// Create New instance of FileInfo class to get the properties of the file being downloaded
FileInfo file = new FileInfo(filepath);
// Checking if file exists
if (file.Exists)
{
// Clear the content of the response
Response.ClearContent();
// LINE1: Add the file name and attachment, which will force the open/cance/save dialog to show, to the header
// Response.AddHeader("Content-Disposition", "attachment; filename=" + file.Name);
Response.AddHeader("Content-Disposition", "inline; filename=" + file.Name);


// Add the file size into the response header
Response.AddHeader("Content-Length", file.Length.ToString());
// Set the ContentType
Response.ContentType = ReturnExtension(file.Extension.ToLower());
// Write the file into the response (TransmitFile is for ASP.NET 2.0. In ASP.NET 1.1 you have to use WriteFile instead)
Response.TransmitFile(file.FullName);
// End the response
Response.End();
}
}


public void CreateNewCatalog(string catalogName, string catalogPath)
{
CIODMLib.AdminIndexServerClass existingCatalog = new CIODMLib.AdminIndexServerClass();
bool FoundCatalog = existingCatalog.FindFirstCatalog();
while (!FoundCatalog)
{
CIODMLib.AdminIndexServerClass obj = new CIODMLib.AdminIndexServerClass();
obj.Stop();
obj.AddCatalog(catalogName, catalogPath);
CIODMLib.ICatAdm obj2 = (CIODMLib.ICatAdm)obj.GetCatalogByName(catalogName);
CIODMLib.IScopeAdm obj3 = (CIODMLib.IScopeAdm)obj2.AddScope(catalogPath, false, null, null);
obj3.Alias = "KMSLOCAL";
obj3.Path = catalogPath;
obj.Start();
FoundCatalog = existingCatalog.FindNextCatalog();
}
}



public string ReturnExtension(string fileExtension)
{
switch (fileExtension)
{
case ".htm":
case ".html":
case ".log":
return "text/HTML";
case ".txt":
return "text/plain";
case ".doc":
return "application/ms-word";
case ".tiff":
case ".tif":
return "image/tiff";
case ".asf":
return "video/x-ms-asf";
case ".avi":
return "video/avi";
case ".zip":
return "application/zip";
case ".xls":
case ".csv":
return "application/vnd.ms-excel";
case ".gif":
return "image/gif";
case ".jpg":
case "jpeg":
return "image/jpeg";
case ".bmp":
return "image/bmp";
case ".wav":
return "audio/wav";
case ".mp3":
return "audio/mpeg3";
case ".mpg":
case "mpeg":
return "video/mpeg";
case ".rtf":
return "application/rtf";
case ".asp":
return "text/asp";
case ".pdf":
return "application/pdf";
case ".fdf":
return "application/vnd.fdf";
case ".ppt":
return "application/mspowerpoint";
case ".dwg":
return "image/vnd.dwg";
case ".msg":
return "application/msoutlook";
case ".xml":
case ".sdxl":
return "application/xml";
case ".xdp":
return "application/vnd.adobe.xdp+xml";
default:
return "application/octet-stream";
}
}
protected void FolderName_SelectedIndexChanged(object sender, EventArgs e)
{
ddlFolderName = FolderName.SelectedValue.ToString().Trim();
}
}

Wednesday, February 4, 2009

how to Generate the Menu(s) programitically in asp.net and c#.net

How to Build Menu’s dynamically with Server Coding only in asp.net and c#.net

Hi to all,

After long time, I got time to post the article into this blog.

Creating the Menu’s in asp.net is biggest challenge. It is possible by two ways
1. Static Menu generation(design the menu component at the time of page designing)
2. Dynamic Menu Build.( the menu components are designed at the time of fly)

Second technic is more helpful than first one: Normally, in any project/application navigations are done by menucontrol. The number of menuitems are applicapable for users is depend upon their rights. Admin can able to see the all of the menuitems from the application.

These are the some good points for, how to collecting the menuitems.

1. The number of menuitems for particular user is depend upon his rights. So, at the time of login itself it’s better to find out the menuitems collections for respective user. So, it’s better to maintain the “detailedMenu” table for holding menu items with respective of the users. It’s better to maintain one more column for parent/child relation for the menu’s. This column specify’s the which child is correspond to which parent.

2. It’s better to keep the “detailedMenu” table structure as follows:
(it’s only for sample, I am putting only mandatory fields. Remaining things are depend upon your requirement)

DetaildID(it’s unique)
Int
UserID
Int
MenuCode
int

2. Name of the menuitems, link informations are held in the menu table as follows:
(it’s only for sample, I am putting only mandatory fields. Remaining things are depend upon your requirement)
MenuCode (it’s unique)
Int
MenuType(it’s specify’s the parent/child)
Int
MenuName(menuitem which is appear in the application)
Varchar(50)
MenuLink(navigate page name .aspx, .html)
Varchar(80)


So, there is a realation between above tables.


Implementation(coding):
At the time of login to the application, the number of menuItems are find from the “detailedMenu” table on the basis of UserID.
So, collect the appropriate elements from two tables.

Put this collection information into the DataSet for programming.

Take one UserControl and put that user control into the master page:
In the usercontrol page_load write the following code

/* this is the code for Webusercontrol page Load */
protected void Page_Load(object sender, EventArgs e)
{


sqlAdp.Fill(ds, "Menu");
strMenu = GenerateUL(ds);
if (strMenu != null)
{

MenuDiv.InnerHtml = strMenu;
string JavaScript = "";
Page.RegisterStartupScript("js", JavaScript);
}
else
{
StringBuilder strError = new StringBuilder();
strError.Append("");
strError.Append("!!! Menu Could not be generated

");
strError.Append("You don’t have proper Menu Righs");
strError.Append("Please kindly contact to Administration if this error prevails");
MenuDiv.InnerHtml = strError.ToString();
}




}

private string GenerateUL(DataSet ds)
{
StringBuilder strMenu = new StringBuilder("");
return strMenu.ToString();
}


It’s give proper idea to build the MenuItems by Server coding. No need to write much things at client side script. I hope this article is helping for you. I happy to accept suggestions/comments/corrections. I will be reached at subhas.soft@gmail.com.

Next time meet with better scenario. Happy Coding.

Cheers,
Subhas