Showing posts with label c#. Show all posts
Showing posts with label c#. Show all posts

Saturday, May 8, 2010

VS 2010 –Some amazing features

For the past some months I'm looking into what’s there will be with Visual Studio 2010.At its beta releases VS 2010 faced a series of problems(Installer crash,Add reference empty in Silverlight project, Smart device project creation problem). Now they fixed most of the issues in the latest releases.I’m describing some of the cool new features with 2010 IDE.

View Call Hierarchy

By this we can see the hierarchical list of function usage.We can see the parameter details and function location.

Untitled11

Data & Schema Comparer

Previously most of us struggle a lot in comparing data's and schemas in and between databases. Also there was some third party tools Sql tool belt from Redgate, its so expensive.In Visual Studio 2010(I'm using vs 2010 ultimate) there is a new schema and data comparison tool.You can select two different databases and run the comparison task.

DMenu  Capture

Dcompare

Architectural and UML Model Explorer

This is quite useful for functional & architect.In the tool bat Select->Architecture->Windows->Architecture Explorer.Dig into it and do more!!!

archmen Arch1

Debugging With IntelliTrace

Visual Studio 2010 had a vast changes in the debugging sections.One of the cool feature is “IntelliTrace” which will more helpful while debugging the application as it provide a detailed picture of the debug info , you can record debug information and we can later look up into the previous debug info.

intellitrace

With IntelliTrace, you can actually see events that occurred in the past and the context in which they occurred. This reduces the number of restarts that are required to debug your application and the possibility that an error will fail to reproduce when you rerun the application.

Also we can pin-in values to variables  while debugging!!!

Read more in MSDN Click here

Read more about debugging information on ScottGu Blog Click here

Also VS 2010 newly added

  • Optional & Named parameters(like old vb 6)
  • Insert Code Snippet for JS,Html
  • We drag windows outside the model-Multi monitor support(Like we drag a tab to another window in Firefox&chrome)

Drag

And many more…that i will update in this chain.

Go and Rocks with VS 2010!!!!!!!!!!!!!!!

Converting “Var” to Dataset

After a long time back i’m into my blog…Didn’t get enough time to sit with the things..

In some cases we need to convert the anonymous datatype var to a dataset or datatable.we cant do it directly as so.Here is a

Simple method that will return the var or List item to dataset


public static DataSet ToDataSet(List list)
{

Type type = typeof(T);
DataSet ds = new DataSet("Company");
DataTable dt = new DataTable("Contacts");
ds.Tables.Add(dt);
//Dynamically adding columns to data table
foreach (var propInfo in type.GetProperties())
{
dt.Columns.Add(propInfo.Name, propInfo.PropertyType);

//You can add columns manually also here
if (propInfo.Name == "ID")
{
dt.Columns.Add("Photo");
}
}
foreach (T item in list)
{
DataRow dr = dt.NewRow();
foreach (var propInfo in type.GetProperties())
{
dr[propInfo.Name] = propInfo.GetValue(item, null);
}
dt.Rows.Add(dr);
}
return ds;
}

Wednesday, February 17, 2010

Xml Manipulation Using Linq-Some basic lessons

The “functional construction” feature of Linq to Xml provides great usability in creating and modifying xml documents. XDocument object is used for the xml declarations. The XElement class constructor are used in resolving the xml entities.

string path = Server.MapPath(@"/Linq2XML/DataStore.xml");
XDocument xd = XDocument.Load(path);
var result = from c in xd.Elements("DataStore").Elements("Table") select new { oid = (string)c.Element("oid"), BuildName = (string)c.Element("BuildName"), Appserver = (string)c.Element("Appserver"), DBServerName = (string)c.Element("DBServerName"), dbname = (string)c.Element("DBName"), comments = (string)c.Element("comments") };

This will load the Xml file to your XDocument object and perform a linq operation to get the xml elements. We can use Descendants to return the filtered collection of matching XName elements.

For modifying the elements we can use the SetElementValue Method of XElement, that will set, add and remove child elements.

public void ModifyEnvironments(string oid,string buildName,string appServer,string dbServer,string dbName,string comments )
{
XDocument objdoc = XDocument.Load(HttpContext.Current.Server.MapPath(@"\Envdetails\DataStore.xml"));
var items = from item in objdoc.Descendants("Table")
where item.Element("oid").Value == oid
select item;
foreach (XElement itemElement in items)
{
itemElement.SetElementValue("BuildName", buildName);
itemElement.SetElementValue("Appserver", appServer);
itemElement.SetElementValue("DBServerName", dbServer);
itemElement.SetElementValue("DBName", dbName);
itemElement.SetElementValue("comments", comments);
}
objdoc.Save(HttpContext.Current.Server.MapPath(@"\Linq2XML\DataStore.xml"));
}

We can use Remove() to delete an element.Also can use RemoveContent method that will make an empty element tag()

public void DeleteEnvironment(string oid)

{
XDocument objdoc = XDocument.Load(HttpContext.Current.Server.MapPath(@"\Linq2XML\DataStore.xml"));
var items = (from item in objdoc.Descendants(@"Table")
where item.Element("oid").Value == oid
select item).FirstOrDefault();
items.Remove();
objdoc.Save(HttpContext.Current.Server.MapPath(@"\Envdetails\DataStore.xml"));
}

For adding new XElement we can use the Add() method

public void AddEnvironments(string buildName, string appServer, string dbServer, string dbName, string comments)
{
XDocument objdoc = XDocument.Load(HttpContext.Current.Server.MapPath(@"\Envdetails\DataStore.xml"));
XElement xe = objdoc.Descendants("DataStore").Last();
xe.Add(new XElement("Table", new XElement("oid", GetMaxOid()), new XElement("BuildName", buildName)
,new XElement("Appserver",appServer),new XElement("DBServerName",dbServer),new XElement("DBName",dbName),
new XElement("comments",comments)));
objdoc.Save(HttpContext.Current.Server.MapPath(@"\Linq2XML\DataStore.xml"));
}

Please find the sample XML file (“DataStore.xml”)here

Tuesday, February 2, 2010

Location and Sensor Platform in Windows 7

Cool , there are some nice sets of Location and Sensor API associated with windows 7.As now computers are portable like cellular phone the necessity of GPS enabled application are very useful. If your laptop doesn’t have any sensors installed it will take the default location provided by the user. This Location and sensor API open wide variety of applications.

References
http://msdn.microsoft.com/en-us/library/dd318936(VS.85).aspx
http://msdn.microsoft.com/en-us/library/dd464636(VS.85).aspx


Learn how to read the GPS co-ordinates, See this article.
http://blogs.msdn.com/coding4fun/archive/2006/10/31/912287.aspx
Even More..

Thursday, January 14, 2010

Func<T,TResults> – Flexible delegate to create reusable functions

Today while googling i found an interesting feature of delegate Func<T,TResults> ,it allows us to represent a method that can be passed as a parameter without declaring a custom delegate explicitly and the method must have one parameter that is passed to it by value and must return a value.

In the following example we need to explicitly define a new delegate and assign a named method to it.



using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace BlogSamples
{
delegate int ConvertMethod(int _x);
class Program
{
static void Main(string[] args)
{
ConvertMethod objConv = SquareMe;
int val = 5;
//delegate is called
Console.WriteLine(objConv(val));
Console.ReadKey();
}
private static int SquareMe(int myInt)
{
return myInt * myInt;
}
}
}

Without explicitly defining a new delegate it can be simplified as below

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace BlogSamples
{
class Program
{
static void Main(string[] args)
{
Func convertMethod = SquareMe;
int val = 6;
Console.WriteLine(convertMethod(val));
Console.ReadKey();
}
private static int SquareMe(int myInt)
{
return myInt * myInt;
}
}
}


Please see the msdn link for more references.

Wednesday, October 28, 2009

Getting Country List from CultureInfo

We can use CultureInfo to get the list of countries/languages.Today i got a method to list all the countries, even it has some duplicate values that are elimated by a distinct linq query.

public void CountryList()
{
ArrayList cList=new ArrayList();
foreach (CultureInfo ci in CultureInfo.GetCultures(CultureTypes.AllCultures & ~CultureTypes.NeutralCultures))
{
RegionInfo ri = new RegionInfo(ci.LCID);
cList.Add(ri.EnglishName);
}
var countries = cList.ToArray();
var i = (from temp in countries select temp).Distinct().OrderBy(s=>s);
foreach (var item in i)
{
listBox1.Items.Add(item.ToString());
}
}

Also an interesting thing with Textinfo to make the first letter of a string/sentence to capital.(Little bit tricky :-))

string temp = "MULTIDIMENSIONAL NEWTON RAPHSON";
string firstSmall = CultureInfo.CurrentCulture.TextInfo.ToTitleCase(temp.ToLower()); //I made a trick to make the string to lower case
MessageBox.Show(firstSmall.ToString());

Output :Multidimensional Newton Raphson

Tuesday, October 27, 2009

Workstation & Server Garbage Collector

There are two types of garbage collector,the workstation GC and Server GC.Workstation is the default on client versions of windows,but server is much faster on multicore machines.The Server GC utilize more memory
  

<configuration> <runtime>
<gcServer enabled="true"/>
</runtime>
</configuration>



Note:All sample code is provided is for illustrative purposes only.These examples have not been thoroughly tested under all conditions.Myself, therefore, cannot guarantee or imply reliability,serviceability, or function of these programs.

Monday, October 12, 2009

Getting all reference of an Assembly

To get the assembly reference in a ASP.NET web application i found a recursive method that will read from the csproject file.
Import these namespace also
using
System.Xml.Linq;
 
public void LoadAssembly(string path)
{
int result=0;
XNamespace msbuild = "http://schemas.microsoft.com/developer/msbuild/2003";
XDocument projDefinition = XDocument.Load(path);
IEnumerable<string> references = projDefinition.Element(msbuild + "Project")
.Elements(msbuild +
"ItemGroup")
.Elements(msbuild +
"Reference")
.Elements(msbuild +
"Name")
.Select(refElem => refElem.Value);
foreach (string reference in references)
{

richTextBox1.AppendText(reference);

richTextBox1.AppendText(Environment.NewLine);

        }
}
 
If you need to loop through the IEnumerable iterator to find out other xml nodes u can use the following
 
using (IEnumerator<string> enumerator = references.GetEnumerator())
{
while (enumerator.MoveNext())
result++;
}
if (result == 0)
{
//Do ur xml operations

}

Saturday, May 2, 2009

Converting Text to RSS Feeds


Today i used created a good method to parse a raw text document to rss feeds using Generic Handlers.Please refer the code below.
<%@ WebHandler Language="C#" Class="Cricket" %>

using System;
using System.Web;
using System.Net;
using System.Text;
using System.Linq;
public class Cricket : IHttpHandler {

public void ProcessRequest(HttpContext context)
{
StringBuilder sb=new StringBuilder();
context.Response.ContentType = "text/xml";
sb.Append(@"


Score
http://renjucool.co.nr
Get latest score
(c) 2008 renjucool.co.nr

");
sb.Append("");
sb.Append("Score of "+DateTime.Now.ToShortDateString()+"");
sb.Append("Score of " + GetScore() + "");
sb.Append("Score of " + GetScore() + "");
sb.Append("Score of " + DateTime.Now.ToString("ddd, MMM yyyy hh:mm:ss tt") + "");
sb.Append("
");
sb.Append(@"


");
context.Response.Write(sb.ToString());
}
public string GetScore()
{
string ret = "";
WebClient myClient = new WebClient();
String data=Encoding.ASCII.GetString(myClient.DownloadData
("http://renju.sparkonnet.com/files/raw.tx"));

foreach (string s in (from s in data.Split((char)10) select GetValue(s)))
{
ret += " "+s;
}
return ret;
}
public string GetValue(string inp)
{
if (inp.IndexOf("=") == -1) return inp;
return inp.Substring(inp.IndexOf("=") + 1);
}

public bool IsReusable {
get {
return false;
}
}

}
Please refer the screen shot as the code contains html tags

Sunday, January 25, 2009

Upload T-SQL and execute at your hosting provider using an ASP.NET page

With this approach, you can use the Database Publishing Wizard to generate a T-SQL file from your local database. Then, you can upload the script to your hosting provider, and use the sample ASP.NET page provided to execute the code below.

This approach is useful in the following circumstances:

* Your hosting provider has not deployed the Database Publishing Services, enabling simple publishing of your SQL Server database
* Your hosting provider does not have a T-SQL script execution window or the T-SQL script generated by the Database Publishing Wizard is too large to paste into the T-SQL script execution window

Here is the code, just copy it then paste to your RunSQL.aspx


<%@ Page Language="C#" AutoEventWireup="true" %>
<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Data.SqlClient" %>
<%@ Import Namespace="System.IO" %>
<%@ Import Namespace="System.Net" %>
<%
// **************************************************************************
// Update these variables here
// **************************************************************************
// Url of the T-SQL file you want to run

string fileUrl = @"http://<>/<>.sql";

// Connection string to the server you want to execute against
string connectionString = @"<>";

// Timeout of batches (in seconds)
int timeout = 600;
%>





Executing T-SQL






<%
SqlConnection conn = null;
try
{
this.Response.Write(String.Format("Opening url {0}
", fileUrl));

// read file
WebRequest request = WebRequest.Create(fileUrl);
using (StreamReader sr = new StreamReader(request.GetResponse().GetResponseStream()))
{
this.Response.Write("Connecting to SQL Server database...
");

// Create new connection to database
conn = new SqlConnection(connectionString);

conn.Open();

while (!sr.EndOfStream)
{
StringBuilder sb = new StringBuilder();
SqlCommand cmd = conn.CreateCommand();

while (!sr.EndOfStream)
{
string s = sr.ReadLine();
if (s != null && s.ToUpper().Trim().Equals("GO"))
{
break;
}

sb.AppendLine(s);
}

// Execute T-SQL against the target database
cmd.CommandText = sb.ToString();
cmd.CommandTimeout = timeout;

cmd.ExecuteNonQuery();
}

}
this.Response.Write("T-SQL file executed successfully");
}
catch (Exception ex)
{
this.Response.Write(String.Format("An error occured: {0}", ex.ToString()));
}
finally
{
// Close out the connection
//
if (conn != null)
{
try
{
conn.Close();
conn.Dispose();
}
catch (Exception e)
{
this.Response.Write(String.Format(@"Could not close the connection. Error was {0}", e.ToString()));
}
}
}
%>



Below are the instructions to use this approach:

1. Run the Database Publishing Wizard to generate a T-SQL script file for your local database
2. Using FTP (or another approach if applicable), upload this T-SQL file to your hosting account
3. Download the sample ASP.NET page by clicking on this link: RunSQL.aspx
4. Edit the ASPX page and change the values of the variables fileUrl and connectionString as follows:
1. fileUrl should be the url of the T-SQL file you uploaded. For example if your domain name is www.mydomain.Com, then the url would be http://www.mydomain.com/File.Sql
2. connectionString should be the connection string of your hosted SQL Server database
5. Upload the ASPX page to your hosting account
6. Point your web browser to the ASPX page you uploaded. When this page has completed loading, your database should now be populated in the remote SQL Server database
7. Important: Delete the T-SQL file and ASPX page in your hosting account. This will prevent others from reading your data or tampering with your database.

Saturday, October 11, 2008

Parsing/Looping through Treeview using Interface

private static void parseNode(TreeNode tn)
{

IEnumerator ie = tn.ChildNodes.GetEnumerator();

string parentnode = "";

parentnode = tn.Text;

while (ie.MoveNext())
{
TreeNode ctn = (TreeNode) ie.Current;

if (ctn.ChildNodes.Count == 0)
{
sr.Write(ctn.Text);
}
else
{
sr.Write("<" + ctn.Text + ">");
}
if (ctn.ChildNodes.Count > 0)
{
parseNode(ctn);
}
}

sr.Write("");
sr.WriteLine("");

}

Saving the treeview to XML

public static void exportToXml(TreeView tv, string filename)
{
sr = new StreamWriter(filename, false, System.Text.Encoding.UTF8);
sr.WriteLine("");
if (tv.Nodes.Count > 0)
{
IEnumerator ie = tv.Nodes.GetEnumerator();
ie.Reset();
if (ie.MoveNext())
{
TreeNode tn = (TreeNode)ie.Current;
sr.WriteLine("<" + tn.Text + ">");
parseNode(tn);
}
}

sr.Close();
}

Wednesday, September 10, 2008

Parsing Emails using Regular Expressions

Using Regular Expressions

Using regular expression we can simply parse valid emails from the given contents.this is mainly used to extract actual email addressess from the to,from,cc and bcc fields.

Implementation(c#)

First import using System.Text.RegularExpressions;

the code is as below

private string ParseEmails(string text)
{
const string emailPattern = @"\w+@\w+\.\w+((\.\w+)*)?";

MatchCollection emails = Regex.Matches(text, emailPattern, RegexOptions.IgnoreCase);
StringBuilder emailString = new StringBuilder();
foreach (Match email in emails)
{
if (emailString.Length ==0)
{
emailString.Append(email.Value);
}
else
{
emailString.Append("," + email.Value);
}
}

return emailString.ToString();
}

Monday, September 8, 2008

Word Break for Gridview/DataGrid

Sometime we are facing problems with gridview in inserting word breaks to format the grid.ie if we are inserting a coloumn that is having more length so the grid layout is changed.

"wbr" Tag is used for that.That should be placed in angle bracket("<>").I'm representing it as wbr in the code given below as it is an html tag.

public static string WordBreak(String inString, int length)
{
StringBuilder stb = new StringBuilder();
String ret = "";
int pos;
if (length == 0)
length = 10;
while ((true))
{
if (inString.Length <= length)
{
ret += inString;
break;
}
pos = inString.IndexOf(" ");
if (pos != -1)
{
if (pos > length - 1)
{
pos = length;
ret += inString.Substring(0, pos + 1) + "wbr";
}
else
{
ret += inString.Substring(0, pos + 1);
}
inString = inString.Substring(pos + 1);
}
else
{
ret += inString.Substring(0, length) + "wbr";
inString = inString.Substring(length);
}
}
if (ret.Length > 50)
{
string temp = ret.Substring(0, 50);
stb.Append(temp);
stb.Append("....");
ret = stb.ToString();
}
return ret;
}


Regards
www.renjucool.com

Friday, September 5, 2008

Bubble Sort Algorithm in C#

static int[] bubbleSort(int[] numbers, int array_size)
{
int i, j, temp;

for (i = (array_size - 1); i >= 0; i--)
{
for (j = 1; j <= i; j++)
{
if (numbers[j - 1] > numbers[j])
{
temp = numbers[j - 1];
numbers[j - 1] = numbers[j];
numbers[j] = temp;
}
}
}
return numbers;
}

Returning multiple values from a Function

public static int add(int a, int b, ref int c)
{
c = a + 2;
return a + b;
}

We can use out and ref,can be called as shown below

int e = add(2, 3, ref d);

Thursday, September 4, 2008

Exporting DataTable to Excel

private void ExportToExcel(DataTable dtIn)
{

DataTable dt = dtIn;
if (dt != null)
{
Response.Clear();
Response.AddHeader("Content-Disposition", "attachment;filename=FileName.xls");
Response.Charset = "";
Response.ContentType = "application/vnd.ms-excel";
string tab = "";
foreach (DataColumn dc in dt.Columns)
{
Response.Write(tab + dc.ColumnName);
tab = "\t";
}
Response.Write("\n");
int i;
foreach (DataRow dr in dt.Rows)
{
tab = "";
for (i = 0; i < dt.Columns.Count; i++)
{
Response.Write(tab + dr[i].ToString());
tab = "\t";
}
Response.Write("\n");
}
Response.End();
}

}

Dynamic DataGrid Templates

public void DynamicGrid()
{
DataGrid dg = new DataGrid();
DataSet ds = objws.getempinactivity(1, 8, DateTime.Now.AddDays(-50), DateTime.Now);
DataTable dt = ds.Tables[0];

for (int i = 0; i <= dt.Columns.Count - 1; i++)
{
TemplateColumn templateColumn = new TemplateColumn();
string columnName = dt.Columns[i].ColumnName;
templateColumn.HeaderTemplate = new DataGridTemplate(ListItemType.Header, columnName);
for (int j = 0; j <= dt.Rows.Count - 1; j++)
{
string value = dt.Rows[j][i].ToString();
templateColumn.ItemTemplate = new DataGridTemplate(ListItemType.Item, value);

}
DataGrid1.Columns.Add(templateColumn);
}
DataGrid1.DataSource = ds;
DataGrid1.DataBind();
}



using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

///
/// RENJU.R
/// Summary description for DataGridTemplate
///
public class DataGridTemplate : ITemplate
{
ListItemType templateType;
string columnName;
public DataGridTemplate(ListItemType type, string colname)
{
//
// TODO: Add constructor logic here
//
templateType = type;
columnName = colname;

}
public void InstantiateIn(System.Web.UI.Control container)
{
Literal lc = new Literal();
switch (templateType)
{
case ListItemType.Header:
lc.Text = "" + columnName + "";
container.Controls.Add(lc);
break;
case ListItemType.Item:
lc.Text = columnName;
container.Controls.Add(lc);
break;
case ListItemType.EditItem:
TextBox tb = new TextBox();
tb.Text = "";
container.Controls.Add(tb);
break;
case ListItemType.Footer:
lc.Text = "" + columnName + "";
container.Controls.Add(lc);
break;
}
}
//public void InstantiateIn(Control container)
//{
// LiteralControl l = new LiteralControl();
// l.DataBinding += new EventHandler(this.OnDataBinding);
// container.Controls.Add(l);
//}

//public void OnDataBinding(object sender, EventArgs e)
//{
// LiteralControl l = (LiteralControl)sender;
// DataGridItem container = (DataGridItem)l.NamingContainer;
// l.Text = ((DataRowView)container.DataItem)[colname].ToString();
//}
}
Poste

Asp.Net Message Box

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Collections;
using System.Text;

///
/// Summary description for MessageBox
///
/// Done by RENJU.R
/// You are licenced to distribute the code
/// http://www.renjucool.co.nr

public class MessageBox
{

private static Hashtable m_executingPages = new Hashtable();
private MessageBox() { }
public static void Show(string sMessage)
{
if (!m_executingPages.Contains(HttpContext.Current.Handler))
{
Page executingPage = HttpContext.Current.Handler as Page;
if (executingPage != null)
{
Queue messageQueue = new Queue();
messageQueue.Enqueue(sMessage);
m_executingPages.Add(HttpContext.Current.Handler, messageQueue);
executingPage.Unload += new EventHandler(ExecutingPage_Unload);
}
}
else
{
Queue queue = (Queue)m_executingPages[HttpContext.Current.Handler];
queue.Enqueue(sMessage);
}
}

private static void ExecutingPage_Unload(object sender, EventArgs e)
{
Queue queue = (Queue)m_executingPages[HttpContext.Current.Handler];
if (queue != null)
{
StringBuilder sb = new StringBuilder();
int iMsgCount = queue.Count;
sb.Append("");
m_executingPages.Remove(HttpContext.Current.Handler);
HttpContext.Current.Response.Write(sb.ToString());

}
}

}

ASP.NET Site Search

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
using System.Data.OleDb;
using System.Text;
using System.IO;
using System.Text.RegularExpressions;
//Programmed by Renju.R
//Refer Microsoft Indexing Service
public partial class _Default : System.Web.UI.Page
{
public static DataView tempds = new DataView();
public static int resultCount = 0;
public DataRow drIndexed;
public DataTable dtPub = new DataTable();
public DataSet dsPub = new DataSet();
public DataRow dr2;
public DataTable dt2 = new DataTable();
public DataSet ds2 = new DataSet();
public DataSet ds = new DataSet();
public DataRow dr;
public DataTable dt = new DataTable();
public static StringBuilder stb = new StringBuilder();
// public static OleDbConnection oldbCon = new OleDbConnection("Provider=MSIDXS.1;Integrated Security .='';Data Source=Reader");
public static OleDbConnection oldbCon = new OleDbConnection("Provider=MSIDXS.1;");
public int count;
protected void Page_Load(object sender, EventArgs e)
{
}
public void FillResult()
{
//ds.Merge(dtTemp, false, MissingSchemaAction.Add);
//ds.Merge(ds2.Tables[0]);
//ds.Tables[0].Merge(ds2.Tables[0]);
//tempds = ds.Tables[0].Copy().DefaultView;
MergeSearch();
Searchfill();
}
protected void Button1_Click(object sender, EventArgs e)
{
string searchText = TextBox1.Text.ToString();
//OleDbCommand cmd = new OleDbCommand("select doctitle, filename, Path ,Attrib, rank, characterization from scope() where FREETEXT('" + searchText + "') and filename <> 'Default.aspx' order by rank desc", oldbCon);
OleDbCommand cmd = new OleDbCommand("select doctitle, filename, Path ,Attrib, rank, characterization from saravanan.Reader..scope() where FREETEXT('" + searchText + "') and filename <> 'Default.aspx' order by rank desc", oldbCon);
cmd.CommandType = CommandType.Text;
if (oldbCon.State == ConnectionState.Closed)
{
oldbCon.Open();
}
OleDbDataAdapter da = new OleDbDataAdapter(cmd);
da.Fill(ds);
resultCount = ds.Tables[0].Rows.Count;
ds2.Tables.Add(dt2);
dt2.Columns.Add("new");
/////
//ds.Tables.Add(dt);
//dt.Columns.Add("search");
////
dsPub.Tables.Add(dtPub);
dtPub.Columns.Add("text");
foreach (DataRow drTemp in ds.Tables[0].Rows)
{
ReadDocuments((string)drTemp["path"]);
}
FillResult();
}
void Searchfill()
{
DataList1.DataSource = ds.Tables[0].DefaultView;
DataList1.DataBind();
}
public DataSet MergeSearch()
{
ds.Tables[0].Columns.Add("search");
int cnt = 0;
// ds.AcceptChanges();
//int mCount = ds2.Tables[0].Rows.Count;
foreach (DataRow drLoop in ds2.Tables[0].Rows)
{
DataRow drTest= ds.Tables[0].Rows[cnt];
drTest["search"] = drLoop["new"];
//dt.Rows.Add(drTest);
// ds.Tables[0].Rows.Add(drTest);
cnt++;
}
return ds;
}
public DataSet MergedValues(string str)
{
DataRow dr5 = ds2.Tables[0].NewRow();
dr5["new"] = (string)str;
dt2.Rows.Add(dr5);
return ds2;
}
public DataSet SearchResult(string text)
{
DataRow drResult = dsPub.Tables[0].NewRow();
drResult["text"] = (string)text;
CreateExcerpt((string)text, TextBox1.Text.ToString(),ds);
dtPub.Rows.Add(drResult);
return dsPub;
}
private string parseHtml(string html)
{
string temp = Regex.Replace(html, "<[^>]*>", "");
return temp.Replace(" ", " ");
}
public string CreateExcerpt(string source, string keyword,DataSet ds)
{
count = 0;
string excerpt = string.Empty;
int charsBeforeAndAfter = 100;
int index = source.IndexOf(keyword, StringComparison.CurrentCultureIgnoreCase);
if (index >= 0)
{
int excerptStartIndex = 0;
int excerptEndIndex = source.Length - 1;
if (index > (charsBeforeAndAfter - 1))
excerptStartIndex = index - charsBeforeAndAfter;
if ((index + keyword.Length + charsBeforeAndAfter) < (source.Length - 1))
excerptEndIndex = index + keyword.Length + charsBeforeAndAfter;
excerpt = source.Substring(excerptStartIndex, excerptEndIndex - excerptStartIndex + 1);
index = excerpt.IndexOf(keyword, StringComparison.CurrentCultureIgnoreCase);
excerpt = excerpt.Insert(index + keyword.Length, "");
excerpt = excerpt.Insert(index, "");
excerpt = string.Format("...{0}...", excerpt);
foreach (DataRow dr in ds.Tables[0].Rows)
{
if(count ==0)
MergedValues(excerpt);
count++;
}
}

//stb.Append(excerpt.ToString());
//stb.Append("
");
//stb.Append("
");
return excerpt;
}
public void ReadDocuments(string docPath)
{
FileStream fs = File.OpenRead(docPath);
string dumptext;
using(StreamReader sr = new StreamReader(docPath, System.Text.Encoding.Default))
{
dumptext = parseHtml(sr.ReadToEnd());
}
SearchResult((string)dumptext);


}
}