Thursday, July 31, 2014

Genealogy View(family tree) in ASP.NET C# with database

In my previous post I shown how to find no of nodes in left and right of a binary tree. Now in this article I will show you how to design the binary tree in ASP.NET  C#. We had retrieve the data from database in the previous post. I remain the database structure same in this example as previous.

Database structure :

-------------------------------------------------------
Id(int) | Parent_Id (int) | Placement (NVarChar(10))
-------------------------------------------------------
1          0                        -
2          1                        Left
3          1                        Right
4          2                        Left
5          2                        Right
-------------------------------------------------------


CREATE TABLE [dbo].[tblBinaryUsers](
    [tid_no] [nvarchar](50) NULL,
    [placement] [nchar](10) NULL,
    [parent_no] [nvarchar](50) NULL,
    [First_name] [nvarchar](50) NULL,
    [enroll_time] [nvarchar](50) NULL
)  


And insert into the table 

INSERT [dbo].[tblBinaryUsers] ([tid_no], [placement], [parent_no], [First_name], [enroll_time]) VALUES (N'100001', N'', NULL, N'Arkadeep De', N'6/7/2014')

INSERT [dbo].[tblBinaryUsers] ([tid_no], [placement], [parent_no], [First_name], [enroll_time]) VALUES (N'100002', N'Left', N'100001', N'Pradeep Das', N'8/7/2014')


INSERT [dbo].[tblBinaryUsers] ([tid_no], [placement], [parent_no], [First_name], [enroll_time]) VALUES (N'100003', N'Right', N'100001', N'Mekesh Nayak', N'9/7/2014')


I added two more fields with this structure. First_Name (nvarchar(255)) and Enroll_Time  (nvarchar(20)). 

First decide how many levels you want to show in the binary tree. Then design according to that Laval. Here I have done with 4 levels. 

So design the html first and then write the coding. I also added a search facility in this project to find the ID with a DropDownList. 
 Your design will be some thing like this.

 
As the code is little bit long I am not giving these here. But don't worry here is the link where you can download the full source code.

Your output will be like this.
Download the full source code here.



Prevent back button click after Logout the session in ASP.NET C#

Some time its happen after logging out when you are clicking on the back button its redirect to the previous page which one should open if the browser is holding the session. To prevent this a simple solution I found. Three lines of code that can solve your problem in a minute.

Code:

protected void Page_Load(object sender, EventArgs e)
{
      /* Starts here */
      Response.Cache.SetCacheability(HttpCacheability.NoCache);
      Response.Cache.SetExpires(DateTime.Now.AddDays(-1));
      Response.Cache.SetNoStore();
      /* Ends here */

      if (Session["User"] == null)
           Response.Redirect("login.aspx");
}

Copy the code and paste into your project and test it. It will redirect to your login page. Enjoy...

How to find no of Sundays in a month in ASP.NET C#

Today I was asked how to find no of Sundays in a month by one of my colleague. To make him happy I found the code and now sharing this with all of you to make you all happy.

A simple code to find the no of Sundays in a months using List.


protected void Page_Load(object sender, EventArgs e)
{
      List<DateTime> dates = new List<DateTime>();
      int year = 2013;
      int month = 1;

      DayOfWeek day = DayOfWeek.Sunday;
      System.Globalization.CultureInfo currentCulture = Thread.CurrentThread.CurrentCulture;
      for (int i = 1; i <= currentCulture.Calendar.GetDaysInMonth(year, month); i++)
      {
            DateTime d = new DateTime(year, month, i);
            if (d.DayOfWeek == day)
            {
                dates.Add(d);
            }
      }

      Response.Write(dates.Count.ToString());
      GridView1.DataSource = dates;
      GridView1.DataBind();
}

And in the ASPX page coding ...


<head runat="server">
    <title>Show Sundays in a month using ASP.NET C#</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:GridView ID="GridView1" runat="server"></asp:GridView>
    </div>
    </form>
</body>

Now the output :



Test the code and before that download the full source code here.

Thursday, July 24, 2014

Count left right node of a MLM(Multi Lavel marketing) binary tree with database in ASP.NET C# - double recursion

Here I will show how to count the number of left right node of a parent node or some node.

Here I am sueing MS. SQL Database and structure is some thing like this.

-------------------------------------------------------
Id(int) | Parent_Id (int) | Placement (NVarChar(10))
-------------------------------------------------------
1          0                        -
2          1                        Left
3          1                        Right
4          2                        Left
5          2                        Right
-------------------------------------------------------


Here I am using double recursion to find the count of left & right node.


Code:
/* Call these from any method */
Data obj = new Data();
pNodeL(LeftNode, "");
pNodeR(RightNode, "");


 /// <summary>
 /// To Count right node
 /// </summary>
 /// <param name="node"></param>
 /// <param name="place"></param>
private void pNodeR(string node, string place)
{
     string sql = "select * from biodata_master where parent_no='" + node + "'";

      DataTable dt = new DataTable();
      dt = obj.SelectData(sql);

      if (dt.Rows.Count == 1)
      {
          Cr = Cr + 1;
      }
      else if (dt.Rows.Count > 0)
      {
           Cr = Cr + 2;
           pNodeR(dt.Select("PLACEMENT='Left'")[0].ItemArray[0].ToString(), "LEFT");
           pNodeR(dt.Select("PLACEMENT='Right'")[0].ItemArray[0].ToString(), "RIGHT");
      }
}

 /// <summary>
 /// To Count left node
 /// </summary>
 /// <param name="node"></param>
 /// <param name="place"></param>
private void pNodeL(string node,string place)
{
      string sql = "select * from biodata_master where parent_no='"+node+"'";

       DataTable dt = new DataTable();
       dt = obj.SelectData(sql);

       if (dt.Rows.Count == 1)
       {
           Cl = Cl + 1;
       }
       else if (dt.Rows.Count > 1)
       {
            Cl = Cl + 2;
            pNodeL(dt.Select("PLACEMENT='Left'")[0].ItemArray[0].ToString(), "LEFT");
            pNodeL(dt.Select("PLACEMENT='Right'")[0].ItemArray[0].ToString(), "RIGHT");
       }
}


/* SelectData Method & Connection string */

SqlConnection con = new SqlConnection(WebConfigurationManager.ConnectionStrings["ConnectionString"].ToString());

public System.Data.DataTable SelectData(string sql)
{
      try
      {
          SqlDataAdapter da = new SqlDataAdapter(sql, con);
          DataTable dt = new DataTable();
          da.Fill(dt);
          return dt;
      }
      catch
      {
          throw;
      }
}
   
It will return your left & right count in the variable Cl and Cr.
Try yours.

Monday, July 21, 2014

Bind two data columns as DataTextField in a DropDownList with SQLDataSource in ASP.NET C#

Hello! To day i will show you how to bind two data fields into one DataTextField or DataValueField in a DropDownList in ASP.NET.

Table structure :

Id             Name           
1        Arkadeep De
2        Pradeep Das
3        Praphul Kumar

Now in your DropDownList your data will show llike

Arkadeep De (1)
Pradeep Das (2)
Praphul Kumar (3)

And in your value will be as your data in Id column ( 1,2,3...).

So how to do that with SQLDataSource !

First create a new project and add a new web form. After that add a new DropDownList and a New SQLDataSource. Bind the DropDownList with the SQLDataSource.

<asp:DropDownList ID="ddlTID_NO" runat="server" DataSourceID="SqlDataSource1"> </asp:DropDownList>

Now in the SelectCommand of the SQLDataSource write down the following query.

SELECT [ID], [NAME]+'  ('+Id+') ' as Name1 FROM [TABLE_NAME] order by ID

Now in the DropDownList add the DataTextField=Name1 and DataValueField=Id

Your project is ready. Now run the project and check the result.

Saturday, July 19, 2014

How to run JavaScript function from code behind in ASP.NET C#

Every time we access JavaScript or Jquery from the aspx page or html page. But some times its really necessary to access the javascript function from the code behind. So today  in this example I will show you all how to call a javascript function or e\write your javascript code in code behind.

To show an alert pop up box the simplest code is..

Response.Write("<script type="text/javascript">alert('Your message');</script>")

But I will show you a better option to do that one.

ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "alert", "alert('Your message');", true);

Within "alert('Your message');" aa call your javascript function or write your code, what ever you want.

For more details go through this link http://bit.ly/1qQtc8y

Wednesday, July 16, 2014

Unable to copy from obj\debug to bin\debug

Visual studio locked the files some time due to some reason. And you will get this error in your project.

Could not copy "obj\Debug\<Project name>.dll" to "bin\<project name>.dll". Exceeded retry count of 10. Failed. <Project name>

Unable to copy from obj\debug to bin\debug

To get rid of this problem a simple solution I found and sharing here to run the project without error.

Go to Solutions Explorer, select the project and right click on it. Go to properties option. Here you will find the Build Events.

On the Build Event there will be a space for Pre-build event command line. Go to that one and paste the following code..


if exist "$(TargetPath).locked" del "$(TargetPath).locked"if not exist "$(TargetPath).locked" move "$(TargetPath)" "$(TargetPath).locked"


Save it and run your project. Save some ones day..Share it...

Monday, July 14, 2014

Bind an image slider with a folder(Without database) in ASP.NET C#


Hello every one, today in this tutorial I will show you how to bind your image slider with a folder, where all the images will come from that folder without any database. Just dump your photos into that folder and the slider will automatically get the images to show with all the animations.

So first know how to get the all file names and files within a folder.


string[] filePaths = Directory.GetFiles(Server.MapPath("~/img/"));
List<ListItem> files = new List<ListItem>();
foreach (string filePath in filePaths)
{
    string fileName = Path.GetFileName(filePath);
    files.Add(new ListItem(fileName, "img/" + fileName));
}

In this way we will get the all files details with the img folder.

Now its time for the slider. Get any slider's html file from any where or write your own code. And now xopy all the resources in your project.


Now create a new web page and copy the head section. Now in the body where actually your slider is presented, change that code with a repeater.


<div id="banner-fade">
<!-- start Basic Jquery Slider -->
 <ul class="bjqs">
      <asp:Repeater ID="Repeater1" runat="server">
           <ItemTemplate>
              <li>
                  <img src='<%# DataBinder.Eval(Container.DataItem,"Value") %>' title='<%# (DataBinder.Eval(Container.DataItem,"Text").ToString()).Split('.')[0].ToString() %>' alt=""></li>
            </ItemTemplate>
        </asp:Repeater>
  </ul>
 <!-- end Basic jQuery Slider -->
</div>

DataBinder.Eval(Container.DataItem,"Value") this one denotes the image url
and
(DataBinder.Eval(Container.DataItem,"Text").ToString()).Split('.')[0].ToString() this one displays the file name without extension.

Now bind the repeater with the above code.


protected void Page_Load(object sender, EventArgs e)
{
     string[] filePaths = Directory.GetFiles(Server.MapPath("~/img/"));
     List<ListItem> files = new List<ListItem>();
     foreach (string filePath in filePaths)
     {
           string fileName = Path.GetFileName(filePath);
           files.Add(new ListItem(fileName, "img/" + fileName));
     }
     Repeater1.DataSource = files;
     Repeater1.DataBind();
}

Now run your code and don't forget to put some images into your image folder.

Download the full source code.

Saturday, July 12, 2014

Add row after in DropDownList binding with SQLDataSource in ASP.NET C#

After binding a DropDownList  in C# using SQLDataSource its showing data all time what ever its bind from the database's table. But if you an one need to add any additional data into the DropDownList  then how to do.

In this article I will show you how to add a row  in a DropDownList  after binding with a SQLDataSource.

First bind a DropDownList with a SQLDataSource and the in the page_Load event write down the following code.

protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
         ddl1.Items.Insert(0, new ListItem("-Select-", "0"));
         ddl1.DataBind();
    }
}

Now run the project and see the change. Enjoy... :)

Thursday, July 10, 2014

Get all folder name within a folder and bind into a repeater

Sometimes its necessary to get the all folder name within a folder or directory. So in this tutorial I will show you how to get all the folder name and put those into an array and then bind the array to a repeater.

So first get the all folder name.

Add a new namespace into the cs file.

using System.IO;

The code is

DirectoryInfo dir = new DirectoryInfo(Server.MapPath("~/FolderName"));
DirectoryInfo[] name = dir.GetDirectories();

Now put this name array in a repeater

Repeater1.DataSource = name;
Repeater1.DataBind();

And in the repeater add the code to display the folder name.


<!--Add your style sheet-->
<asp:Repeater ID="Repeater1" runat="server">
  <ItemTemplate>
      <%# Container.DataItem %>
      <br />
  </ItemTemplate>
</asp:Repeater>

Now on a button click add these two codes to generate directory details within a directory.

Download the full source code here.

Add MySQL Database with .NET Application in C#


In this article I will show you how to add a MySQL database with your .NET application in C#.

For this you need to add MySql.Data.dll as a reference in your project. You can download the dll from here. After downloading the dll select your project and right click on the project, click on the add reference menu. Then browse the dll to add it.

After adding add a new namespace in your .cs page.

using MySql.Data.MySqlClient;

Now after this create a new string which will act as your connection string.

string MySqlConn = "Server=<Ip address>;Port=<Port no>;
                  Database=<Database name>;Uid=<Username>;Pwd=<Password>;";

Generally use port no 3306 as port no in your connection string.

Now to create a new connection

Code:
MySqlConnection con_my = new MySqlConnection(MySqlConn);

Now for command write the follow code

MySqlCommand cmd_my;            
cmd_my = con_my.CreateCommand();
cmd_my.CommandText = "Select * from <table name>";

Now to get the value into a datatable add these.

MySqlDataAdapter da_my1 = new MySqlDataAdapter(cmd_my);
DataTable dt_my1 = new System.DataDataTable();
da_my1.Fill(dt_my1);

If you want to perform any insert, update, delete query then these are the code to proceed.

con_my.Open();
MySqlCommand cmd_my1;
cmd_my1 = con_my.CreateCommand();
cmd_my1.CommandText = "INSERT INTO <tblname>(col1,clo2,col3) 
                VALUES('" + data1 + "','" + datat2 + "','" + data3) + "')";
cmd_my1.ExecuteNonQuery();  // Returns no of row(s)affected
con_my.Close();

So add the MySQL database and enjoy...

Monday, July 7, 2014

Difference between two DataTables in C#

Few days ago I stuck into a problem. I need to update an online database with an offline database. The problem I faced is about to get the difference between two tables of two different databases. After googling I found this code, which helped me a lot. I am sharing the code with you all for your benefits.



public DataTable getDifferentRecords(DataTable FirstDataTable, DataTable SecondDataTable)   
 {   
     //Create Empty Table   
     DataTable ResultDataTable = new DataTable("ResultDataTable");   
 
     //use a Dataset to make use of a DataRelation object   
     using (DataSet ds = new DataSet())   
     {   
         //Add tables   
         ds.Tables.AddRange(new DataTable[] { FirstDataTable.Copy(), SecondDataTable.Copy() });   
 
         //Get Columns for DataRelation   
         DataColumn[] firstColumns = new DataColumn[ds.Tables[0].Columns.Count];   
         for (int i = 0; i < firstColumns.Length; i++)   
         {   
            firstColumns[i] = ds.Tables[0].Columns[i];   
         }   
 
         DataColumn[] secondColumns = new DataColumn[ds.Tables[1].Columns.Count];   
         for (int i = 0; i < secondColumns.Length; i++)   
         {   
             secondColumns[i] = ds.Tables[1].Columns[i];   
         }   
 
         //Create DataRelation   
         DataRelation r1 = new DataRelation(string.Empty, firstColumns, secondColumns, false);   
         ds.Relations.Add(r1);   
 
         DataRelation r2 = new DataRelation(string.Empty, secondColumns, firstColumns, false);   
         ds.Relations.Add(r2);   
 
         //Create columns for return table   
         for (int i = 0; i < FirstDataTable.Columns.Count; i++)   
         {   
             ResultDataTable.Columns.Add(FirstDataTable.Columns[i].ColumnName, FirstDataTable.Columns[i].DataType);   
         }   
 
         //If FirstDataTable Row not in SecondDataTable, Add to ResultDataTable.   
         ResultDataTable.BeginLoadData();   
         foreach (DataRow parentrow in ds.Tables[0].Rows)   
         {   
             DataRow[] childrows = parentrow.GetChildRows(r1);   
             if (childrows == null || childrows.Length == 0)   
                 ResultDataTable.LoadDataRow(parentrow.ItemArray, true);   
         }   
 
         //If SecondDataTable Row not in FirstDataTable, Add to ResultDataTable.   
         foreach (DataRow parentrow in ds.Tables[1].Rows)   
         {   
             DataRow[] childrows = parentrow.GetChildRows(r2);   
             if (childrows == null || childrows.Length == 0)   
                 ResultDataTable.LoadDataRow(parentrow.ItemArray, true);   
         }   
         ResultDataTable.EndLoadData();   
     }   
 
     return ResultDataTable;   
 }  

Now its all about calling the method..


DataTable dt;   
dt = getDifferentRecords(FirstDataTable, SecondDataTable);  

After this you will get the different rows of both datatables into DataTable dt.

Enjoy the code. :)

Reference:
http://canlu.blogspot.in/2009/05/how-to-compare-two-datatables-in-adonet.html

Popular Posts

Pageviews