Sunday, March 29, 2015

Highlight search text using Java Script

How to  highlight your search results instantly from your web page. As its more like searching an element or a phrase of word in your page or selected section. We will use Java Script to do this. Lets do how to do this.

Open any of those text editor you used. Write down your code or html to design your text portion in your page. Then come to the Java Script portion. Its playing the main role along with css.

As text I am putting the content of Kolkata, my city. You put your content or fetch back from your database. So you can test your application is running successfully or not.

<div id="search" name="search">
    <input name="query" id="query" type="text" size="30" maxlength="30" />
    <input name="searchit" type="button" value="Search" onclick="highlightSearch()" />
    <div id="searchtext">
                Kolkata /koʊlˈkɑːtɑː/, formerly Calcutta /kælˈkʌtə/, is the capital of    the Indian state of West Bengal.
                Located on the east bank of the Hooghly river, it is the principal commercial, cultural,
                and educational centre of East India, while the Port of Kolkata is India's oldest operating
                port as well as its sole major riverine port. As of 2011, the city had 4.5 million residents;
                the urban agglomeration, which comprises the city and its suburbs, was home to approximately
                14.1 million, making it the third-most populous metropolitan area in India. As of 2008,
                its economic output as measured by gross domestic product ranked third among South Asian cities, behind Mumbai and Delhi.


Now write down this java script function to do the trick.

function highlightSearch() {
      var text = document.getElementById("query").value;
      var query = new RegExp("(\\b" + text + "\\b)", "gim");
      var e = document.getElementById("searchtext").innerHTML;
      var enew = e.replace(/(<span>|<\/span>)/igm, "");
      document.getElementById("searchtext").innerHTML = enew;
      var newe = enew.replace(query, "<span>$1</span>");
      document.getElementById("searchtext").innerHTML = newe;

Now you must remember the importance of css to modify the text. So here is the css part to make the text highlighted.

#searchtext span {
    background-color: #FF9;
    color: #555;

div {
  padding: 10px;

Now run your program and test it. Enjoy..
Download the full source code here.

Friday, February 13, 2015

User Control in ASP.NET C#


In this post I will show you how to add UserControl to your .NET web application or web site with the back end in C#. Its a very basic thing to cover in .NET and I am sure many of you are aware of this. So those are not aware of the UserControl till now they have no need to worry because this article will cover the whole thing about UserControl.

What is the purpose to use UserControl?

Usually we use master page to set a template or something static in every page. Here we will do the same, but in a different way. Here we will add the controls in one page to make it as a whole one. This is the alternate process of master page and some time its better than the master page, because you can separate each section is a page  into a different control and code it as you do. 

Difference between Master page and UserControl

In master page concept you can put all the necessary control like say menu, login or registration, header, footer in one master page and in the slave page you just  inherit those and put the different data in the ContentPlaceHolder as per your requirement. And for that you have to code of all thing within one master page. How about this if you separate the all sections (menu, login or registration, header, footer) and just add as a control (like a button or a label) into your project. This is the UserControl concept. You create control for header, footer, login, register separately, and where ever you need just add the control. One extra thing you have to do is need to add a Register tag at the top of each page, because its a user created control, not an inbuilt one.

So lets see how to create a web page adding the controls. We will create a simple web page  to do this.

Create a new project and add a new web form, add a html table for the structuring the web page. Now add a new folder named control, here all the controls will be stores. 

Here add a new item, add Web User Control named it header.ascx.

Here you can design your header section. I have just add a H1 tag within a anchor tag to redirect it to insex page. If you can want you can code in C# just like another web page. You must remember it has functionality like any other web page, but it can't run alone like the master page. it will act as a section of a page and it does not content any form.


Header Section

Now put the footer section, same as like header section. Now put a demo section which will content code to make you understand better how it works. We will do a simple code to show a pop up box in a UserControl. So add another control in the control folder. 

Add a new asp button on this and on button click add this code.

Response.Write("alert message goes here.");

Now here is the question how to add these into your web page. Here is the solution.
On your web page write down these code at the top of the page after Page tag.

<%@ Register Src="~/Controls/header.ascx" TagPrefix="uc1" TagName="header" %>
<%@ Register Src="~/Controls/footer.ascx" TagPrefix="uc1" TagName="footer" %>
<%@ Register Src="~/Controls/demo.ascx" TagPrefix="uc1" TagName="demo" %>

and where you want to add the controls just put down these controls.

These are your controls, do whatever you want to do with these.

See the file attached for a better experience. Run your project and test your code.

Download full source code here.

Saturday, January 24, 2015

SQL Bulk copy from DataTable using XML

To copy data from DataTable or DataSet to SQL Server we need to use either foreach or for loop. It is OK when the count of rows is reasonable. But if the data is like 1 lakh or 1 core, then it is not possible to round the loop for such that time. Then what to do? A simple and easy way to follow is use XML. I am sure you all are more or less aware of this XML. Its a like the database with tags. Or I better to say its a database. It keeps data into a file with extension of  ".xml".

Our intention to convert the DataTable's data into an XML file and send it to server, where with the help of a stored procedure we will extract data and insert into the database table. So lets come see, how to do this...

First of all create a new database and create a new table, named it as you want. Database table structure will be like this.

Name NVarChar(255) not null
Adderss NVarChar(255) not null
Phone NvarChar(12) not null

OK, now we need to create a new DataTable  and put some data on it. Make sure your column and the database table's column are same.

DataTable dt = new DataTable();

dt.Rows.Add("Arkadeep", "Kolkata", "123456890");
dt.Rows.Add("Saikat", "Chennai", "99999999");

dt.Rows.Add("Sucheta", "Delhi", "9876543210");

Now you have to convert this DataTable into XML. To do this copy and paste the following code after the DataTable section. 

private static string ConvertToXML(DataTable dt)
      DataSet dsBuildSQL = new DataSet();
      StringBuilder sbSQL;
      StringWriter swSQL;
      string XMLformat;
           sbSQL = new StringBuilder();
           swSQL = new StringWriter(sbSQL);
           dsBuildSQL.Merge(dt, true, MissingSchemaAction.AddWithKey);
           dsBuildSQL.Tables[0].TableName = "DataTable";
           foreach (DataColumn col in dsBuildSQL.Tables[0].Columns)
               col.ColumnMapping = MappingType.Attribute;
           dsBuildSQL.WriteXml(swSQL, XmlWriteMode.WriteSchema);
           XMLformat = sbSQL.ToString();
           return XMLformat;
       catch (Exception sysException)
           throw sysException;

Call this method to convert the DataTable to XML. 

String xmlData = ConvertToXML(dt);

Now pass the value to the stored procedure like the following way.

SqlConnection conn = new SqlConnection(WebConfigurationManager.ConnectionStrings["connection"].ToString());
SqlCommand command = new SqlCommand("sp_InsertData '" + xmlData + "'", conn);

Now lets check the stored procedure sp_InsertData.

(@xmlString VARCHAR(MAX))

      DECLARE @xmlHandle INT
      DECLARE @stagingTable TABLE
         [Name]               VARCHAR(50),
         [Address]            VARCHAR(50),
         [Phone]              VARCHAR(50)
      EXEC sp_xml_preparedocument @xmlHandle output, @xmlString 

      INSERT INTO @stagingTable
      SELECT  [Name]    ,
      FROM  OPENXML (@xmlHandle, '/DataTable',1)
                        WITH ([Name]            varchar(50)       '@Name',
                                [Address]       varchar(50)       '@Address',
                                [Phone]         varchar(50)       '@Phone'

      INSERT INTO SampleData ([Name], [Address], [Phone])
            (SELECT [Name] , [Address],[Phone]FROM @stagingTable)
      EXEC sp_xml_removedocument @xmlHandle

Now run your project and after run this check your database table whether data has been inserted or not...

Thursday, January 15, 2015

Generate Genealogy view in ASP.NET C# using Google Organizational Chart

Previously I  have show you how to create a genealogy view of a family or a tree view in ASP.NET using C#. You can go through that link here.  But that process was some kind of orthodox concept to show the data, because we have used a primary structure of HTML table and put a huge code of all the buttons, labels and images present in the HTML table.

But in this article I will show you how to create a genealogy view of data coming from database with coding of just 20-25 lines. We will use Google organizer chart to create the tree view. Our only motive is to generate the parent and position (left & right) wise data presentation by fetching it from database.

So lets come to the database part first. I cut all other thing except name and parent no. If only one child is present it will show direct under the parent(neither in left nor in right) and two children will show to left and right according to their position in database. So you need to be careful to handle these kinds of small but very effective things when you will do yours.

I will first discuss about the Google organizational chart. Lets check how it works first. Here I am just pasting the  code which will generate the tree view. For more visit this link.

function drawChart() {
     var data = new google.visualization.DataTable();
     data.addRows([['Mike',''], ['Jim''Mike'], ['Alice''Mike'],['Bob','Jim'],['Carol''Jim']]);

     var chart = new google.visualization.OrgChart(document.getElementById('chart_div'));
     chart.draw(data, { allowHtml: true });

This code is not similar to the code present in the website. I took only the things that will help me to do the primary things. Others can be added later.

All these codes are basically based on the data. Data containing of Mike, Jim, Alice, Bob etc. So if we can replace it with our value, which is coming from database then our work will be done. So first lets fetch the data from database and form a string like does here.

string s = "";
DataTable table = new DataTable();
table.Columns.Add("name", typeof(string));
table.Columns.Add("parent", typeof(string));
table.Rows.Add("Mike", "");
table.Rows.Add("Jim", "Mike");
table.Rows.Add("Alice", "Mike");
table.Rows.Add("Carol", "Jim");
for (int i = 0; i < table.Rows.Count; i++)
     s = s + "['"+table.Rows[i][0].ToString()+"','"+table.Rows[i][1].ToString()+"'],";
s = s.TrimEnd(',');

I only took a DataTable and bind it some dummy data. You need to bind it with SQL to fetch it from DB.

Now our string "s" is ready to launch as a bunch of data to Google organizational chart. Now how to add this data to javascript fucntion to call it or pass it.

The way I did it here, call a javascript fucntion which is created within code behind. Lets see how I did this.

String csname1 = "PopupScript";
Type cstype = this.GetType();
ClientScriptManager cs = Page.ClientScript;
if (!cs.IsStartupScriptRegistered(cstype, csname1))
     StringBuilder cstext1 = new StringBuilder();
     cstext1.Append("function drawChart() {");
     cstext1.Append("var data = new google.visualization.DataTable();");
     cstext1.Append("data.addColumn('string', 'Name'); data.addColumn('string', 'Manager');");
     cstext1.Append("var chart = new google.visualization.OrgChart(document.getElementById('chart_div'));");
     cstext1.Append("chart.draw(data, { allowHtml: true });");

      cs.RegisterStartupScript(cstype, csname1, cstext1.ToString());

And one more thing don't forget to add a "chart_div" in the ASPX page. Its the thing which is holding all the tree view.

Output :

Download the whole source code here

Monday, December 22, 2014

How to upload a file in MVC 4.0 Razor

In this tutorial I will show you how to upload a files in ASP.NET MVC 4.0. So how to do this?? Lets get start. Create a new MVC 4.0 application and add a new controller, name it as HomeController. We will use Index ActionMethod to write the code to upload the file.

We need two ActionMethod named Index, one is for HttpGet and another for HttpPost. Within the HttpGet ActionMethod we don't need to write anything.

Lets create the View first. To create the View right click on the ActionMethod Index and click on the Add View  option.

In the View write down the code.

    ViewBag.Title = "Upload file";

<h2>Upload File</h2>
<h3 style="color: green">@ViewBag.Message</h3>
@using (Html.BeginForm("Index", "Home", FormMethod.Post
            , new { enctype = "multipart/form-data" }))

    <input type="file" id="fileToUpload" name="file" />
    <span class="field-validation-error" id="spanfile"></span>

    <input type="submit" id="btnSubmit" value="Upload" />

Here we have taken a simple HTML file up loader and a submit button. Within the form we are calling the ActionMethod Index, which is present in HomeController. A ValidationSummary to show all validation message.

Now get back to the ActionMethod. Within the Index ActionMethod (HttpPost) write down the code.

public ActionResult Index(HttpPostedFileBase file)
      if (ModelState.IsValid)
           if (file == null)
              ModelState.AddModelError("File""Please Upload Your file");
           else if (file.ContentLength > 0)
              int MaxContentLength = 1024 * 1024 * 4; //Size = 4 MB
              string[] AllowedFileExtensions = new string[] { ".jpg"".gif"".png"".pdf" };
           if (!AllowedFileExtensions.Contains
                 ModelState.AddModelError("File""Please file of type: " + string.Join(", ", AllowedFileExtensions));
           else if (file.ContentLength > MaxContentLength)
                 ModelState.AddModelError("File""Your file is too large, maximum allowed size is: " + MaxContentLength + " MB");
                 var fileName = Path.GetFileName(file.FileName);
                 var path = Path.Combine(Server.MapPath("~/Upload"), fileName);
                 ViewBag.Message = "File uploaded successfully. File path :   ~/Upload/"+fileName;
     return View();

Before run this project don't forget to create a Upload folder within root directory, otherwise you will get an error.

HttpPostedFileBase file getting the file which you are uploading.

file.ContentLength : Size of the file
file.FileName : file name with extension

Now run your project and enjoying your uploading.

Download the full source code here.