Tuesday 18 March 2014

Implementing Search Functionality in ASP.NET MVC 4

What we are Going To cover


* In this Tutrial we are going to cover how to implement search functionality in Asp.Net MVC 4 . In our web applications in MVC we often need to add the functionality to search the database objects for specific data based on some creteria like to find employees with name starting with 'N' or to find data of employees that have Gender Male

Download Demo App With Database Link Below

Creating Database For This Application

1. First create Database

* Open Microsoft Sql server . Click on New Query . Now execute the query below to create database

Create Database searchingInmvc

Implementing Search Functionality in ASP.NET MVC 4
Create Database Searching in Asp.net MVC 4

2. Then Press F5 . This will create Database successfully

Create Table And Inserting Demo Data


create table tblEmployee         //creating table
(
ID int identity primary key,
Name nvarchar(50),
Gender nvarchar(50),
Email nvarchar(50)
)
Implementing Search Functionality in ASP.NET MVC 4
Creating Table In database 

//Inserting Demo Data

Here , we are inserting 4  Rows in Database table

insert into tblEmployee values('John','Female','john@geeksprogrammings.blogspot.in')
insert into tblEmployee values('funky','Male','funky@geeksprogrammings.blogspot.in')
insert into tblEmployee values('wiley','Male','wiley@geeksprogrammings.blogspot.in')
insert into tblEmployee values('ceren','Female','ceren@geeksprogrammings.blogspot.in')

Implementing Search Functionality in ASP.NET MVC 4
Inserting Data in Table 

Showing All Inserted Data

Download Database script file

In link below you can download the script file and then double click on file it will open in sql server . It will create the database automatically for you when you execute it

Create New MVC 4 Application in Visual Studio

1. Start Visual Studio with language selected as C#
2.Click on File --> Then click on New Project
3. Scroll down and select ASP.NET MVC 4 Web Application

Implementing Search Functionality in ASP.NET MVC 4
Implementing Search Functionality in Asp.Net MVC 4


4. Give appropriate Name,Path and solution Name and Hit Enter
5. choose Empty Template
6. Choose Razor View Engine and Hit Enter
7. Now New MVC 4 web application is started

Adding Models to MVC 4 Application

1. In solution Explorer -- > Right click on Models --> Then click on New item

Implementing Search Functionality in ASP.NET MVC 4

2. Then select ADO.NET Entity Data Model --.> Give it a valid name like 'sampledatamodel'
3. Click Add

Implementing Search Functionality in ASP.NET MVC 4
Implementing Search Functionality in Asp.Net MVC 4

4. Now A dialog box appears choose database connection to sql server and give your connection string a name that will be give to connection string in web.config file

Implementing Search Functionality in ASP.NET MVC 4
Implementing Search Functionality in Asp.Net MVC 4

5. click next
6. Now in next dialog box you will be presented with tables available in database table select you table

Implementing Search Functionality in ASP.NET MVC 4
Implementing Search Functionality in Asp.Net MVC 4

7. Now click Finish
8. Now Entity model of table is generated you can rename your database here to 'Employee'

Implementing Search Functionality in ASP.NET MVC 4
Implementing Search Functionality in Asp.Net MVC 4

9. Now Model is successfully Added

Adding Controller and Views To MVC 4 Application

To add controller to database --

1. Right click on Controllers folder in solution folder
2. click on Add --> Then click on Controller

Implementing Search Functionality in ASP.NET MVC 4
Implementing Search Functionality in Asp.Net MVC 4

3. Now Add controller Dialog Box appears
4. Give your controller a name like 'HomeController'
5. In template choose  'MVC controller with read/write and views using Entity  Framework'
6. The Reason behind choosing this is it will automatically generate some pages to insert,delete , update data of model to which we are associating this controller
7. Now give the Model name that we have added in previous step 'Employee'
8. Now Choose dbcontext class from dropdown menu and finally  click ADD
9. This autimatically add Views for insert , update, delete and index view in views folder under controller named folder

Implementing Search Functionality in ASP.NET MVC 4
Implementing Search Functionality in Asp.Net MVC 4

 10. Now Run your application . This will give output below:-

Implementing Search Functionality in ASP.NET MVC 4
Implementing Search Functionality in Asp.Net MVC 4

Adding Style And Look To Application

So we are going to search the database and retrieve data from database and then show the retrieved result to user. For this we have to get some controls and code . The GUI design that are going to give to this application is as below :-

1. In solution Explorer under Index view Double click on Index.cshtml
2. Now just before the line '<h2>Index</h2>' add a line 

<div style='font-family:Arial'>
and close this div right below the code after table tag 

Other UpdationAre in Demo Project Downlao And Use it

3. Update your Index.cshtml file under view folder in solution Explorer with the code below

@model IEnumerable<SearchInMVC.Models.Employee>
@{
    ViewBag.Title = "Index";
}
<div style="font-family:Arial ">
<h2>Index</h2>

<p>
    @Html.ActionLink("Create New", "Create")
</p>
<p>
@using (Html.BeginForm ("Index","Home",FormMethod.Get ))
{
<b>Search by:</b>@Html.RadioButton("searchBy","Name")<text> Name</text>
@Html.RadioButton("searchBy","Gender")<text>Gender</text><br />
@Html.TextBox("Search");<input type="submit" value="Search" />
    }
</p>
<table border="1">
    <tr>
        <th>
            @Html.DisplayNameFor(model => model.Name)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.Gender)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.Email)
        </th>
        <th>Action</th>
    </tr>
    @if (Model.Count() == 0)
    {
        <tr>
        <td colspan ="4">No Rows Match Search Criteria</td>
        
        </tr>
    }
    else
    {
foreach (var item in Model)
{
    <tr>
        <td>
            @Html.DisplayFor(modelItem => item.Name)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.Gender)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.Email)
        </td>
        <td>
            @Html.ActionLink("Edit", "Edit", new { id = item.ID }) |
            @Html.ActionLink("Details", "Details", new { id = item.ID }) |
            @Html.ActionLink("Delete", "Delete", new { id = item.ID })
        </td>
    </tr>
}
    }
</table>
</div>




Now Run your Application and you can see the change with output below :-

Implementing Search Functionality in ASP.NET MVC 4
Implementing Search Functionality in Asp.Net MVC 4

Code Description

In code above we have used Razor code and instead of using <form> tag that we usually use in html we have used Html Helper below


@using (Html.BeginForm ("Index","Home",FormMethod.Get ))
{
<b>Search by:</b>@Html.RadioButton("searchBy","Name")<text> Name</text>
@Html.RadioButton("searchBy","Gender")<text>Gender</text><br />
@Html.TextBox("Search");<input type="submit" value="Search" />
    }




In Html.BeginForm ("Index","Home",FormMethod.Get )

Here, Html.BeginForm  is used in place of using form tag . Html.BeginForm  Received 3 arguments .
Here, "Index" is Name of action that will be executed on posting form  to server
Here, "Home" is name of controller to which this link will be redirected when clicked
Here, " FormMethod.Get" type of encoding method that applied on data we are posting 

Now Open Controller And Add code below to Index Action of home controller

 if (searchby == "Gender")
            {
                return View(db.Employees.Where(x => x.Gender == search || search ==null).ToList());
            }
            else
            {
                return View(db.Employees.Where(x => x.Name.StartsWith(search)).ToList());
}






























Monday 3 March 2014

Working with Master Pages Asp.net


Why Do We Need Master Pages ?


Most Web sites today have common elements used throughout the entire application or on a majority of the pages within the application. If you look at main page of Reuters News website  ( www.reuters.com ) , you can see common elements that are used throughout the entire web site. Here is screenshot of website given below :-


In this screenshot , notice header section , the navigation section, and footer section on the page. In fact, nearly every page within the entire applicaiton uses these same elements. Even before master pages, you had ways to put these elements into every page through a variety of means; but in most cases, doing so posed difficulties.

Some developers simply copy and paste the code for these common sections to each and every page that requires them. This works , but it's rather labor intensive. However, if you use the copy-paste method, whenever a change is required to one of these common sections of the application, you have to go into each and every page and duplicate the change.


How To Use Master Page In Asp.net

DEMO APP DOWNLOAD LINK IS AVAILABLE  BELOW

1. In Visual Studio click on file then New Project then Choose your preferred
language like i have used c# then choose Web  and Then click on Asp.NET Empty Web Application and click ok

2. Now empty web site solution is created for you

3. Now in solution explorer in right side panel Right click on you solution name

4. In popup menu click on Add then click on New Item

5. Now choose Master Page give it a name like 'master1.Master' and click ok

Each Master Page consist of ContentPlaceHolder  control that control provides the space to other webform that is inheriting this Masterpage to place its own content on that webform along with Content on Master Page The Master Page contents are availaible in Child Webform but we cannot edit these content in child webform But in Content placeholder we can add the content according to our requirements

Content Placeholder are used like below:- 


These lines of code are automatically added to your Master Page .

 <asp:ContentPlaceHolder ID="ContentPlaceHolder1" runat="server">

<%-- This Place is available to Child web-form to put its content along wit master page --%>

</asp:ContentPlaceHolder>

To place default content within one of the content areas of master page, you simply put it in the contentPlaceholder server control on the master page itself or it is automatically added. Any content page that inherits this master page also inherits the default content

Calling Master Page Content Placeholder in other WebForm

Add  ' MasterPageFile ="~/master1.Master" '   to Page Tag at Top of your Webform



This tells that webform to inherit contents from its master Page and webform can also put its own content within content placeholder avaliable by Master Page

Demo App 

App To use Master Pages in Asp.net

Master Page Code


<%@ Master Language="C#" AutoEventWireup="true" CodeBehind="master1.Master.cs" Inherits="WebApplication5.Site1" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <asp:ContentPlaceHolder ID="head" runat="server">
    </asp:ContentPlaceHolder>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    This is Master Page
        <asp:ContentPlaceHolder ID="ContentPlaceHolder1" runat="server">
      
       
        </asp:ContentPlaceHolder>
    </div>
    </form>
</body>
</html>


Webform Page code


<%@ Page Language="C#" AutoEventWireup="true" MasterPageFile ="~/master1.Master" CodeBehind="WebForm1.aspx.cs" Inherits="WebApplication5.WebForm1" %>
<asp:Content runat ="server" ContentPlaceHolderID ="ContentPlaceHolder1"><p>
    <br />

    This is Child Page Inheriting Master Page</p>
</asp:Content>


Description of code :- In @ Page directive we have included the MasterPageFile that implements the Master Pages concept in your web application or website This highly reduces code in websites and webapplications and it reduces redundancy of code

In this code we have called or used the contentPlaceHolder that we have initialized in Master Page we can add contents to this Content Place Holder that is only specific to this page only.


Nesting Master Pages

I hope you see the power that master pages provide to help you create templated web applications . so far you have been creating single master page that the content page can sue. Most companies and organisations, however are not just two layers. Many divisions and groups exist within the organization that might want to use variations of the master by, in effect , having a master page within a master page. With ASP>NET , this is quite possible.

How To USE DEMO APP

In this Demo App i have connected contains :-

( i )  master1.master
( ii ) master2.master  // inherit from master1
( iii) Default.aspx  // has master page - master 2

So we have 2 Master Pages and 1 Webform . These two master pages contain all Designing part of webpage and it remains same for full website so it kept in master . Master1 contains Header and Navigation part and Master 2 conatains other Remaining body part of webpage 

Code For Master Page 1


<%@ Master Language="C#" AutoEventWireup="true" CodeBehind="master1.master.cs" Inherits="Masterpages.master1" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">

<%--oswd.org--%>


<head runat="server">
    <link href="Styles/style1.css" rel="stylesheet" type="text/css" />
    <title></title>
    f
</head>
<body>
    <form id="form1" runat="server">

    <table width="100%" border="0" cellspacing="0" cellpadding="0">
  <tr>


   <%--fgfg--%>

    <td class="shadow_left">&nbsp;</td>
    <td class="header_column">
<table width="100%" border="0" cellspacing="10" cellpadding="0">
      <tr>
        <td class="logo_area">Logo Here </td>
        <td width="300">
          <form id="form2" name="form1" method="post" action="">
  Search the website <br />
            <input name="search_text" type="text" id="search_text" />
            <input type="submit" name="Submit" value="Search" />
          </form>
          </td>
      </tr>
    </table></td>
    <td class="shadow_right">&nbsp;</td>
  </tr>
  <tr>
    <td class="horizontal_column">&nbsp;</td>
    <td class="horizontal_center"><table width="100%" border="0" cellpadding="0" cellspacing="0" class="linkcontainer">
      <tr>
        <td><div class="navigation"><a href="#" class="main_link">Home</a></div></td>
        <td><div class="navigation"><a href="#" class="main_link">Gallery</a></div></td>
        <td><div class="navigation"><a href="#" class="main_link">About</a></div></td>
        <td><div class="navigation"><a href="#" class="main_link">Help</a></div></td>
        <td><div class="navigation"><a href="#" class="main_link">Partner</a></div></td>
      </tr>
    </table></td>
    <td class="horizontal_column">&nbsp;</td>
  </tr>
  <tr>
    <td class="shadow_left">&nbsp;</td>
    <td class="below_header">Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do  eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad  minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip  ex ea commodo consequat. Duis aute irure dolor in reprehenderit in  voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur  sint occaecat cupidatat non proident, sunt in culpa qui officia  deserunt mollit anim id est laborum</td>
    <td class="shadow_right">&nbsp;</td>
  </tr>
  </table>
    </form>
     <asp:ContentPlaceHolder ID="contentholder" runat="server">

    </asp:ContentPlaceHolder>
    <tr>
    <td class="shadow_left">&nbsp;</td>
    <td class="bottom_link_container"><p><a href="#" class="bottom_link">Link</a> | <a href="#" class="bottom_link">Link</a> | <a href="#" class="bottom_link">Link</a> | <a href="#" class="bottom_link">Link</a> | <a href="#" class="bottom_link">Link</a> </p>
    <p>All Right Reserved &copy; 2006 by bprizze<br />
      http://heartlessg.4uhost.info Web Master
    </p></td>
    <td class="shadow_right">&nbsp;</td>
  </tr>
</body>
</html>


Code for Master Page 2 ( master2.master )


<%@ Master Language="C#" MasterPageFile="~/master1.Master" AutoEventWireup="true" CodeBehind="master2.master.cs" Inherits="Masterpages.master2" %>

<asp:Content ID="content" ContentPlaceHolderID="contentholder" runat="server">
    <tr>
    <td class="shadow_left">&nbsp;</td>
    <td class="main_content_box"><table width="100%" border="0" cellspacing="0" cellpadding="0">
      <tr>
        <td class="left_content">
            <p>link</p>
            <p>Link</p>
            <p>link</p>
            <p>link</p>
             <p>link</p>
            <p>Link</p>
            <p>link</p>
            <p>link</p>
            <p>Link</p>
            
        </td>

        <td class="body_content" valign="top">
        <asp:ContentPlaceHolder ID="Main" runat="server">
        
        </asp:ContentPlaceHolder>
        &nbsp;</td>
      </tr>
    </table></td>
    <td class="shadow_right">&nbsp;</td>
  </tr>
  <tr>
    <td class="shadow_left">&nbsp;</td>
    <td class="middle_spacer"><div class="bottom_content">Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do  eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad  minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip  ex ea commodo consequat. Duis aute irure dolor in reprehenderit in  voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur  sint occaecat cupidatat non proident, sunt in culpa qui officia  deserunt mollit anim id est laborum</div></td>
    <td class="shadow_right">&nbsp;</td>
  </tr>

</asp:Content>


Code For Default.Aspx


<%@ Page Language="C#" AutoEventWireup="true" MasterPageFile="~/master2.Master" CodeBehind="default.aspx.cs" Inherits="Masterpages._default" %>
<asp:Content ID="content" ContentPlaceHolderID="Main" runat="server">
    <h1>Main page</h1>
</asp:Content>

Sunday 2 March 2014

HTML / aspx web Page TO PDF using iTestsharp C#


HTML web Page TO PDF Conversion


A number of times while searching on internet for relevant information we like content of more than one website so we often want to save that content we mostly do the old technique like saving the webpage using Ctrl + s or copy its content and save it in some other Notepad file or Microsoft Word etc. This technique consumes  our a lot of time .

So As web Developers we must give easy content saving way to user. For including the Feature of converting a web Page into PDF you can search for number of libraries available on internet . I have used iTextsharp and it works fine for me without any more complications . It takes very less time to implement as compared to other libraries and implements easily

Introduction to iTextSharp


iTextSharp is a free library that is available to create PDF documents with Microsoft  Visual studio using C# or Vb# Language. It is very easy to use and give more flexibility as compared to all other libraries available to  generate PDF. I have used a lot of libraries almost 4-5 but i feel very
comfortable using iTextsharp library that more full customization features for PDF Documents. It consist of number of objects for creating Tables or paragraphs that make easy to customize the view of your data on PDF Documents

Download iTextSharp


For using iTestSharp library in your project for converting your HTML or aspx Web Page into PDF you have to download iTextSharp.dll file from Link Below :


Download C# Application To Convert Html/aspx To PDF

How To Use This Application Code


1. First Download iTextSharp.dll file By clicking on link above

2. Now Download C# Application To Convert Html/aspx To PDF

3. Extract the winrar file on your computer . Then open web2pdf solution file . 

4. Now first, add the reference to download iTextSharp.dll file by following steps :-

( i )   click on Solution Explorer in Right sidebar
( ii )  Now Right click on Reference Folder --> Then click on Add Reference
( iii ) Now in Add Reference Dialog Box click on Browse Tab


upload itextsharp.dll


( iv )  Now select the iTextSharp.dll file from location where you download it ( make sure you   have extracted the iTextSharp file )
( v )   Now click ok
( vi )  Now you can see in Reference folder your iTextSharp file Reference will be added

5. Now Add Reference to following Namespaces in your webform


using iTextSharp.text;


using iTextSharp.text.pdf;
using iTextSharp.text.html;
using iTextSharp.text.xml;
using iTextSharp.text.html.simpleparser;


Application Demo WebPage Code :



<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="web2pdf.WebForm1" %>


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" > 
<head id="Head1" runat="server"> 
<title>Untitled Page</title> 
    <style type="text/css">
        .style5
        {
            width: 24px;
            height: 342px;
        }
        .style6
        {
            height: 89px;
        }
        .style7
        {
            height: 342px;
        }
        </style>
</head> 
<body> 

<form id="form1" runat="server" > 
<div style="width:100%;height:375px;"> 
<table border="1" style="height: 484px; width: 567px" > 
<tr> 
<td colspan="2" style="background-color:#FFA500;" class="style6"> 
    <h1>Web Page To PDF Conversion Using iTextSharp</h1></td> 
</tr> 
<tr> 
<td style="background-color:#FFD700;" class="style5"> 
</td> 
<td style="background-color:#eeeeee;" class="style7"> 
    Don&#39;t Forget To Subscribe us</td> 
</tr> 
<tr> 
<td colspan="2" style="background-color:#FFA500;"> 
    Powered By geeksprogrammings.blogspot.in</td> 
</tr> 
</table> 
</div> 
</form> 

</body> 

</html> 

Design of Demo Webform



HTML Web Page To PDF Using iTextSharp C#




Application C# Code 

( Don't Forget to change
 project, namespaces names or class names according to your App)



using System;
using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.UI;

using System.Web.UI.WebControls;

using System.IO;
using System.Text.RegularExpressions;
using iTextSharp.text;
using iTextSharp.text.pdf;
using iTextSharp.text.html;
using iTextSharp.text.xml;
//using System.Xml;
using iTextSharp.text.html.simpleparser; 


namespace web2pdf
{
    public partial class WebForm1 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }
        protected override void Render(HtmlTextWriter writer) 
MemoryStream mem = new MemoryStream(); 
StreamWriter twr = new StreamWriter(mem); 
HtmlTextWriter myWriter = new HtmlTextWriter(twr); 
base.Render(myWriter); 
myWriter.Flush(); 
myWriter.Dispose(); 
StreamReader strmRdr = new StreamReader(mem); 
strmRdr.BaseStream.Position = 0; 
string pageContent = strmRdr.ReadToEnd(); 
strmRdr.Dispose(); 
mem.Dispose(); 
writer.Write(pageContent); 
CreatePDFDocument(pageContent); 


public void CreatePDFDocument(string strHtml) 

string strFileName = HttpContext.Current.Server.MapPath("test.pdf"); 
// step 1: creation of a document-object 
Document document = new Document(); 
// step 2: 
// we create a writer that listens to the document 
PdfWriter.GetInstance(document, new FileStream(strFileName, FileMode.Create)); 
StringReader se = new StringReader(strHtml); 
HTMLWorker obj = new HTMLWorker(document); 
document.Open(); 
obj.Parse(se); 
document.Close(); 
ShowPdf(strFileName); 



public void ShowPdf(string strFileName) 
Response.ClearContent(); 
Response.ClearHeaders(); 
Response.AddHeader("Content-Disposition", "inline;filename=" + strFileName); 
Response.ContentType = "application/pdf"; 
Response.WriteFile(strFileName); 
Response.Flush(); 
Response.Clear(); 



If, you have any problem with code working or any other issue with converting HTML / aspx to pdf you can share in comments

Saturday 22 February 2014

computer graphics Line Drawing Algorithm



Line Drawing is done by calculating Intermediate positions along the line path Between specified paths. DDA LINE Algorithm is a simplest algorithm of drawing a line . In DDA Algorithm line is simply Draws by adding the increment to initial pixel values with respect to x and y direction . After drawing initial pixel whose x and y direction are entered by user or inputted by user Then the Next pixel is drawn by adding Change in x and y direction of new pixel to the initial pixel 

We will add the value of change in x and y axis to initial or previous x and y axis values to get New pixel plotted on screen and This process continues upto and end point that is also inputted by user at start of execution of This Algorithm

The Screen Locations are refrenced by integer values and if these values are in fraction like 10.25 and 21.4 :- (10.25,21.4)  where 10.25 is x coordinate in x-Axis and 21.4 is Y Coordinate in Y-Axis Then These Fractional Values will be converted into Integer values on Screen and interpreted as (10,21). This rounding of two integers cause lines to be displayed with stare steps appearance in Zagged line


To Display a pixel on Screen we use 

                                                          putpixel ( 10 , 11 )

How Line Drawn in DDA Line Algorithm

1. First user input the four values 

* Initial pixel value in x-direction            { let x1 }
* Initial pixel value in y-direction            { let y1 }
* End Point pixel value in x-direction     { let x2 }
* End Point pixel value in y-direction     { let y2 }

2. Now all inputs are  given , Now first input the initial pixels point

putpixel ( x1, y1 )

3. Now we will add the an increment value to initial x and y coordinates and this increment value is added upto End Point


4. The Increment value is calculated by 

dx = x2 - x1   // In x-Direction
dy = y2 - y1   // In y-Direction

Here dx is the how much total distance to cover in x-direction to reach the End coordinate in x-direction
Here dy is the how much distance to cover in y-direction to reach the End coordinate in y-direction

5. Now find the how must distance to cover at one time or at one loop run 

6. This is calculated by dividing the dx and dy by a step 

7. value of step will be value among dx or dy 

If dx > dy then
{
step = dx
}
else
{
step = dy
}

8. After calculating step change in x-direction let be cx will be 

cx =  dx/step 
This will give how much distance to cover in each loop run or at one time how much increment will takes place

Similarly in y-direction 
cy =  dy/step 
This will give how much distance to cover in each loop run or at one time how much increment will takes place

9. Now Start a loop and it will continue upto value in Step variable 

increment x and y as :- 

x= cx + x
y= cy + y
setpixel ( x , y )  // Put or set the New pixel 

 
10. Now at execution of Loop the line will be printed

For Any query feel free and post the question you will get feedback within 2 hours

Friday 21 February 2014

Static Data Member and Static Member Functions




STATIC DATA MEMBER

As we know Each object of a particular specified class consist of its own data . But if we declared Data item is as static data item then this static data item or we can simply say static variable or static member function will be available for global access for all objects of class . It means if you have declared a variable for member function as static then this can be accessed by all objects of class .

I mean to say if you have declared a variable as static then you have assigned it value '5'  through Obj1 object of class . Then if you have created a new object Obj2 and accessing value of static variable that it is still holding value '5' if it is accessed through Obj2 .


A Static Variable is visible or accessible only within the class or only by members of class But its lifetime is throughout the program means it can hold the same value throughout the lifetime of program


DECLARATION :-

                                  Static int stvar;

INITIALIZATION :- 

                
*                                     int abc : : stvar =10

        In this Stvar is initialized with value '10' and abc is class name . 

*              int abc : :  : stvar ;
In this abc is classname and now stvar will be assigned '0' value



SIMPLE PROGRAM TO SHOW USE OF STATIC VARIABLE


#include<iostream.h>
#include<conio.h>

class static_var
{

static int count;    //static member of class
public :


void incr_staticvar()
{
count++;
}

 void outputc()
{
cout<<"Value of Static variable Count :- "<<count<<endl;
}
};

int static_function : : count;

void main()
{
clrscr();
static_var obj1,obj2,obj3,obj4;

obj1.incr_staticvar();
obj2.incr_staticvar();
obj3.incr_staticvar();
obj4.incr_staticvar();

cout<<"\nAfter Increment of static variable by Four Different objects is :-\n";

obj1.outputc ( );
obj2.outputc ( );
obj3.outputc ( );
obj4.outputc ( );


      getch();
}

OUTPUT :-




STATIC MEMBER FUNCTION



The Word Static means fixed . To  make a member function static you have to precede the word static to it .

Facts About Static Member Functions :-

*  The main usage of static functions is they are made to access static members of class or static variables of class that are declared in same class in which static member functions are declared

* These can be called outside class or in main function without using Object of class.



HOW TO CALL STATIC MEMBER FUNCTION


CLASS_NAME  : :  NAME_OF_FUNCTION

SIMPLE PROGRAM TO SHOW USE OF STATIC MEMBER FUNCTIONS


#include< iostream.h >
#include< conio.h >

class static_function
{

int a;
static int count;    //Declaration of static Data member of class 

public :

static_function( )    // Constructor that is initializing variable a to 0
{
a=0;
}

void non_static( )    // public member function that is incrementing a variable
{
a++;
}

void outputn ( )  // public member function to cout value of a
{
cout<<"A :-  "<<a<<endl;
}

void incr_staticvar( )   // public member function to increment static variable
{
count++;
}

static void outputc( )  // public member function to cout value of static variable
{
cout<<"Value of Static variable Count :- "<<count<<endl;
}
};

int static_function :: count;

void main( )
{
clrscr();
static_function obj1,obj2,obj3,obj4;   //creation of four object of class static_function

cout<<"Initially ";
static_function : : outputc();     // calling static function

obj1.incr_staticvar();    //calling public funtion to increment static variable
obj2.incr_staticvar();
obj3.incr_staticvar();
obj4.incr_staticvar();



cout<<"\nAfter Increment of static variable by Four Different objects is :-\n";
static_function ::outputc();

obj1.non_static();    // function to increment a variable
obj2.non_static();
obj3.non_static();
obj4.non_static();

cout<<cout<<"After Increment of Variable 'A' by Four Different objects i :-";
obj1.outputn();
obj2.outputn();
obj3.outputn();
obj4.outputn();

      getch();

}

OUTPUT :-



write Program To Print All Permutations of given string

Combination programs require good understanding of mathematics . In combination or permutation concepts some formulas are used to identify how this combination of letters will be formed and how many combinations will be made . 

Formula for Permutation :- 
                                                N! / (N-r)!
Where N is the total number of characters that are available in your input string . 
Where r is total number of characters that will be taken at one time .

 Like if total number of characters in string is '5 ' and total number of characters taken at one time is '4' Then

Permutation = 5! / (5-4)!  = 120


Formula for Combination :- 
                                                      N! / r!  * (N-r)!
                                                 
Where N is the total number of characters that are available in your input string . 
Where r is total number of characters that will be taken at one time .

Program
In the following program we are making a program in C++ to print all possible combinations of  "abcd" string . As we can see we have to find permutation . So formula for it is :-

    N! / (N-r)!
    4! / (4-4)!  =24 
So 24 total combinations will be made from string "abcd" . There are four characters and 24 combinations . so each character will remain at one position for 24/4 time means 6 times. 

Program To Print all possible combinations of all characters of  "abcd" string .


#include< iostream.h >

#include< conio.h >
main ( )
{
clrscr ( );
int n=4;        // Here n is 4 so this programs prints all possible combinations for
char a[5];      // 4 character you can specify any value you want
cout<<"This program gives all possible combinations of four characters "<<endl;
cout<<"\nEnter Four Characters :-  ";

//Input four character from user in a [  ] array
for(int x=0;x<=3;x++)
{
 cin>>a[x];
}

cout<<"\nNow Combinations "<<" is :- \n"<<endl;

for(int z=0;z<=n-1;z++)
{
for(int j=0;j<=n-2;j++)
{
int temp;
temp=a[n-1];
a[n-1]=a[n-2];
a[n-2]=temp;
cout<<"\t";

for (int l=0;l<=n-1;l++)
{
 cout<<a[l];
 }

cout<<"\t";

temp=a[n-3];
a[n-3]=a[n-1];
a[n-1]=temp;

for ( int l2=0;l2<=n-1;l2++)
 {
cout<<a[l2];
 }
 }

 int temp1;
 temp1  =  a[0];
 a[0]  =  a[z+1];
 a[z+1]  =  temp1;

 cout<<"\n";
  }
getch();

}


OUTPUT :-



CODE EXPLANATION

cout<<"\nEnter Four Characters :-  ";

//Input four character from user in a [  ] array
for(int x=0;x<=n;x++)
{
 cin>>a[x];
}


In This Block of code we are getting input of four character whose combinations are generated by this program. In this we have used a for loop that consist of x counter that is initialized from 0 and it will continue upto 3 that allows user to enter 4 character to get their all possible combinations

Code below is logic of this program that given all possible combinations of entered characters
I have explained it with comments with it



for(int z=0;z<=n-1;z++)    // loop continues from 0 to 3 (  if n is 4 )
{
for(int j=0;j<=n-2;j++)       // loop continues from 0 to 2 (  if n is 4 )
{
{
int temp;
temp=a[n-1];
a[n-1]=a[n-2];
a[n-2]=temp;
cout<<"\t";

for (int l=0;l<=n-1;l++)
{
 cout<<a[l];
 }

cout<<"\t";

temp=a[n-3];
a[n-3]=a[n-1];
a[n-1]=temp;

for ( int l2=0;l2<=n-1;l2++)
 {
cout<<a[l2];
 }
 }

 int temp1;
 temp1  =  a[0];
 a[0]  =  a[z+1];
 a[z+1]  =  temp1;

 cout<<"\n";
  }

This code of block produces the all possible combinations of given input character by placing each character at all positions within the string each character including its original position within string will exchanged with or replaced with every position within the string so as to generate unique string each time

Saturday 15 February 2014

Algorithm and Implementation Program of Quick Sort



Quick Sort is a Sorting Algorithm based on Divide And Conquer Technique. In this at every step element is placed in its proper position.It performs very well on a longer list. It works recursively, by first selecting a random "Pivot value" from the list. Then it partitions the list into elements that are less than the pivot and greater the pivot and greater than the pivot. The problem  of sorting a given list is reduced to the problem of sorting two sublists It is to be noted that the reduction step in the quick sort finds the final position of particular element; which can be accomplished by scanning that last element of list from the right to left and check with the element.

Quick sort is Developed by C.A.B. Hoare. The main purpose of quick sort is to find the element that partitions the array into tow halves and to place it at its proper location in the array.


Working Of Quick Sort


Before we start the learning how quick sort works, we make some assumptions . Set the index of first element of array to LOC and LEFT variable and index of last element of the array to RIGHT variable. Then proceeds as follows :-

1. Start with element pointed to by Right. The array is scanned from right to left , comparing each element on the way with the element pointed by LOC till either.

         ( a ) Element smaller than the element pointed to by LOC is found and elements are interchanged . Procedure continues with Step2.

         ( b ) If the value of the RIGHT becomes equal to value of LOC, the procedure terminates here. This indicates that element is placed in its final position.

2.  Start with element pointed to by LEFT. The array is scanned from left to right, comparing each element on the way with the element pointed by LOC till either.

         ( a ) Element greater than the element pointed to by LOC is found . In this case the elements are interchanged and procedure continues with step 1.
         ( b ) If the value of LEFT becomes equal to value of LOC , athea procedure terminates. This condition indicates that the element is placed in its final position

At the end of this procedure the first element ( PIVOT ) of original array is placed in its final location in the sorted array. The elements to its left will be less than this element and element to the right will be greater than this element . Now whole procedure that we applied on complete file will be applied on first subfile ( first index to LOC-1) and second (LOC + 1 to last index ) until we get the sorted array


Algorithm : QUICK SORT


Consider an Array( A ) with N elements having LB as lowerbound and UB as upperbound.

ALGORITHM : QUICK_SORT(A, LB, UB )

Step 1      If         ( LB < UB ) then
                           P = SUB_ARRAY (A, LB, UB )
                          QUICK_SORT(A, LB, P-1 )
                          QUICK_SORT(A, P+1, UB )            
               Else
                 
                   // Print sorted Array

Step 2    End

The above function is using the Divide and conquer strategy for algorithms. In above step we are dividing a large available Array named 'A' into smaller arrays and then we are passing these smaller arrays to SUB_ARRAY function that sorts the small list . And get back to Quick_Sort function and then again the divide the remaining list into another portion of a small array and then again take it to SUB_ARRAY function to sort this small array list in this way full or all elements of array are sorted


ALGORITHM : SUB_ARRAY(A, LB, UB )

Step 1      Set LEFT = LB,
               Set RIGHT = UB,
               Set LOC = LB

Step 2     Repeat step 3 and 4

Step 3      // Scanning Array from Right To Left
               Repeat while A[LOC] <= A[ Right] and LOC != Right
               Right = Right -1
                          ( a ) If LOC == Right then
                                 Return LOC
                          ( b ) Interchange A [LOC] & A [RIGHT]
                          ( c ) Set LOC == RIGHT

Explanation :- In Step 3 Array 'A' is scanned starting from Rightmost element of array and going towards the Left of array . In this step this algorithm finds the element which is greater the element at A[LOC] or pivot element and  when element which is greater than pivot is found it is replaced with A[LOC] and LOC is set the Location of element with which we have replaced the location it means A[RIGHT] and else the Right is decremented by 1 until it comes to location same as LOC

Step 4     // Scanning Array  from LEFT to Right
               Repeat while A[LOC] >= A[LEFT] and LOC != LEFT
               LEFT = LEFT +1
               ( a ) If LOC == LEFT then
                       Return LOC
               ( b ) Interchange A[LOC] and A[LEFT]
               ( c ) Set LOC = LEFT

Explanation :- In Step 4 Array 'A' is scanned starting from Leftmost element of array and going towards the Right of array . In this step this algorithm finds the element which is smaller the element at A[LOC] or pivot element and  when element which is smaller than pivot is found it is replaced with A[LOC] and LOC is set the Location of element with which we have replaced the location means A[LEFT].

Step 5      End


Implementation of Quick Sort Algorithm in Cplusplus ( c++ ) Program



#include< iostream.h >
#include< conio.h >
int a[20], n, lb, loc, ub, left, right, temp, temp1;

void quicksort(int[10],int,int);

int pivot(int[],int,int);

void main()
{
cout<<"Enter size of array";
cin>>n;
cout<<"Enter Array Elements ";
for(int i=0;i<n;i++)
{
cin>>a[i];
}
quicksort(a,0,n-1);
for(int z=0;z<n;z++)
{
cout<<" "<<a[z];
}
getch();
}
void quicksort(int a[], int lb, int ub)
{
int p;
if(lb<ub)
{
p=pivot(a,lb,ub);
quicksort(a,lb,p-1);
quicksort(a,p+1,ub);
}
}
int pivot( int a[],int lb,int ub )
{
for(int z=0;z<n;z++)
{
cout<<" "<<a[z];
}
cout<<endl;
left =lb;
right = ub;
loc  =lb;
cout<<"right is :- "<<right;
cout<<"\tloc is :-"<<loc;
cout<<"left is :- "<<left;
 cout<<"Now right \n";
while((a[loc]<=a[right]) && (loc!=right))
{
right=right-1;
}
if(loc==right)
{
return loc;
}
temp=a[loc];
a[loc]=a[right];
a[right]=temp;
loc=right;
cout<<"Now left \n";
while((a[left]<=a[loc]) && (loc!=left))
{
left=left+1;
}
if(loc==left)
{
return loc;
}
temp1=a[loc];
a[loc]=a[left];
a[left]=temp1;
loc=left;





}



OUTPUT QUICK SORT PROGRAM
quick sorting technique with quick sort algorithm programming
Output of Quick Sort Program

For any type of more explanation to this program and for any suggest to this post you can freely comment . your comment are very crucial to us.

Sunday 9 February 2014

C program to shutdown restart logoff hibernate computer in windowsxp windows7 and ubuntu

C program To Shutdown Computer in Windows xp

This is a program to Shutdown your computer by using C programming language code. This code will first ask you for the confirmation whether youwant to shutdown the computer or not. Depending on confirmation passed by user This program shutdown the computer or exit from executionif user don't want to shutdown computer. Firstly it will asks you
 to shutdown your computer if you press 'y' the  your computer will shutdown in 30 seconds, 


Logic Behind This program


In this program we have used library file that invoked or calls function of  "stdlib.h". This function in stdlib.h lubrary is used to  run an exe file "shutdown.exe" which is availiable in directory path
"C:\WINDOWS\system32"

Windows XP provides numerous options to use or parameters to pass to shutdown.exe 
while executing shutdown.exe 

For Example
  -s option shutdown the computer after 30 seconds

  -t :- This option allows you to specify the time along with shutdown command to specify after how much time computer will be shutdown If you want to shutdown your computre immediately then you canuse  "shutdown -s -t 0"

  Where -s parameter is stands for shutdown it denotes or pass parameter to shutdown.exe file to denotes shutdown.exe that user wants to shutdown this computer

"-t 0"  this denotes we are specifying time so that after that time computer must be shutdown. you can also specify time you want

-r This paramter is used to restart your computer


#include <stdio.h>
#include <stdlib.h>

main()
{
   char ch;

   printf("Do you want to shutdown your computer now )\n");
   printf("Press Y for Yes\n");
   printf("Press N for No\n");
   scanf("%c",&ch);

   if (ch == 'y' || ch == 'Y')
      system("C:\\WINDOWS\\System32\\shutdown -s");

   return 0;
}


C program To Shutdown Computer in Windows 7

#include <stdio.h>
#include <stdlib.h>

main()
{
   char ch;

   printf("Do you want to shutdown your computer now \n");
   printf("Press Y for Yes\n");
   printf("Press N for No\n");
   scanf("%c",&ch);

   if (ch == 'y' || ch == 'Y')
      system("C:\\WINDOWS\\System32\\shutdown /s");

   return 0;
}


C program To Shutdown Computer in Ubuntu


To Run this program in Ubuntu you must be logged in as root user
#include <stdio.h>

int main() {
  system("shutdown -P now");
  return 0;



C Program To Shutdown Restart Logoff and Hibernate Program


The below availibale program can be used to shutdown your computer , to restart, logoff and hibernate you computer using c programming language

#include<stdio.h>
#include<dos.h>
#include<stdlib.h>
#include<conio.h>

void main()
{
int ch;
clrscr();
printf("\n\n------------SHUTDOWN MENU----------------\n");
printf("Press1 For Shutdownn\nPress2 For Restart\n Press3  For Logoff\n Press4  for Hibernate\n5.exit”");
printf("\nEnter Your choice : ");
scanf("%d",&ch);
switch(ch)
{
case 1:system("shutdown -s");
break;
case 2:system("shutdown -r");
break;
case 3:system("shutdown -l");
break;
case 4:system("shutdown -h");
break;
case 5:exit(1);
break;
default:printf("Invalid choice");
}
getch();
}

Happy Coding 

Don't Forget To Share This Post on Social Networks like Facebook , Twitter. Share your questions and how you like this post