Sunday, July 19, 2015

E-ICEBLUE, Your Office Development Master

E-ICEBLUE, Your Office Development Master
iText sharp is one of the 3rd party component to use for PDF, Word, Excel, Power Point creation and others in .NET, Now here are E-ICEBLUE to make your office experience even better with .NET. It comes with both C# and VB.NET component. Just download and add the dll into your solution, use their code to create your PDF, Word, Excel or Power Point.

What E-ICEBLUE offers ?

Here are the full list of offers that E-ICEBLUE have for you.
  1. Spire.Doc
  2. Spire.DocViewer
  3. Spire.XLS
  4. Spire.Presentation
  5. Spire.PDF
  6. Spire.PDFViewer
  7. Spire.PDFConverter
  8. Spire.DataExport
  9. Spire.BarCode
All these are offered by E-ICEBLUE to make your Office experience better. Demos are available in their site. Lets see how it works..

How it works? 

For each and every product you have to download the installation file and install this. Now add the add the dll files into your project, as example..

For Spire.Doc download the file and install it in its default path(C:\Program Files\e-iceblue\Spire.Doc). Now add the dll file into your project by browsing the file into default folder or where you have installed. Similarly same thing goes for others also.

As you add the dll files into your project you have to add the namespaces into your VB or CS file. 

using Spire.Doc;
using Spire.Doc.Documents;

Imports Spire.Doc
Imports Spire.Doc.Documents

As you add those namespaces you are now able to access the class to create your doc,
excel,power point and pdf files just by calling the method. 

Let us see how to create a simple doc file in just few lines.

//Create word document
Document document = new Document();

//Create a new paragraph
Paragraph paragraph = document.AddSection().AddParagraph();

//Append Text
paragraph.AppendText("Word file by using Spire.Doc");

//Save doc file.
document.SaveToFile("Sample.doc", FileFormat.Doc);

//Launching the MS Word file.
catch { }

'Create word document
Dim document_Renamed As New Document()

'Create a new paragraph
Dim paragraph_Renamed As Paragraph = document_Renamed.AddSection().AddParagraph()

'Append Text
paragraph_Renamed.AppendText("Word file by using Spire.Doc")

'Save doc file.
document_Renamed.SaveToFile("Sample.doc", FileFormat.Doc)

'Launching the MS Word file.
End Try


How simple to create a doc file. Same thing happens also for Excel, PDF, Power Point. Here I have seen only for Windows application, they have provided also in Silverlight and WPF. 

To check all tutorials you can go for following links.
  1. Spire.Doc
  2. Spire.DocViewer
  3. Spire.XLS
  4. Spire.Presentation
  5. Spire.PDF
  6. Spire.PDFViewer
  7. Spire.PDFConverter
  8. Spire.DataExport
  9. Spire.BarCode
Also you can use the API of Spire.Doc, Spire.DocViewer, Spire.XLS, Spire.Presentation, 
Spire.PDF, Spire.PDFViewer. For that click here.

Important links:

For products visit E-ICEBLUE.
For tutorial visit E-ICEBLUE Tutorials.
For video tutorials E-ICEBLUE Video Tutorials
For purchasing visit E-ICEBLUE.

Friday, July 3, 2015

Image slider from a folder in MVC 4.0

In this post we will learn about to create a HTML JQuery CSS slider where images are binding from a specific folder. Means you just have to add a folder name and rest of the work will be take care of the code.

All we need a pack of JQuery slider. As I found one from my hard disk, I will do with this. 

Step 1:

After creating a new project you have to put all the resources like images, JavaScript and css files into new solutions. We have taken a empty MVC project as Razor view engine. 

As we all can see the assets folder is the resources that we have imported from our HTML Jquery. img folder in assets is the main folder from which we are fetching the images to create a slider.

Step 2:

As we take an empty project we have to build a new controller, so we created a new controller named HomeController and in model folder created a new model named Slider.cs.

Step 3:

Now lets create the Slider.cs file first. It will took two things. One is src (this is the source of the image) & second one is title (Title and alt of the image)

namespace MVCImageSliderFromFolder.Models
    public class Slider
        public string src { get; set; }
        public string title { get; set; }

Step 4:

Now its time for the controller. This is the main thing to get manage all the images and send that to View part to show.

Before proceeding we must have to discuss about the algorithm, which is actually happening. 

Get the Folder Name -> Search all the images(.jpg, .png and others...) -> Make a list of that with source and title -> Send to view for showing the slider.

So lets proceed with searching all the files/images from the desired folder. 

string[] filePaths = Directory.GetFiles(Server.MapPath("~/assets/img/"));

In this way we will get all the files in the folder ~/assets/img. Now we have to create a List of type Slider to pass this to View. To do this...

List<Slider> files = new List<Slider>();
foreach (string filePath in filePaths)
      string fileName = Path.GetFileName(filePath);
      files.Add(new Slider{
            title= fileName.Split('.')[0].ToString(),
            src = "../assets/img/" + fileName

Now in the List files we have the source and the title of all the files/images present in img folder. Now send this to View by    return View(files);

Step 5:

Now the last part is left to do. Bind the model to View part and your slider is ready. 

First of all add the resources at the top of the HTML file (Header section).

<link rel="stylesheet" href="../assets/bjqs.css">
<link href='|Open+Sans:300' rel='stylesheet' type='text/css'>
<link rel="stylesheet" href="../assets/demo.css">

<script src=""></script>
<script src="../assets/js/bjqs-1.3.min.js"></script>
<script src="../assets/js/libs/jquery.secret-source.min.js"></script>

Now add the slider, as we are dealing with only the slider we don't need to worry about all other stuffs. If it is a full web page then you can add a Partial View and pass the Model on that and create the slider portion in that Partial View.

To create the slider....

<div id="banner-fade">
    <ul class="bjqs">
       @foreach (var item in Model)
               <img src='@Html.DisplayFor(modelItem => item.src)'
                     title='@Html.DisplayFor(modelItem => item.title)' alt="">

Write a loop to create the li within ul. All you is done. Only left is to call the javaScript function to run the slider. To call this

jQuery(function ($) {
             includeTag: false

             height: 320,
             width: 620,
             responsive: true

This one will differ from slider to slider, as I took this one they have called it in this way, in other slider calling of the JavaScript functions are different. 

Now build your project and run this. Enjoy the slider.

Download the full source code here.

Saturday, June 13, 2015

Team management Part - II (Add Users)

Team Management
  1. Team Management part 1 (View users)
  2. Team Management Part II (Add Users) [Current]

In my previous post I have posted how to view users using SQL server query with database table structure and as a view method I have shown the ways of genealogy view using normal HTML, CSS and Google organizational chart.

In this post I will show you how to add a new user under one user. The post covers
  1. Full database table structure of users.
  2. Add new user under another user.
  3. Send confirmation mail.
  4. Confirm users via mail id (Using GUID). 
Full database structure:

Previously we have shown only the normal descriptions like email, name, phone no. and member's parent Id. But here we will include another 2 fields.  One is IsConfirm(bit) and another is IsDelete(bit).

Database Design:

UserId (Primary Key)
Int (Identity(1,1)) Primaty Key

IsDelete: Its a bit value to save whether the user is deleted or not. In real process not a single value is being deleted during the delete or update. Each and every information about any thing is keep in store. So we use this type of flag to ensure the arising confusions. If this user is being deleted then the IsDelete field will be False (0), else True (1).

Now you will be little bit confused about the Password section. Where I am storing the password for the user. Here is the answer.

We are using a another table to store the passwords for each user using the UserId.

Int(Identity(1,1)) Primary Key

Using this table we can trace the user's password and their previous password and we can also use this as recovery process.

IsConfirm: This flag is being used to check whether the user is a valid one or not. Here we are sending an email after user's registration. As user go back to his/her mail box and hit the link, he/ she will be an authenticate user by updating the flag from False to True.

Check the diagram closely and understand the process flow of a full add user process.

Step 1:
Take the all inputs from user by creating a form. Here we will take users name, password email and other details. At the time of choosing the parent you can do two things.

  1.  Take the Id of current user (who is logged in). - Use the Session value to get the parent id
  2.  Use a Drop Down List to select the user. - Use a Drop down by binding all the users and their id. Take the selected one as Parent. 

Take the parent id and insert those data into database table. Get the ID from there using
@@identity or SCOPE_IDENTITY()

and with the help of that id insert the password into password table. Here you have to maintain another table for the process of email verification.

I am sure you know how to send the mail with HTML body. If not then go through this link. Here I have described how to send mail via Gmail and GoDaddy.

To get the email verification I am using GUID. To know what is GUID and how to generate that go through ...

We have to link this generated GUID with our user id, and IsConfrim. So what to do? Lets create the table structure.


GUID: The actual code to be generated (unique id)
TableName: On which table it will be updated
Field: On which field the action will be done.
Value: What will be the value after updation of the field.
UserId: On which user it change will be applicable.
IsActive: Is this still usable or not. At first when the GUID is creating it is True and after use it will turn into False.

How to create a GUID? 

To create GUID write down the following code snippet

Guid obj = Guid.NewGuid(); 
Console.WriteLine("New Guid is " + obj.ToString());

this will return a new GUID and with this you can perform all the operations you want.

All you have to do now is have to send a mail along with this GUID. To mail this you can use any of the SMTP server. To send via Google check this or if you want to send via GoDaddy server check this one.  As the mail content will be a link, may be a page link with the generated GUID. Like this


or any thing you want. You can easily get the guid from the URL via Query string.

string guid  = Request.QueryString("id");

when ever you got the GUID you can easily check whether it is previously used or not?

Select  IsActive from <table_name> where GUID="<your GUID>"

It will return either True or False and from that we can get that we have to proceed or not with this user. 

If True then get the table name, user id,  field and the value using this guid.

Select  TableName, Value, UserId, Field from <Table_Name> where GUID = "<your GUID>"

Took this data into a DataTable (say DataTable dt) for future use. Now you have to do the trick with this DataTable. The update statement will something like this.

Update dt.Rows[0]["TableName"].ToString()  set dt.Rows[0]["Field"].ToString() ="+ dt.Rows[0]["Value"].ToString() +" where UserId = "dt.Rows[0]["UserId"].ToString()"

Its is like

Update tblUser set IsActive="True" where UserId="<userid>"

Now update the table and send User a confirmation mail. Before exiting update the Guid table's isActive with false against the GUID.

Now your user is ready to use the application. Enojoy. 

Saturday, May 30, 2015

Logout user after browser close in ASP.NET C# using web services

Keeping a track of user's time in your web application is one of the most important issue to maintain. It not only helps to keep the track of user's but also it helps to solve any other analytical problems with application's data, like average in time, average out time, average time spent in your application etc. So how to keep the users login logout information of your web application.

By clicking on the login button you can easily get the login time, and I hope you have kept your session checking active during logging of your users. On other hand by clicking on the Logout button you can also trace the logout time. But what happen when user close the browser, then how will you keep the track of user's logout time. Here in this post we will discuss about this serious issue.

Using of Web Services
Instead of using  normal methods we will use Web services to get the logout time for the user.

What is Web Services?
According to MSDN
Web services are components on a Web server that a client application can call by making HTTP requests across the Web. ASP.NET enables you to create custom Web services or to use built-in application services, and to call these services from any client application.
Key Concept:
There is a function named onbeforeunload of javascript. This is called at the time of unloading the web page, whether you are closing the browser or closing the tab or redirecting to any other web page from that particular page, where it is coded. Do not use an alert() within onbeforeunload, it will not work.

Using this we are getting the login session id and passes it to the web services. And in web service we are doing our necessary thing(sql server entry or putting it in any notepad with login id etc.).

Using the code:
 Lets create a project named it whatever you want. Add a new web form and design it according to you.

On the aspx page's head section write down the following code.

<script src=""></script>
        window.onbeforeunload = function (evt) {
            var message = 'You have started writing or editing a post.';
            var loginId = '<%= Session["LoginId"].ToString() %>';

                url: "Logout.asmx/LogoutMethod",
                contentType: "application/json; charset=utf-8",
                type: "POST",
                success: function (data) {
                error: function (x, y, z) {
                    alert(x.responseText + "  " + x.status);

On body you do whatever your design or work. In the web services write down again the following code. And make sure that [System.Web.Script.Services.ScriptService] is uncommented

[WebService(Namespace = "")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
public class Logout : System.Web.Services.WebService
   [WebMethod (EnableSession = true)]
   public string LogoutMethod()
       // take a log.txt and write on there with time
       string a = Session["LoginId"].ToString();
       File.AppendAllText(Server.MapPath("~/log.txt"),"Login id loges out "+a+ " at "+ DateTime.Now.ToString()+ Environment.NewLine);

        return "";

Before run this create a log.txt file in your solution explorer, where all your log out log will be stored.

You can down the full source code here.  Now its your turn to do. Try it in your machine.

Saturday, May 23, 2015

Team management Part-I (View users)

Team Management
  1. Team Management part 1 (View users) [Current]
  2. Team Management Part II (Add Users) 

In various applications user is the main character to play a role and for software developer, user management is a big issue to handle. Many thing like user satisfaction, user info secrecy, child parent management, easy to handle, scalability etc. are one of the parts of user management process.  Today in this post I choose to write about the parent child relation within a user management or rather we should say the Team management. This is only the part 1, registration checking delete and many others are coming after this.

What is a Team?

So what is a Team? A group of users which has an admin or manager who is managing a set of people or users. And with all those users a team is forming. In the terms of database all the users are virtual, there is no existing of a physical user. So how to manage those virtual users from our database. Lets see.

Basic Database design:

Database design is one of the most important part of a team management process. If your table structure is not properly maintained then many more problems will arise as the no. of team members will increase. As it follows a tree structure you can take a single table or more than one table to put your users with their all details and an important one, their level.  Level is the one thing from which you can actually track your users and do a descend tracking of users.

Database Design:

UserId (Primary Key)
Int (Identity(1,1))

Here I didn't take any position to place the member under an admin. All the users are under one roof. And they are distinguished by UserId & Email and described as a child of a Parent with ParentId.

Design of the database is quite simple and straight forward. I hope you will understand it clearly.

Query to fetch:

Now we have to write the SQL query to fetch the data along with the parent details. The most easiest and simplest way is to use Self Join. To know Self join more precicely you can follow either or Both have explained it very well.  Now lets come to our query.

select a.UserId, a.Name, a.Email, b.UserId, b.Name, b.Email from tblUser a inner join tblUser b
on a.ParentId = b.UserID

This query will return the all users with their and their parents details.

select a.UserId, a.Name, a.Email, b.UserId, b.Name, b.Email from tblUser a inner join tblUser b
on a.ParentId = b.UserID and a.UserId = '<user_id>'

With the help of this query you can get a single user's details with his/her parents details.

Now you have to find out the possible children and possible parents of a selected node.  For this follow the bellow SQL query.

Query to find all possible parents

SET @UserId = 4;
WITH tblParent AS
    SELECT *
        FROM tblUser WHERE UserId = @UserId
    SELECT tblUser.*
        FROM tblUser  JOIN tblParent  ON tblUser.UserId = tblParent.ParentId
SELECT * FROM  tblParent
    WHERE UserId <> @UserId

Query to find all possible children

SET @userId = 1;
WITH tblChild AS
    SELECT *
        FROM tblUser WHERE ParentId = @userId
    SELECT tblUser.* FROM tblUser  JOIN tblChild  ON tblUser.ParentId = tblChild.UserId
    FROM tblChild

View Team:

You have done your database, you have shown the details of user and their parents information in a tabular format. Now its time for some graphics. We will produce a genealogy or family view of the whole team, or you can set the admin from a particular user (can be set by sql query).

There are whole lots of process to generate a genealogy view. Here I choose two of the easiest way to generate.
  1. Using Google Organizational Chart
  2. Using ulli and CSS3
Google Organizational Chart:

You can get the full details of Google Organizational chart from here. But here I will show you how to connect this with your SQL database. For this you don't need to do much more thing. You just have to create the string which will contain the user data along with their parents' id or name.
Just have a look over the line

data.addRows([['Mike',''], ['Jim''Mike'], ['Alice''Mike'],['Bob','Jim'],['Carol''Jim']]);

It contains the whole of the operation, it is holding the data. You have to create this data string to generate your parent child view. I am taking a DataTable to store the data. You will use the upper sql query to do so.

string s = "";
DataTable table = new DataTable();
for (int i = 0; i < table.Rows.Count; i++)
     s = s + "['"+table.Rows[i][0].ToString()+"','"+table.Rows[i][1].ToString()+"'],";
s = s.TrimEnd(',');

Now in the s string you have all the data stored. Only passing the data stream to JS is left. To do follow the next step.

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());

Here I am using ClientScriptManager to run the created JS code from back end(C# code). Run the code and see the result. 

Using ulli and CSS3:

We have seen how to do this with he help of Google Organizational Chart. Now its time for a pure HTML, CSS work to do. For that We need to generate the HTML. Follow the bellow code to generate the HTML quickly.

DataView view = new DataView(table);
DataTable distinctValues = view.ToTable(true, "parentid");
tree += "<div class='tree'><ul><li style='background-color: white;'>Relegare(Admin)[rel]</li></ul></div>";

 for (int i = 1; i < distinctValues.Rows.Count;i++ )
     SqlDataAdapter da2 = new SqlDataAdapter("select userid,fname+' '+lname from tbl_userlogin where parentid='" + distinctValues.Rows[i]["parentid"] + "'",con);
     DataTable dt2 = new DataTable();
     string temp = "";
     for(int j =0;j<dt2.Rows.Count;j++)
         if (j == 0)
              temp += "<ul>";
         temp += "<li>" + dt2.Rows[j][1].ToString() + " [" + dt2.Rows[j][0].ToString() + "]</li>";
         if (j == dt2.Rows.Count-1)
              temp += "</ul>";
              if (i == 1)
                   tree = tree.Replace("[rel]", temp);
                   tree = tree.Replace("["+distinctValues.Rows[i][0].ToString() + "]", temp);
tree = tree.Replace("[]","");
tree = Regex.Replace(tree, @"\[(.*?)\]", "");

For CSS follow the jsfiddle online demo.

Run your own project to check the team management, though I didn't mention the add or edit/delete part of the team management. In next article I will discuss about the manage roles and permissions of users from their admin end. Enjoy coding.

Download the Download the full source code of Google Organizational chart here.

Follow by Email

Popular Posts