Thursday, December 27, 2012

Use of Routing in Asp.net MVC


The basic thing we have to know when we working with MVC .i:e "How to deliver or processing a request in Asp.net MVC".we have dynamic object type  route ,which is used to manage requests.This can deliver request to web forms called web forms routing,wcf services or any other .But in MVC the it will directly send the request directly to controller.To exaplain this process i have choosen a basic Internet application .


In that you will go the App_Start folder ,then select the route config file.The routing file has default collection of mapRoute.Here we can also create our custom mapRoute as per requirement

Wednesday, December 26, 2012

how to create structure of database in sqlserver

Creating other database structure using existing data base using sqlserver is pretty simple compare to other.As you can see the below image ,the existing data base is appeared in sql server.In this example the existing  DB has 15 tables .Now i will place the same structure in to other DB.

To create structure we need to create a script for existing database.For this we have to select the generate script option.Then we can create script as in below


 
 To create a nee DB with this query we need to update the database name with desired DB name.Here i have changed to TestDB1.
                                      

 



Here you can observe the structure of the new database (TestDB1) which is complely similar to the structure of  existing one

Monday, December 24, 2012

methods of thread class in c sharp


Start():- it will start thread execution[Thread is ready for execution ]
Current Thread():- Shared method it will return thread under execution.
Sleep(milliseconds):-shared method iy will halt thread excution for perticular milliseconds
suspend():-It completly halt the thread execution
Resume():-It will state thread execution which is halted using suspend method
Abort():-It will stop thread execution[Killing thread execution]

Priority[property]:- t.Priority =thread Priority.High
                                 thread Priority.Abovenormal
                                 thread Priority.Normal[Default]
                                 thread Priority.BelowNormal
                                 thread Priority.Low
Priority will specify importance/weightage for thread.The thread with high priority will give more cpu cycle

Saturday, December 22, 2012

How to create one-Dimensional array in c#.net


This post will describe the basic concepts of chsarp which is array.
String [] str=new String[4];
In the above i have created two single dimensional array for integers and string.Here the str array size is 5.So we can create five elements from str[0] ...str[4]

Initialization of array:
int[] x=new int[] {1,2,3,4,5};
while initialization of array size is not recommended

Example:A program to print the default values of an array
Place a submit button on a form and add the below code
Button click event
{
int[] x= new int[2];
for(int i=0;i<x.lenght;i++)
{
MessageBox. Show(x[i]+..);
}
}

Thursday, December 20, 2012

Jquery Dropdownlist validation in asp.net

Title: JQuery How to validate Drop Down List value  in asp.net

Description:
Recently i have worked drop down list data validation using JQuery. Now i would like to explain how to validate the data of drop down list using JQuery .In previous articles i have given an example on Jquery drop down validation,JQuery allow only numbers.Here in this post i will given script for Validate DropdownList Using JQuery
Example:
   $(document).ready(function () {
    $('#btnsubmit').click(function(){
        cntydr = $('#ddlcountry');
        if (cntydr.length == 0 || $(cntydr).val() == "") {
            alert("Please Choose Country");
        }
        });
    });
As you can see the below screen shots to know the how they will get validation  conformation on page
In the above script i have used button click event to perform the validation.So when ever we click on the submit button the validations will be done.

Monday, December 17, 2012

Java Script Dropdownlist validation in asp.net

In previous post i have given Dropdownlist validation using jquery.In this post i will show how to perform validation on drop down list using java script in asp.net.Here we have to check whether the select index value of dropdown list is zero or not.Based on that we can do validation on it .
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="DropdownValidation.aspx.cs" Inherits="DropdownValidation" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<title>Dropdown Validation using Jquery</title>
<script language="javascript" type="text/javascript">
function cityValidate() {
var ddlcity = document.getElementById("<%=ddlCity.ClientID %>");
if (ddlcity.selectedIndex <= 0) {
alert('please choose city');
return false;
}
else
return true;
}
</script>
</head>
<body>
<form id="form1" runat="server">
<table><tr><td>First Name:</td><td> <asp:TextBox ID="txtname" runat="server"></asp:TextBox></td></tr>
<tr><td>Last Name:</td><td><asp:TextBox ID="txtlastname" runat="server"></asp:TextBox></td></tr>
<tr><td>Phone:</td><td>  <asp:TextBox ID="txtaddr" runat="server"></asp:TextBox></td></tr>
<tr><td>City</td><td><asp:DropDownList ID="ddlCity" runat="server">
<asp:ListItem Text="Please Select" Value=""></asp:ListItem>
<asp:ListItem Text="Hyderabad" Value="a"></asp:ListItem>
<asp:ListItem Text="Delhi" Value="b"></asp:ListItem>
<asp:ListItem Text="Bombay" Value="c"></asp:ListItem>
<asp:ListItem Text="Chennai" Value="c"></asp:ListItem>
</asp:DropDownList></td></tr></table>
<asp:Button ID="btnvalidate" runat="server" text="submit"  OnClientClick="return cityValidate()"/>
</form>
</body>
</html>
Basic Form
Alert for Dropdown validation
Recently i have seen a question regarding dropdown lists.i:e which is correct in drop down or drop-down?. Every one would provide the answer with comment on this post

Sunday, December 16, 2012

Query to get the rank of student in a class in MYSQL

Based on my requiremnet i need to get the rank of student in million records in SQL database.Initially i just fetch the students records in decending order .Then put it an array in my code and got the result.This method will reduce the application performance.For this i have done complete data filteration in database using below query

SELECT sub_q.* , @rn := @rn + 1 'Rank_id'
FROM
(SELECT * FROM `student` ORDER BY total_marks DESC,DATE DESC) sub_q,(SELECT @rn := 0) r;
In the above query
1.Initialise the variable rn=0
2.The sub query given data of students records in sort order.
3.Here the rn will be incremneted based on the records count(@rn := @rn + 1).

Initial Data:
Existing Data of Database table
Resultant Data:
resultant output

Friday, December 14, 2012

How to set CSS properties only for IE9

Mostly this kind problem occur when working with different browsers.Recently i had struggle with css issue for my application.The problem here  is the image border has default border when load in IE but not in remaining browser.For this i just write CSS for IE browser.
#slider li img {border :none/9}
It can applied to applicaiton CSS when it will be loaded on IE

Tuesday, December 11, 2012

what is satellite assembly in asp.net


Assembly which contains only resources information is called as satellite assembly or "Resource only Assembly"
.net is providing Assembly linker utility (al.exe) to produced sattelite assembly

e:\vb.net al/embedresources my resources.resources/out:rassembly.dll
e:\vbnet92>dir r*.dll

It will produce raseembly.dll,this dll contains resources information.

Sattelite assembly exapmle

Monday, December 10, 2012

How to filter the data in Crystal report


Crystal Report viewer control is providing selection information property
Syntax:CRV.SelectionFormula="Criteria"

Here i will give some examples to filter the data in reports
Query based on numeric
CRV.SelectionFormula="{emp.deptno}=10"
Query based on string
CRV.SelectionFormula="{emp.nob}"="head"
Query based on date
CRV.SelectionFormula="{emp.expDate}"="#11/12/2012#"
We can use operators  >,<,in,like etc to filter the data.

Design of crystal reports

Title: Design of Crystal reports in asp.net

From VS 2008 to current version  providing the crystal report designer for generating reports towards windows form and web form.The applications should provide report generation to make data entry operator job easier.Report is formatted data with proper management.The info can be arranged in diffident section

*Report Header section:The info will be placed with in the first page of report
ex:Company name,logo,date etc
*Page Header Section :The information will be placed with in each page of report at the top
*Group Header Section:This will display grouped column information.It will avoid repetition
ex:display (deptno) only once
*Details section:It will display each record information
*Group footer section: Will display calculated value with respect to grouped columns
ex: sum of sals  w.r.t dept
* Page footer Section:The information will be displayed at the end of page.
ex:One out of count,turn page..etc
*Report footer Section:It will display information at the end of page.
total salary payed for all the emps

Thursday, December 6, 2012

How to remove or cancel onsubmit event in java script

This kind of situation we may get when we work with javascript methods.In my application the dynamic java script onsubmit event has been used to form for validation .Based on requirement i need to add the onclick event on submit button in form.So the problem here is ,when i click on the button the form onsubmit event also fired.Because of that i can't insert the valid data in to data base.
To resolve this i just do the onsubmit function return false.then then will stop that event when i click on button.
function validatecheck()
{
var rad=document.getElementById('OR');
if(radi.checked)
{
var vali=document.getElementById('OT').value;
if(val=="")
{
alert('Please enter value');
document.getElementById('frmres').onsubmit = function() {
return false;
}
}
else
{
document.getElementById('frmres').onsubmit = function() {
return dynamicvalidation();
}
}
}
}

Tuesday, December 4, 2012

Validate textbox based on radio button selection in java script

In this post i will show a simple validation on text box using java script base on radio box selection.Here i have radio button groups which has four radio button.Then the requirement here is ,when we checked the other radio button we should enter the data in to text box.To resolve this just given Id's to both controls and access to through the script.
HTML:
<div>
<table>
<tr>
<td><input type="radio" name="Amt_Num" value="1000"/></td><td>$2,000</td>
</tr>
<tr>
<td><input type="radio" name="Amt_Num" value="500"/></td><td>$300  </td>
</tr>
<tr>
<td><input type="radio" name="Amt_Num" value="450"  /></td><td>$250  </td>
</tr>
<tr>
<td><input type="radio" id="OtherR" name="Amt_Num" value="Other" />
</td><td>Other:</td><td><input type="text" id="OtherT"  name="AmtOther_Num" size="6"/></td>
</tr>
</table>
<input type="submit" id="btnsubmit" value="GetData" onclick="validatetext()"/>
</div>
 
JavaScript:

function validatetext() {
var v = document.getElementById('OtherR');
if (v.checked) {
var t = document.getElementById('OtherT').value;
if (t =="") {
alert('Please enter value in Other');
document.getElementById('OtherT').focus();
} 
}
}
In the above script ,just check the text box data is empty or not.If the text box is empty ,we will display an alert for confirmation.

Monday, December 3, 2012

How to get the data using onclick Event in java script ||Java script onclick event

In this post i would like give an example on Javascript onclick event and How to get the data of text box using java script.In the below one i will write down a onclick event for button ,then get the text box data in it.Here we can a method GetValue which has been using to get the data of input control.
<input type="text" id="txtname"/>
<input type="submit" onclick="GetValue()" value="GetData"/>

//Java script
<script type="text/javascript">
function GetValue() {
  var val=document.getElementById("txtname").value;
alert(val);
 }

</script>

Wednesday, November 28, 2012

Jquery Alert Box

As you can see in the below script, i just have added a jquery plug-in to my application for jquery classes.The jquery /Javascript provides alert box to display the desired data on dialog box.
<script src=http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js></script>
<script type="text/javascript">
    $(document).ready(function () {
        alert('Jquery Alert Box');
    });
</script>
<html>
<head><title>Jquery Alert</title></head>
<body>
</body>
</html>
you can excute the script by the time of page using Doument.ready function

String to DataTable in asp.net using C#.Net

Title:How to bind data table using string array in asp.net using c#

Description:
We have already learnt data binding to data source controls.Now i would like to show how would we use the array list to bind the data to grid view etc.

Examples:
Some  examples for JQuery Auto complete text boxhow to bind or Export CSV data to data table in asp.net.The below example describes the logic of iteration of array list to  data table.In the below i have used a string array to hold the string data and a grid view to display the resultant data of Data table.
<asp:Content ID="HeaderContent" runat="server" ContentPlaceHolderID="HeadContent">
</asp:Content>
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
<asp:GridView ID="GvOrdr" runat="server"></asp:GridView>
</asp:Content>

DataTable dtOrdrName = new DataTable();
dtOrdrName.Columns.Add(new DataColumn("Name", typeof(string)));
string[] strSplitOp = new string[] { "bhaskar", "Siva", "Ram" };
for (int i = 0; i <= strSplitOp.Length - 1; i++)
{
DataRow NewDrow = dtOrdrName.NewRow();
NewDrow["Name"] = strSplitOp[i].ToString();
dtOrdrName.Rows.Add(NewDrow);
}
GvOrdr.DataSource = dtOrdrName;
GvOrdr.DataBind();

Saturday, November 24, 2012

UniqueId and ClientID in asp.net

Here i have given two scenarios to explain those importance in asp.net
In case of a control which is placed in a web form without Master Page:
The Id and Name attribute rendered to the browser are same as Id of control on server and thus the same Id/Name can be used

for programming a control in java script

In case of a control which is placed in a web form with Master Page:

The control Client side Id="<%=ServerofControl.ClientID%>" example:ct100_ContentPlaceHolderId_ServerIdofControl

The control Client side Name="<%=ServerofControl.UniqueID%>" example:ct100$ContentPlaceHolderId$ServerIdofControl

1.Add a text box and HTML button to webform/content page which has been page
<asp:TextBox runat="server" ID="txtwform"/>

<input type="button" value="cbutton" onclick="Show()"/>

2.Add the following to the web form (cphHead isId of ContentPaveHolder added to Head Section of Master Page)
<asp:Content ID="chead" ContentPlaceHolderID="cphead" runat="server">

<script>
function Show()
{
var test=document.<%=Page.Form.ame%>.<%=txtwform.UniqueID%>;
alert(test.value);
}
</scrip>

Thursday, November 22, 2012

How to create object reference in Wpf

The creation of object reference in wpf will be easy when we compare with previous version of XAML.In previous versions we have to declare and binding Element name .In updated XAML we can used X:Reference to create object reference
<Label Target="{Binding ElementName=OId}">OrderId</Label>
<TextBox x:Name="Oid" />

 updated version:
<Label Target="{x:Reference Oid}">OrderId</Label>
<TextBox x:Name="Oid" />
<Label Target="{x:Reference Oname}">OrderName</Label>
<TextBox x:Name="Oname" />
<Label Target="{x:Reference Oslaes}">Sales</Label>
<TextBox x:Name="Osales" />
 
Note:The XAML X:Reference can supported in WPF frame work.In  XAML 2006 we have to use binding to reference the object
 

Wednesday, November 21, 2012

Difference between literal and label control in asp.net

Most of you confused when work these control.Because both controls are used to display the text.But there are some difference between those controls .
Main Difference:
Label control will display text in span tag .So we can apply styles to it.But literal control rendered out only text.Here i will show an example for how they behave in application



Tuesday, November 20, 2012

The ALTER TABLE statement conflicted with the FOREIGN KEY constraint

It Will happen when the primary key Field has null value which has been referenced to child table with foreign key relation.To avoid these kind of errors we need get the records which has null value in parent table.To get those details we need to use the below query .

select  * from Order O LEFT JOIN Sales s on O.Order_Id= s.Order_Id
WHERE s.Order_Id is null

If you are not get any data using this query ,we can solve in other using below queries

Second Method:
First i will get the records  which is not null  using foreign key filed.Then i will check the FK value with PK values .If any FK is referenced to null i will update record with existing PK value
select *from order where order_id is not null
update order  set order_id=4 where order_id=5

 

Jquery UI autocomplete text box in Asp.net

In previous articles we have seen how to develop a Ajax autocomplete text box,Validate Asp.net dropdownlist using Jquery,Get dropdownlist selected value in Jquery,Allow only Numbers to textbox.Here i will show how to create a text box with auto complete using JqueryUI.Whenever use the jquery ,we need to add the jquery reference libraries to our application.In below i have been used jquery libraries(JqueryUI)and css to this task. In jquery i just create a array withe elements,then it will be assign to text box using auto complete .
<link rel="stylesheet" href="http://code.jquery.com/ui/1.9.1/themes/base/jquery-ui.css" />
<script src="http://code.jquery.com/jquery-1.8.2.js"></script>
<script src="http://code.jquery.com/ui/1.9.1/jquery-ui.js"></script>
<script type="text/javascript">
$(function () {
var Keyword_Data = ["Share point","Sharepoint2010","Asp.Net","Asp","Csharp","Dotnet","MVC","MVC4","Jquery","Vb",
"Vb.Net","Sql Server","SQLSERVER 2012","Sliver Light"];
$("#<%= autoc1.ClientID %>").autocomplete({
source: Keyword_Data
});
});
</script>
Aspx:
Autocomplete textbox using jquery
<div>
<form id="UIform2" runat="server">
<asp:label id="tex" runat="server" text="Technology:"></asp:label>
<asp:textbox id="autoc1" runat="server"></asp:textbox>
</form>
</div>

Sunday, November 18, 2012

Machine.Config and web.config


Machine.Config

The config files are used to give the instructions to the web pages,all config files are implemented using XML .using XML files we can give the instructions at the design time as well as at the run time. The machine.config file is web server level any wrong modification having in the machine.config file we Can not execute  any asp.net application

web.config:

Using web.config file we can give programmer defined instructions to the web pages.The web.config file is application level in the web application .We can work with multiple web.config files,when any wrong modifications having in the web.config file we can not execute current application only

Monday, November 12, 2012

How to disable client side validation in sharepoint 2010

The validation controls are used get the right input from users.so i have used four validation controls for four text boxes in my web part.Then i was disable those validation based on page mode on server side.If the mode is display mode i will turn on all the validations on site.To turn on the validations we have to set the EnableClientScript property to false
WebPartManager wpmr = WebPartManager.GetCurrentWebPartManager(Page);
Respose.Write(wpmr.DisplayMode);
if (wpmr.DisplayMode == WebPartManager.EditDisplayMode)
{
ReOrderName.EnableClientScript = false;
RaOrderQuantity.EnableClientScript = false;
ReOrderAmt.EnableClientScript = false;
RaOrderAmt.EnableClientScript = false;
}
else if(wpmr.DisplayMode == WebPartManager.DesignDisplayMode)
{
ReOrderName.EnableClientScript = True;
ReOrderAmt.EnableClientScript = True;
}

Tuesday, October 30, 2012

Set autofocus to textbox in asp.net using HTML5

In previous versions of html we don't have direct property to set the auto focus to desired control.If we want to do this things,we have to use java script ,jquery etc.But the HTML5 provides set of new attributes to make easy such kind of things. Here i will set the auto focus to input control using AUTOFOCUS attribute in HTML5.Below are the examples for both patterns
In asp.net Each control has a method to set the auto focus property.Here tb name is textbox id.
tbname.Focus();
Here i have taken two input controls for name and comments.Then set the autofoucs to name text box.
<html>
<head></head>
<body>
<label for="name">Enter your name : </label> 
<input autofocus="autofocus" type="text" /><br />
<label for="Comment">Enter your comments : </label> 
<input type="textarea" /><br />
</body>
</html>

Monday, October 29, 2012

Dynamically add columns to GridView in asp.net using C#.net

Title:How to create dynamic columns in grid view in asp.net using c#.net

Description:
Up to now we have gone through the data binding concepts like bind data to drop down list in grid view and how to use the link button in grid view.Here i would like to explain how to do customized grid view using c#.net.t.For this the i have created a data table which has three columns and assign the list data to data table using iterations.The resultant grid view can see in the below image

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Add rows Dynamically to grdivew</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:gridview autogeneratecolumns="False" id="DynamicColAddGrid" runat="server">
</asp:gridview>
</div>
</form>
</body>
</html>


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;

public partial class _DynamicCol : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
List<string> li = new List<string>();
li.Add("Bhaskar");
li.Add("Siva");
li.Add("Ram");
li.Add("Venky");
li.Add("Hari");
li.Add("Aru");
li.Add("Srinu");
li.Add("anil");
li.Add("sri");
li.Add("john");
DataTable ddt = new DataTable();
DataRow darow;
DataColumn dc = new DataColumn("Id", typeof(string));
DataColumn dc1 = new DataColumn("Name", typeof(string));
DataColumn dc2 = new DataColumn("FullName", typeof(string));
ddt.Columns.Add(dc);
ddt.Columns.Add(dc1);
ddt.Columns.Add(dc2);
int ditem = 0;
while (ditem < 8)
{
darow = ddt.NewRow();
ddt.Rows.Add(darow);
ddt.Rows[ditem][dc] = ditem.ToString();
ddt.Rows[ditem][dc1] = li[ditem].ToString();
ddt.Rows[ditem][dc2] = li[ditem].ToString();
ditem++;
}    
DynamicColAddGrid.DataSource = ddt;
DynamicColAddGrid.DataBind();  
}
}
Result:

Sunday, October 28, 2012

bind all font name to list box in asp.net using C#.net

In this post i will show how to Display all font name in list box  and based on the selection show the preview in label.To get the font name we have add the name space for Drawing class

Using System.Drawing.Text;
Using System.Collection;

Private void from_load(..)
{
InstalledFontCollection ifcn=new InstalledFontCollection()
IEnumerator ien;
ien=ifcn.Families.GetEnumerator();
While(ien.MoveNext()==true)
{
string si=ien.Current.Tostring();
int i=si.IndexOf("=");
si=si.Substring(i+1);
si=si.Substring(0,si.Lenght-1);
ListBox1.Items.Add(si);
}
}
//list box selected index changed event code
{
String sres=ListBox1.SelectedItem.Tostring();
Lbl.Form=new font(sres,40);
}

Thursday, October 25, 2012

Bind data to gridview using LINQ in asp.net

In previous posts we have seen how to bind the data to gridview and bind data to dropdown in gridview in asp.net.In this post i will given how to bind and filter the data then bind to grid view using LINQ in Asp.net.Here i have placed a button and grid view then get the orders data with linq query.
//add name spaces
System.Data.SqlClient;
System.Linq; 
//button click_event
SqlConnection con=new SqlConnection("User id=sa;password=;Databse=test;server=localhost");
SqlDataAdapet ad=new SqlDataAdapater("Select * from products",con);
Dataset dslq=new Dataset();
da.Fill(ds,"d");
DataTable dtlq=dslq.Tables("d");
Enumerable <DataRow> Edr=dtlq.AsEnumerable();
Queryable <DataRow> EQ=dtlq.AsQueryable();
EQ=From i in EQ where i["ordername"].Tostring=="Computer" select i;
EQ=From i in EQ where int.parse(i["orderid"].Tostring())<5 select i;
GvOrder.DataSourcec=QE.CopyToDataTable();





Tuesday, October 23, 2012

how to create table in database using asp.net


In this post i will show how to create a table in sql server/Oracle data base using Ado.net program.For this  i just placed a button on page and write code for button click event to done this process

//BtnCreate_Click event
{
OledbConnection con=new OledbConnection("user id=scott;password =tiger;provider =msdaora.1");
con.Open();
MessageBox.Show("Con is good"); 
String strcmd="Create table ctr(eno number,Ename varchar(20),sal number(5))";
OledbCommand cmd=New OledbCommand(strcmd,con);
Try
{
cmd.ExcuteNonQuery();
MessageBox.Show("Table is created");
}
Catch(OLEDB exception oe1)
{
MessageBox.Show(oe1.Message);
}

obs:The table ctr has been created in  Oracle Database

Monday, October 22, 2012

Create a service to send a mail automatically in asp.net using c#.net

In previous post i have given an example on how to send a mail with attachment in asp.net.In this post i will show how to create a service to send automatic email every  day.
Open windows service project -->project menu-->add reference -->system.web(required for mail message class)
Place a timer control ,then set the properties for as below
Enable=True
Interval=60000
Using System.Mail;
Time1_elapsed event
{
int sh=DateTime.Now.Hour;
int sm=DataTime.Now.Minute;
if(sh==9 &&sm==10)
{
MailMessage mm=new MailMessage()
mm.To="Test@test.com";
mm.cc="Test@test.com";
mm.Subject="Test";
mm.BodyFormat=MailFormat.HTML;
mm.Body="<h1>Send automatic email</h1>";
mm.From="Test@test.com";
smtpmail.Send(mm);
}
}

Then do the below process:-
1.open the service.cs[Design]
2.Right click on in side of service.cs design-->Add installer
obs:Then two new control will be added
3.service process installer-->right click-->properties-->account=Local system
4.Service Installer --><Right click-->Properties -->service name=P2
5.Build the project(Build-->Build solution)
obs:WS2.exe created under D:c197/ws2/bin/Debug folder with a service called P2

Open .Net command prompt and type as follows ar c:> drive
 Install util -i 197/ws2/bin/debug/ws2.exe

open service(start-->run-->services.msc-->right click on P2-->start

Obs:P2 service will be executed sharp settled time and a mail will be delivered

Saturday, October 20, 2012

Difference between ExecuteNonQuery,ExecuteReader and ExecuteScalar

These three are OLEDB command class methods.Now we will see what is main difference between them
1.ExcuteNonQuery:
This method is required to execute DDL,DML,TCL and stored procedure
2.Execute Reader:
a)This method required to execute select statement
b)This is required while expecting multiple records
c)Execute Reader() returns the records in the format of Data Reader

3.Execute Scalar:
a)This is also required To execute select statement
b)required which expecting a Particular record
c)Execute scalar() returns object
d)Execute Scalar() checks for first match only,If the match is found ,then on first column value of the first record will returned



Difference between Sealed and Partial class in C#.Net

Sealed Class:
1.Sealed is a keyword
2.Sealed class are not inheritable
3.When ever a class is providing full functionality as per the requirements,then that class need to be declared as sealed

Partial class:
1.Partial keyword can be used with classes and interfaces
2.When a class or interface need be written in multiple locations with same name then those class or interfaces need to be partial

Here i will given an example on Partial class
//Open windows form project.Then place a button
//Code in General declaration
Interface test
{
void read();
void print();
}
Partial class testchild:Test
{
public void read()
{
Message.Show("Read");
}
}//testchild
Partial class testchild
{
public void print()
{
Message.Show("print");
}

//Code for button click
{
testchild tc=new testchild();
tc.read();
tc.print();
test t=new test();
t.read();
t.print();
}

Friday, October 19, 2012

User defined exceptions in Asp.net using c#.Net

1.User define exception is a class,which must be inherited from exception class
2.It required based on the projects requirement
3.Syntax to write user defined exception class
class test:exception
{
}
4.User defined exception must be raised with throw keyword
syntax:throw new abc()

Here i will given an example to create user defined exception.I just placed a text box and button on the form

Class salexception:Exception
{
public salexception()
{
Messagebox.Show("sal must be 5K");
}
}//class sql exception
//code for button_click event
try
{
int sal =Int.Parse(txtsal.Text);
if(sal >5000)
Messagebox.Show("ur sal is:"+sal);
else
Throw new Exception ();
}
catch (salexception se)
{
}
}

How to send a Email with html Format in Asp.Net

In previous post we have seen how to send  a mail with attachement.Send a Email with html content can do in two ways.The first One is Creating html page as a body and Create html string as a body .Here i will show how to send the html format using String Builder in asp.net .In the below code i will send the user details to user in valid html format , who are submitting the form .This html string is bind to string builder then assign to email body.The below code have to place in button click event to send mail
Note:We need to set the ISbodyHtml to True For MailMessage properties
System.Text.StringBuilder mailBody = new System.Text.StringBuilder();
mailBody.Append("<b>Name:</b>");
mailBody.Append(Name.Value);
mailBody.Append("<br/>");
mailBody.Append("<b>Location:</b>");
mailBody.Append(Location.Value);
mailBody.Append("<br/>");
mailBody.Append("<b>Date:</b>");
mailBody.Append(Date.Value);
mailBody.Append("<br/>");
mailBody.Append("<b>Phone Number:</b>");
mailBody.Append(Phone.Value);
mailBody.Append("<br/>");
mailBody.Append("<b>City:</b>");
mailBody.Append(City.Value);
mailBody.Append("<br/>");
mailBody.Append("<b>State:</b>");
mailBody.Append(State.Value);
mailBody.Append("<br/>");
mailBody.Append("<b>Zip Code:</b>");
mailBody.Append(Zip.Value);
mailBody.Append("<br/>");
mailBody.Append("<b>Email Address:</b> ");
mailBody.Append(Email.Value);

///////////////////////////////////////Email Sending method//////////////////////////////////////////////////
string sFrom = Email.Value;
SmtpClient SmtpServer = new SmtpClient(SmtpserverName);
SmtpServer.Credentials = new System.Net.NetworkCredential(Username, PWD);
SmtpServer.Port = int.Parse(Port.ToString());
MailMessage objMailMsg = new MailMessage();
objMailMsg.From = new MailAddress("mulebhaskarareddy@gmail.com");
objMailMsg.Body = mailBody.ToString();
objMailMsg.IsBodyHtml = true;
objMailMsg.To.Add(SFrom);
objMailMsg.Subject = "Details of Registration";
SmtpServer.Send(objMailMsg);

 

Wednesday, October 17, 2012

Windows 8 app development tutorials

Windows 8 apps can develop  using different web technologies (Java script,C#,HTML5,Direct X etc).If you develop the apps in Visual Studio,we need to install  Microsoft Visual Studio Express 2012 for Windows 8, Windows 8 (SDK). and also need get the  developer license.

Tutorials:
Windows 8 apps basics
Develop windows 8 app using javascript ,html5 and css
Develop app using .net with c#,WPF
Windows 8 App life cycle
Windows API reference

Tuesday, October 16, 2012

How to Creating an Entity Data Model from a Database in Asp.net MVC 4

In this post i have given how to create an Entity Data Model in MVC4 project. Here i will create Entity Data model on "TestKrihsna" database which contains eight tables.
Steps for creating EDM:
1.Right click -->select add -->new item -->select "data" in installed templates frame-->select the Ado.net entity data model.

2.We have two option to create EDM which are 1.using Data Base 2.Empty Model.Here i will select Generate From data base option to create EDM with existing database
3.Here we have to select the which data base  used for application .Then the connection string has generated as per sql server credentials.
4.We can see in the below screen ,it  has check box options to select which tables,views and procedures to include in model.Here i have select all table for my application then click on next button
5.Finally we can see the browser window which has entity data model(model.edmx) in VS

 Why we are using entity data model? .

Monday, October 15, 2012

How to add external script(JS) on page in sharepoint 2010

Here i will explain how to import the external java script file into specified share point site web page.To add the file reference by using  a class "script link" which will be used to request scripts by the time of page rendered in share point 2010.We will add the reference both client side and sever side to page using this below piece of code.
Client Side:
<SharePoint:ScriptLink ID="sl" name="/_layouts/Jscripts/testadd.js" runat="server" Defer="false"/>
Server Side:
By using the below method we can access script on server side.The Register method contains the there variable which are page name,script file name and localizable value .
ScriptLink.Register(this.Page, "/_layouts/Jscripts/testadd.js", false);

 

Sunday, October 14, 2012

Required and compare Validations in Asp.net MVC4

I have created a registration form  for my application,then placed some validation for user inputs based on requirement.In asp.net we have to use validation controls to implement validations.In Asp.Net MVC System.ComponentModel.DataAnnotations name space has been included to get the validation class to perform validations on it.The below code has done for required validation for user name and compare validation for password field

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;
using System.Web.Mvc;
 
namespace TestApp.Models
{
public class RegisterModel
{
public int Id { get; set; }
[Required]
public string UserName { get; set; }
[StringLength(100,ErrorMessage="Password must have 5 characters at least",MinimumLength=5)]
[Required] 
[DataType(DataType.Password)]
public string Password { get; set; }
[Compare("Password", ErrorMessage = "The password and confirmation password do not match.")]
public string ConfirmPassword { get; set; }
}
}

There is one more validation  i have done i:e String-length validation on user name.This can make the password minimum length to "5"

Saturday, October 13, 2012

Difference between TCP channel and HTTP channel

TCP ChannelHTTP channel
Streambinary standard streamXML based stream
FormatCompressed formatText format
memoryconsume less memoryconsume Huge memory
CommunicationFastslow
platformsSupport homogeneoushomo and hetero geneous
Networksupports normal networksupport both normal and Internet

Friday, October 12, 2012

How to read XML file data in sharepoint 2010

 
In this post i have given code for how to read  the XML file data which in document library .Here i instantiated a Web Request object by using the path(URI) of the XML file ,then get the Response from path using Web Response class.The GetResponseStream method  is used to get the stream of  content in XML file to stream.Finally we will read the stream into resultant string.By doing the same process we can access any external XML file(URI) into application.But we have to use HttpwebRequest class to make request.
String file_path = "http://sp12/test"
WebRequest wr = WebRequest.Create(file_path);
wr.Credentials = CredentialCache.DefaultCredentials;
WebResponse Wresponse = wr.GetResponse();
using (StreamReader str = new StreamReader(Wresponse.GetResponseStream()))
{
String Result_Data =str.ReadToEnd();
}
Response.Close();

Thursday, October 11, 2012

How to Get Last updated /Inserted records from the table in sql server

How could you solve if you had a big problem with data base when insert the huge amount of duplicate records into table ?The same situation i have faced recently.by the time i  simply makes the insertion process for that bulk records.But later on i got a trouble  with those records .For this i want to checked out to display the recent insertion data from table.In the  below query i have used date function and length function to get the last updated records which are  greater than current date minus 5 (last five days) and length of header is greater than 4
select * from order
where len(order_head)<=4
and (inactive_date is not mull or inactive_date > getdate()-5)
and order_head is not null
and order_code like 'SAT%'
Finally all redundant insertion records has been deleted for last five days using the below query
Delete order
where len(order_head)<=4
and (inactive_date is not mull or inactive_date > getdate()-5)

Wednesday, October 10, 2012

How to convert the Date/Number to string in sql server 2012

The new version(2012) of sql server makes easy to string conversion from number or date.We don't have any direct  function to do this one in older versions .If we want to do this one ,then we have to use Conversion functions(CAST or CONVERT).
SELECT CAST(date AS nvarchar(100)) AS string_date from Orders
The FORMAT string function has introduced to convert the number/date to string in Sql server 2012 .Here i have given a simple query to get the amount(It has money data type in table)  in currency format.
SELECT order_ID,FORMAT(Price_Amt, 'C', 'en-us') AS 'Amount' from Orders
In this function we  have to use standard numeric formats for desired Format ..Details about standard Numeric Format Strings

Tuesday, October 9, 2012

How to insert data from view to table in sql server

Recently i have work with large database for data insertion which is from "excel sheet".For this first I will export data from  excel sheet to data table,then  "create view" (test_orders)which has data based on where condition.
insert into orders(ordr_code,ordr_desc,ordr_code,price_amt)
select [Title ID] ,Name,replace(ORDERCODE,'-',''),[List Price] from [test_orders]
In the above first i have select the data from view then insert into desired table.Here i have done string replacement for one column when fetch the data from view

Monday, October 8, 2012

Get current user Profile in SharePoint 2010

Earlier i have given a customised solution to get the current user permissions in share point 2010.Here i will show how to get the user details from share point site using  UserProfileManager class.Before going to get the profile details we need to check whether the user is valid or not.Then the resultant data will be assigned to user profile class and get account name into string

SPSite sps = SPContext.Current.Site;
using (SPWeb spw = sps.OpenWeb())
{
SPServiceContext spsc = SPServiceContext.GetContext(sps);
UserProfileManager uprofile = new UserProfileManager(spsc);
string useraccountname = SPContext.Current.Web.CurrentUser.LoginName;
if (uprofile.UserExists(useraccountname))
{
UserProfile Profileinfo = uprofile.GetUserProfile(useraccountname);
if (!string.IsNullOrEmpty(Profileinfo["FirstName"].ToString()))
{
string AccountName = userProfile["FirstName"].ToString();
}
}
}

Friday, October 5, 2012

How read data from List in sharepoint 2010

In previous posts i have given how to read data from the excel file in document library.Here i have given a customised code to read the data from share point list. In the below code we are first get the data(ordername,orderamount,orderarea) from "orders" list using QAMLquery .Then the resultant data in to list item collection and read the each values through loop condition
SPList spl =SPContext.Current.Web.Lists.TryGetList("Orders");
SPQuery spq = new SPQuery();
spq.ViewFields =string.Concat("<FieldRef Name='OrderName' />","<FieldRef Name='OrderAmount' />","<FieldRef Name='OrderArea' />");
SPListItemCollection splc = spl.GetItems(spq);
foreach(SPListItem sitem in splc){
if(sitem != null)
{
Oname = item["OrderName"].ToString(); 
Oamt = item["OrderAmount"];
Oarea = item["OrderArea"];
}

I have used condition to check whether the list item(sitem) is null or not.Because the variables (oname and etc) has used in another method  here .

Thursday, October 4, 2012

How to concatenate strings in sql server 2012

In previous versions there is no direct function to make this one.If we want concatenate two strings we have to use '+' symbol .
But in the latest version of sql server2012 introduce a new string function "CONCAT()" ,which is used to concatenate the strings.Let me explain one example for how to use and execute this function in sql server 2012.
Here i have table with three five columns(id,name,sal,surname,add).Now i want to concatenate the name and surname when executes the select query from emp table

select id,CONCAT(name,surname) as FullName from employee

Monday, October 1, 2012

How to add images/files to document library in sharepoint 2010

In previous post we have seen how to get the updated items from the document library and read the excel file data from document library.Here i will shown how to add the image files to document library/List .For this i have been converted  the attachment file to string format then get the size using some length and memory of this.Then using document  library class the result Data has added to library after check in .
XPathNavigator dX = MainDataSource.CreateNavigator();
XPathNavigator XN = fileAttach.Current;
byte[] converted_attachment = Convert.FromBase64String(XN.ToString());
double filelength= converted_attachment.Length;
double memoryb = 2048 * 2048;
double resultfSize = filelength / memoryb;
if (resultfSize < 8 && resultfSize != 0)
{
int fln = converted_attachement[32] * 2;
byte[] fb = new byte[fln];
for (int i = 0; i < fb.Length; i++)
{
fb[i] = converted_attachement[24 + i];
}
string[] filenameparameter = System.Text.UnicodeEncoding.Unicode.GetChars(fb);
string ResultfName = new string(Filenameparameter);                            
byte[] Result_Data = new byte[converted_attachement.Length - (24 + fln)];
for (int i = 0; i < Result_Data.Length; i++)
{
Result_Data[i] = converted_attachement[24 + fln + i];
}
}
SPDocumentLibrary dl = (SPDocumentLibrary)Web.GetList(Site.ServerRelativeUrl + "/DesiredLibraryName");
SPFolder spfolder = dl.RootFolder;
SPFileCollection spf = spfolder.Files;
SPFile sf = spf.Add(spfolder.Url + "/" + DateTime.Now, Result_Data);
SPListItem spf_item = sf.Item;
spfitem["Filename"] = resultfName;
spfitem.Update();
spfitem.File.CheckIn("WF CheckIn", SPCheckinType.MajorCheckIn);


Friday, September 28, 2012

Complete Details about session state management in Asp.net

Title:State management in asp.net

Description And Explanation:
The session setting provide following options:
1.Session mode
2.cookie less session
3.session timeout
4.optimisation of session
session mode:
It will specify when the session to be maintained.Asp.net is providing different types of session modes
1.State server session
2.SQL server session
3.In process session[default]
4.Custom session[Requires manual coding]
In process session[Process dependent session]:
session maintained with in website app domain under works process is called "In process session" or process dependent session.This produce come with two problems
1.No reliability:Restoring website with erase sessions[saving web.config or restarting web server will restart website]
2.No solution for web forming
Web forming:It is running different websites on different web services as a one unit,This is implemented for load balancing
In web forming single session can not be maintained fore client
Process Independent session
In session maintained outside of website external to under process calls process independent".the external process to maintain session can be
1.State server
2.Sql server
Database server session:
This requires following steps
* start state server:State server comes with .net installation in the form of windows service
start --->run-->services.msc
then select asp.net state server --->right click and select start--->state server will be started to maintain
Configure website to state server for maintaining session
Go to application web.config file
<system.web>
<session state mode="state server" state connection string="tcp/ip= 127.0.0.1:2424">
</system.web>

Note:state connection string requires IP address of system in which state server is running and port number of state server
TcpIp=Ipadress:port number
Note:State server will support in memory storage,data will be lost will state server is restarted and backup can not be maintained.When reg is move reliability go with sql server

Sql server session:
Sql server supports persistent storage in the form of table,This provide mode reliability with more financial investment and requires more processing
This requires following steps
*continue sqlserver with table to maintain session
.net is providing asp.net -regsql.exe utility
VS2010 command prompt-->asp.net -regsql -u "sa" -p "" -ssadd -sstype "c" -d "test"
It will place table into sql server
Configure website to maintain session with sql server
<system.web>
<session state mode="SQLserver"  sqlconnection string="user=sa;password="" database="test" allow customDatabse="true">
</system.web>

Note:Sql server agent will maintain Job to monitor session when timeout occurs  it will delete sessions
Cookie less session:
By default session ID wll be given to browser in the form of in memory Cookie,if the browser disabled cookies session can not be maintained
The solution is cookieless session providing session Id to client Browser by appending to URL is called cookies less session.
<sessionstate cookieless="usecookies
                                         useurl
                                        useDeviceProfile
                                        autoDetect
                                        true
                                        false" time out=""
</session state>
Use Cookies:will provide session id in the form of cookies
Use URL will provide session Id by
Use Device Profile:Session will be given based on requested device in the form cookies
Auto Detect:It is similar to use device profile.It will verify device browser enabled cookies
True:It is similar to use URL
False:It is similar to use cookies

Wednesday, September 26, 2012

how to get duplicate records from a table in sql server


When i insert the bulk amount data from one table into another table i got problem with existing data.Here in the "products" table the "prod_code" column has already some data of import table(sales_import).For this i have checked the count of redundant(already exists) data in existing table.In this post i have given a query to get the existing data(products) in the table compare to import table(sales_import).
select count(*) from products a where exists
(
 select  1 from [sale_Import] b where a.prod_code = b.[Title ID]
)

If you want to get tha data you have to use * instead of count(*)

Monday, September 24, 2012

how to Passing parameters into a Modal Dialog Window in sharepoin 2010

The share point provide a class for crating modal dialog box i:e SP.UI.ModalDialog.Here i have given an example to create a dialog box for account result by using parameters.The parameter will be assign using args property

function ResultDialog() {
var options = {url: 'Account/Reports.aspx', autoSize: true,title:' 
args: { amt: 'Amt_Tot', category: 'sales' },dialogReturnValueCallback: Result
};
SP.UI.ModalDialog.showModalDialog(options);

}
For the above model dialog box i passed two arguments to display the sales amount regarding order.The reports.aspx has hold the resultant output ,so i dialog box url set to this page here.

Wednesday, September 19, 2012

Optimisation of Session in asp.net

Optimisation of session is arranging session in a proper manner to improve performance of the web server.The optimisation can be applied at 2 levels
1.Page Level
2.Website Level

PageLevel:
In the page level optimisation requires enable session state option with page directive
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default2.aspx.cs" Inherits="Default2"  EnableSessionState="true"%> 


It has three properties i:e
True:Session tracking takes place ,program with be loaded for reading and writing
False:No session tracking,this will reduce processing burden on server
Read Only:Session tracking program loaded for reading,this will reduce burden compare to true

WebSite Level:Website level optimisation requires settings under web.config
<Sessionstate mode="off"/>

This will in form web server not to create sessions for website.This will reduce processing burden on web server and memory wasted will not take place

Sunday, September 16, 2012

redirect to another domain without the url changing || Redirect to another domain using URL Rewriting

This post will describes how to use Url rewriting concept to redirect and rewrite the url in asp.net applications.In URL rewriting we can use regular expression to check the conditions based on requirement.Here i have given a rule for redirect to other domain  when loading specific page in the website which has different domain names.Then the application redirect to "mydomaintest" domain home page when "home-live.aspx" will loaded.
<rule name="MBR-Enterprises" stopProcessing="true">
<match url="^home-live-(.*)$" />
<conditions>
<add input ="{HTTP_HOST}" pattern ="www\.mydomain\.com"  />
</conditions>
<action type="Redirect" url="http://www.mytestapp.com/home-live-{R:1}" redirectType="Permanent" appendQueryString="false" />
</rule>
Redirect to another domain using domain Name:
Here we have to check only the domain name to redirect to desired domain
<rule name="MBR-Enterprises" stopProcessing="true">
<match url="^$" />
<conditions>
<add input ="{HTTP_HOST}" pattern ="www.myapp.com"  />
</conditions>
<action type="Redirect" url="http://www.mytestapp.com" redirectType="Permanent" appendQueryString="false" />
</rule>

Wednesday, September 12, 2012

Import Excel data into SQL Server

.In previous post i have given Import excel data to sqlserver,Export grdivew to excel .There are couple of ways(Copy and paste,Import) to save or insert the data into sql server table from excel sheet .Here i would like show how to import the data form excel sheet to sql server using sql server tasks.This is the way we can save excel data into database
When make a selection of Import for data base we will get a popup window which is used to import/Export data in sql server database

Then we have to select data source type and path of the file using the option in wizard.Here i was select Excel Sheet as data source

Here the destination data source has selected using server credentials Then click on the next button until the Wizard process completed.The below screen shots will show the complete process.





Here we can see the DVD data table which has been created using Excel sheet

Sunday, September 9, 2012

common language runtime in .Net

CLR is the run time environment in which .net application are executed CLR forms as a layer on top of the OS providing its services between .net application of OS.CLR contains several components in its architecture
1.Class Loader
2.Code Manager
3.Garbage Collector
4.Security Manager
5.Exception Manager
6.Thread Manager
7.Just time Compiler

Class Loader:
It is the provider for verify the class libraries refereed by the .net application and load all those class libraries into memory to make them available for .application

Code Manager:
In .net The code manager is responsible for loading .net application code into memory and managing until the .net application was closed.Dot net application code is classified into

1.Managed Code:The .net code that is executed by code manager is called as Managed code
2.Unmanaged Code:The .net code that is not executed by code manager is called as Managed code

Garbage Collector:
This is responsible for memory management for the .net application.When you create variables and objects in the program then allocates memory for them and De-allocating memory when their lifetime is expired is the responsibility of Garbage Collector

Security Manager:
In .net you can provide the security either by using role based security or code access security .When you provide security by using either of this then verifying the security and executing the security related code is the responsibility of security manager role based security provides the security based on the roles available in OS and code access security provides the security completely based on the own code



Exception Manager:
It is responsible for verifying whether there is any possibility for exception,raise the exception .If there is possibility,verify whether exception handling code is provided and executing is providing and otherwise terminate the program abnormal


Thread Manager:Executing multiple tasks at a time is called as multitasking .To implement multitasking you need to create threads with in the application.When you create threads within the .net application for implementing multitasking executing those threads is the responsibility of thread manager

Wednesday, September 5, 2012

Jquery LightBox example Using CSS

Title: JQuery LightBox Example And Plugin

Description:
In this post i will given how to create light box for image,content etc using jquery with CSS. We can also use JQuery light box plugin to do this kind of light box overlay.But here i just use simple jquery functions and some css properties to make light box.In the below example when we click on the image ,it will be display in light box as in below images.In this way we can create jquery lightbox using css and jquery


<asp:Content ID="HeaderContent" runat="server" ContentPlaceHolderID="HeadContent">
<script type="text/javascript" src="Scripts/jquery-1.4.1.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$("a#Main").click(function () {
$("#lbDiv").show();
})
$("a#Sub").click(function () {
$("#lbDiv").hide();
})
})
</script>
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" Runat="Server">
<a id="Main" href="#"><img src="Styles/munnar1.jpg" /></a>
<div id="lbDiv">
<h4>Munnar</h4>
<img src="Styles/munnar.png" style="margin-left:45px;" />
<p align="center">
<a id="Sub" href="#"><img src="Styles/images.jpg" /></a>
</p>
</div>
</asp:Content>
CSS for Div:
 #lbDiv {
 display:none;
 position:fixed;
 background:#CFFCCC;
 padding:10px 15px 10px 15px;
 top:150px;
 left:50%;
 margin-left:-250px;
 width:400px;
 z-index:999;
}


For Jquery Light Box Library Click on this

Bel