Thursday, May 31, 2012

client object model in sharepoint 2010

The ClientObjectModel is used to develop the client side applications and it can only work on client side and used to  access the  share point server.This is the core advantage for developer to work easily  on the share point
1) From the browser ,using JavaScript(ECMASscript) object model
2)Using the .NET framework (no lesser that .NET framework 3.5),Managed .net client object model
3)Silver light object model.
Managed .net client object model:It can only access the share point server to .net application .Using this object model we can do all list modifications in COM and authentication for application.To run the managed .nee client object model we need to add the below libraries into applications.
JavaScript(ECMAScript) Client object model:We can not use this COM in  .net applications and can not access the data from  other share point sites.We have to add the sp.js file

Silver light Client object model:In share point 2007 we don't have an option to integrate silver light application to share point.In share point 2010 we can integrate silver light application into share point application.
These three COM's  acts as a subset of the server object model which is defined  in Microsoft sharepoint dll ,which includes the objects at site collection level or lower that is defined in the share point hierarchy. In order to improve the security and performance of the application client object model focus on the relevant COM's for the client side development ,hence limiting the size of client libraries which reduces the time of downloading in the context of ECMASCRIPT and Silver light Applications.
These Object models provide consistency and easy to use ,object oriented system to connect between the share point and the remote client or server.These type of services are mainly countable in the context of Microsoft  Business Connectivity  Services.
These Models are implements as a part of Windows Communication Foundation Service ,but uses web bindings to implement efficient request batching.All the operations are serialized using XML and are sent to server using a single HTTP request and the server returns the request in the request client object model notation respectively with appropriate object .

Wednesday, May 30, 2012

Find list of primary keys in a database in sql server

Here i will show how to get the all list of existing primary key field's in data base in sqlserver.For this i have write a simple sql query to get constraint in tables.Here i have three table which are emp,Department,city.

Sql query:
USE [Test Krishna]




Tuesday, May 29, 2012

How to use ProcessBatchData method in sharepoint

Here i want to deleting a list item from list.For this there is method PBD in sharepoint which is used to send the commands like save,delete. to server based on transaction.It can send multiple command at a time to server.I will give a simple example to delete the Xml  data of list using this method.For this i have passed the static values to xml data and delete command will be send to server
using(SPSite ss = new SPSite("site url"))
using(SPWeb sW = spSite.OpenWeb())
sbd,Append("<ows:batch onerror="\&quot;Continue\&quot;">)
sbd.Append("<setvar name="\&quot;ID\&quot;">" + 45 + "</setvar>");
sbd.Append("<setvar name="\&quot;Cmd\&quot;">Delete</setvar>");
sbd.Append("<setvar name="owsfileref">/mysite/files/documentss/testfile.txt</setvar>")
sbd.Append("<setvar name="owshiddenmodstatus">1</setvar>");

Monday, May 28, 2012

how to create a custom webpart in sharepoint 2010

Title:How to create a custom web part in share point 2010

In previous post we known how to create and filter the list in SharePoint.Here i will show how to create a custom web part in share point 2010.For this i will use a class SPWebPartCollection to get the existing web parts in page ,then add a new web part to page by creating object for web part.we have two chrome state is Minimized which can do the border in minimized state and other one is none which gives the normal state  .Chrome type property has for attributes .those are Title only which give only title bar,Border only which gives only border,Title And Border which give both title and border .None which give no one .After set the properties we can add the custom web part to web part list sing add() method

if(inplist!=null && set!=null)
using (SPSite ss = new SPSite(URL) 
using (SPWeb sW = ss.OpenWeb())   
SPWebPartCollection webpartscollection = sw.GetWebPartCollection(pagrurl,Storage.Shared);      
WebPartToBeAdded wptest = new WebPartToBeAdded();      
wptest.ZoneID = "zoneid";     
wptest.Title = "My first webpart";
wptest.ChromeState = System.Web.UI.WebControls.WebParts.PartChromeState.Minimized;
wptest.ChromeType = System.Web.UI.WebControls.WebParts.PartChromeType.TitleAndBorder;  

Sunday, May 27, 2012

how to get the content type id in sharepoint 2010

Here in this post we will describe how to get content type id in share point.The Content type ID is used for identify the content type and which hold the parent parent content type.Using this one we can get the child content id and inherit the content types from parent to child.
using (SPSite ssite = new SPSite(url))
{using (SPWeb sweb = ssite.OpenWeb())
{SPContentTypeId scontnentId = SPBuiltInContentTypeId.Document;
foreach (SPList slist in sweb.Lists)
{SPContentTypeId cId = slist.ContentTypes.BestMatch(scontentId);
if (scontentId.IsParentOf(cId))

Sql Server:How to reverse a string

Here i will show how to reverse a string using sql function.There is a function "REVERSE" is used to done this task in sql.I declared a string "mystring" then pass the value "bhaskar" to it .The output after will like "raksahb
DECLARE @mystring varchar(50)
SET mystring="Bhaskar"
SELECT REVERSE (@mystring) as ReversedString

Saturday, May 26, 2012

How to delete a file in sharepoint 2010

Here i will give an simple code for how to delete a file in sharepoint2010.For this i got the all files in existing list then delete a file using file index in list of files.
ClientContext clc = new ClientContext(url);
Web w = clc.Web;
List li = w.Lists.GetByTitle("City");
var files = li.RootFolder.Files;
FileCollection fc =files;
File Deleteitemfile = fc[3];          

Get Images from folder and generate HTML anchor in

Here i will show how to get the image from folder then create a anchor link to that image and assigned to string builder "sb".."sPhysicalPath" is the path of gallery folder.The class Directory Info is used to get the all the image files from the folder
public static string BindImages(int images, bool isRedirecting)
string thumbNailFolderName = ConfigurationManager.AppSettings["ThumbFolder"];
string previewFolderName = ConfigurationManager.AppSettings["PreviewFolder"];
StringBuilder sb = new StringBuilder("");
string format = "<span><a href=\"{0}\" title=\"\"><img alt=\"\" src=\"{1}\" /></a></span>";string sPhysicalPath = HttpContext.Current.Server.MapPath(ConfigurationManager.AppSettings["GalleryFolder"]);
DirectoryInfo oDir = new DirectoryInfo(sPhysicalPath);
FileInfo[] oFiles = oDir.GetFiles();
int i = 0;
foreach (FileInfo oFile in oFiles)
sb.AppendFormat(format, (isRedirecting ? "Gallery.aspx" : "school/gallery/" + previewFolderName + "/" + oFile.Name),
"school/gallery/" + thumbNailFolderName + "/" + oFile.Name);
if (i == images && images != 0)
return sb.ToString();

Friday, May 25, 2012

BInd data to dropdownlist in gridview in

Title: How to bind data to drop down list in using

In previous posts i explained bind data to grid view,bind data to dropdownlist,Bind drop down in MVC4.Bind grid view using LINQ. Here i will show how to binding the data to Drop down List inside of Grid View.Here the dropdownlist has place inside of grid view template Field .You can observe here i will bind data to both drop down and grid view While loading page.

<html xmlns="" >
<title>Bind data to Dropdownlist in gridview in</title>
<form id="form1" runat="server">
<asp:GridView ID="GvSalesData" AllowSorting="True" Runat="server"
AllowPaging="true" AutoGenerateColumns="False" >
<asp:TemplateField HeaderText="SalesID">
 <%#Eval("SID")  %>
<asp:TemplateField HeaderText="SalesPName">
<%#Eval("SalesPersonName")  %>
 <asp:TemplateField HeaderText="Samount">
<%#Eval("Samt")  %>
<asp:TemplateField HeaderText="SalesCity">
<asp:DropDownList ID="ddl_city" runat="server">
Code behind:
using System;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Data.SqlClient;

public partial class Dropdowningridview : System.Web.UI.Page
SqlConnection cn = new SqlConnection(ConfigurationManager.ConnectionStrings["bhaskarconnection"].Tostring());

protected void Page_Load(object sender, EventArgs e)
//Bind data to gridview
//Bind data to Dropdown in gridview
private void BindOrdrGrid()
 SqlDataAdapter Ordr_ad = new SqlDataAdapter("select * from Order_details", cn);
 DataSet Ordr_ds = new DataSet();
 Ordr_adp.Fill(Ordr_ds, "Order_details");
 GvSalesData.DataSource = Ordr_ds;
private void BindDropdownGrid()
SqlDataAdapter Ddl_ad = new SqlDataAdapter("select * from order_city", cn);
DataSet Ddl_ds = new DataSet();
ad.Fill(Ddl_ds, "order_city");
foreach (GridViewRow row in GvSalesData.Rows)
DropDownList _ddlcity = (DropDownList)(GvSalesData.Rows[row.RowIndex].Cells[4].FindControl("ddl_city"));
_ddlcity.DataSource = Ddl_ds;
_ddlcity.DataValueField = "CID";
_ddlcity.DataTextField = "City_name";

Thursday, May 24, 2012

How to Convert SQL Table Data To XML Format in sqlserver

Here i will show how to get the xml output from sql data table.For this we can use FOR XML AUTO statement.The AUTO is one of mode of FOR XML.This sql statement get the emp table data ,then convert in to xml.This can be see in the black rectangle in below screen shot.
Query: select*from emp FOR XML auto

Wednesday, May 23, 2012

How to get random number and string in

Here i will show how to get the random  text from given user input in method GetRandomTextKey() has taken the length as parameter.The logic"minValue + rndValue * randomRange" has used to generate a random provide a class which Rnadom is used in this process
 public static string GetRandomTextKey(int length)
        Random rnd = new Random((int)System.DateTime.Now.Ticks);
        System.Text.StringBuilder randomText = new

        int minValue = 65;
        int maxValue = 90;
        int randomRange = maxValue - minValue;

        double rndValue;
        for (int i = 0; i < length; i++)
            rndValue = rnd.NextDouble();
            randomText.Append((char)(minValue + rndValue * randomRange));

        return randomText.ToString();

Jquery keypress,onclick event in sharepoint 2010

Here i will show how to how to use the j query events like key press and on click events in share point.The below peace of code i have used to get the event.i just used two functions one is for key press events and other one is for click event.The main thing here is we should add the j query library to share point application
script><script type="text/javascript">
$('#ctl00_inputTextField').keypress(function() {
function getdata()
alert("key press event");

function clickfunction(event) {
alert('click event');

Tuesday, May 22, 2012

sql server:how to create a foreign key relationship

Here i will show how to create a foreign  key relation between two tables in server.The parent table must have the primary key field when we will giving the foreign key with child table.For this we have to right click on the child table ,select relationships then  we will get a pop like as in screen.In this pop up we have an option "Table and column specification" ,,then we have to select circled option  which is right to blue color field.
We will get an option to select which  tables has to be involved in  foreign key relation as in below screen.Here the emp ,table_3 are table's are used
 The ID is the primary key field in emp table is foreign key relation with id in table_3 table.we can see this process as in below 2 images

After all process has done ,we can see the which table and columns are involved in this relationships

Monday, May 21, 2012

How to programmatically download file from sharepoint

  Here i will show how to get the documents from share point site.For this we can use path of document to download or to do any file operation in folder.The below example has the path of the url of document(testfilename) i:e".If you  what to get the data we should use the web client class.For this we have to add the System.Net.Web Client name space
WebClient webc = new WebClient();
webc.UseDefaultCredentials = true;
byte[] testbytedata = webc.DownloadData(path);
FileStream fst = new FileStream(testfilename, FileMode.Create, FileAccess.ReadWrite);
BinaryWriter biw = new BinaryWriter(fst);

create custom list view and filter the list data in sharepoint 2010

SharePoint has one of the best feature i:e we can  create a custom  view for list.Basically the view can used to display the user tasks based on the login in share point and we can filter the list data using as our filter condition.Here i will show how to create a view for subjects list and filter the data as per author
using (SPSite Site = new SPSite(url))
using (SPWeb sWeb = Site.OpenWeb())
SPList sList = sWeb.Lists["subjects"];
SPViewCollection sViewCollection = sList.Views;
string testViewName = "TestView";
System.Collections.Specialized.StringCollection testviewFields = new System.Collections.Specialized.StringCollection();
string spquery = "<query><where><eq><fieldref name="\"Name\"/">" +
                    "<value type="\"author\"/">Testview</value></fieldref></eq></where></query>";
sViewCollection.Add(testViewName, testviewFields, spquery, 100, true, false);

Grid view row data bound event in

Here I will show how to do RowDataBound event in grid view in this I have given a simple example which is bind the percentage data to label in grid view.
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" Width="100%" OnRowDataBound="GridView1_RowDataBound">
<asp:TemplateField HeaderText="Student Id">
<asp:Label ID="lblstudentid" runat="server" Text='<%#Eval("StudentID") %>'></asp:Label>
<asp:TemplateField HeaderText="Student Name">
<asp:Label ID="lblstudentname" runat="server" Text='<%#Eval("Name") %>'></asp:Label>
<asp:TemplateField HeaderText="Total">
<asp:Label ID="lblTotal" runat="server" Text='<%#Eval("total")%>'></asp:Label>
<asp:TemplateField HeaderText="Percentage">
<asp:Label ID="lblPercentage" runat="server"></asp:Label>
 protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
 if (e.Row.RowType == DataControlRowType.DataRow)
 Label lblPercentage = (Label)e.Row.FindControl("lblPercentage");
 Label lblTotal = (Label)e.Row.FindControl("lblTotal");
 if (total > 0)
 float percentage = float.Parse(lblTotal.Text) / total;
 percentage = percentage * 100;
 lblPercentage.Text = percentage.ToString();
 lblPercentage.Text = "0";

Sunday, May 20, 2012

how to use XmlDataSource in

Here i will show how to use xml as the data source for user information.
1.For this create an XML file using add new item and enter user information with required columns inside it
2.Got o data layer and write a method to search data in the created XML file and return true or false
3.Go to login page and in logiin button check for credentials using data layer but they time passing XML file as the option.We can write login's event to check in data base or xml.
Add-->newitem-->xml file ->create user.xml
</userInfo>Add-->newitem-->xml file ->create user.xml

Then in app_code go to data layer
public Datalayer()
public static bool validateuser(string username,string pwd,string loc)
Dataset ds=New Dataset();
DataRow[] recs=ds.Tables[0].select("username="'+uname+'" and password"'+pwd+'"";
trturn true;
return false;
in web.config
<add key="loginsrc" value="XML"/>

sign in code behind
bool found;
lbl.text="Invalid username and password"l

Saturday, May 19, 2012

How to use Multiview in

Multi view is a such intrinsic control and it is collection of views.A multi view can not have any control.A multi view can have view multi view by default not show any view. multi view can display only single view.All views can share the content declared in the page because they all belong to single page only

Here i will show how to use by placing 3 buttons/link buttons and multi view in the page.Then place the views inside the multi view control and place required controls inside views
protected void buttin1_click()
MultiView1.ActiveViewIndex =0;
protected void buttin2_click()
MultiView1.ActiveViewIndex =1;
protected void buttin3_click()
MultiView1.ActiveViewIndex =2;

Friday, May 18, 2012

How to use view state in

View state provides page level state management i:e as long as user is in current page state is maintained,as redirected to new page the current page state is lost  and new page state is started .view state can store any type of data   .It is not preferred to store complex type of data as it has to undergo serialization and serialisation every time
View state data is not secured it is simply encoded in  base64 format and because of which is not readable.Any how view state related configuration settings and some properties are available to make the data encrypt/secured
-->View state falls in client state management because no load or values are stored with server
//button_click event
ds=DataHelper.GetData("elect*from emp");
ds=DataHelper.GetData("elect*from emp");

Thursday, May 17, 2012

Passport authentication in

This is third party authentication method.In this method we ask users to get authentication from Microsoft third party Service oriented website that is following steps are perform during passport authentication
1.user makes a request to secured web page
2.IIS allowed user as anonymous checks for passport identity and redirects the user to passport website
4.passport displays login page where user should enter passport registered details
5.passport checks for credentials and creates an identity called passport ticket. This ticket is redirected to user
6.user along with ticket requests secured page and is allowed as anonymous and this time also allowed because of passport identity

Wednesday, May 16, 2012

how to execute sql query in c sharp

Here i will show how to Excute the sql query in sql server using c#. For this I will use one method with two parameters which are database connection string and file name.Then read the text in file and passed to string array.Finally we will execute the query using sqlcommand

public void executeSqlfileincsharp(string connectionStringName, string executesqlFileName)
string sqlConnectionString = ConfigurationManager.ConnectionStrings[connectionStringName].ToString();
FileInfo file = new FileInfo(executesqlFileName);
string sqlString = file.OpenText().ReadToEnd();
using (SqlConnection mySqlConnection = new SqlConnection(sqlConnectionString))
string[] spliter = { Environment.NewLine, " GO ", Environment.NewLine };
string[] sqlArrayString = sqlString.Split(spliter, StringSplitOptions.RemoveEmptyEntries);
string executeString = "";
for (int i = 0; i < sqlArrayString.Length; i++)
  executeString = executeString + " " + sqlArrayString[i].ToString();
using (SqlCommand mySqlCommand = mySqlConnection.CreateCommand())
 mySqlCommand.CommandText = executeString;

Tuesday, May 15, 2012

What is a partial class and how to use in c sharp

It was introduced under 2.0 framework which allows you to split a class o n to multiple files
Splitting huge volumes of code into multiple files which makes managing easier.Allows multiple programmers to work on the same class at the same time.grouping related code of a class in separate files
Here i will show how to develop a partial class in csharp.For this add a class to the project naming it as File1.cs and write the following code
partial class parts
public void test1()
public void test2()
add one more class naming it as File2.cs
 partial class parts { public void test3() { Console.Writeline("method3"); } public void test4() { Console.Writeline("method4"); } } Now to test the class add one more class to the project naming it as test parts.cs and write the following class testparts { static void main() { parts p= new parts(); p.test1(); p.test2(); p.test3(); p.test4(); Console.ReadLine();
} }

Monday, May 14, 2012

What is Interface and how to use it in

In object oriented programming the code can be defined under another container known as interface.which can be defined with only abstract methods in it.Inheritance is organised as implementation and interface inheritance .Implementation inheritance is achieved through classes which is always single.
Interface inheritance is achieved through an interface which is multiple .Multiple inheritance is supported through interfaces under java and .net languages
<abstract members>;
-->An interface cannot contain variables in it
-->members of an interface by default public
-->method under interface are by default abstract
-->while implementing the methods of an interface under the class no need of using the override keyword
-->An interface can inherit another interface

Interface Example:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication10
class Program:bhaskar1,bhaskar2
static void Main(string[] args)
Console.WriteLine("Create my first interface");
Program p = new Program();
public void printbhaskar1()
Console.WriteLine("FirstMethod Implementation");
public void printbhaskar2()
Console.WriteLine("Second Method Implementation");
interface bhaskar1
void printbhaskar1();
interface bhaskar2
void printbhaskar2();

Saturday, May 12, 2012

convert uppercase to lowercase in xslt

Here i will show how to translate the uppercase letter to lowercase using xslt.For this i have created a variables ,which are used in this conversion process.Then the result will be assigned to one parameter which is "purl".
<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="">
    <xsl:param name="CurrentUrl"></xsl:param>
    <xsl:param name="PUrl"></xsl:param>
    <xsl:variable name="lowercletters">abcdefghijklmnopqrstuvwxyz</xsl:variable>
    <xsl:variable name="uppercletters">ABCDEFGHIJKLMNOPQRSTUVWXYZ</xsl:variable> 
    <xsl:template match="/">
        <xsl:for-each select="/Item/Menu">
            <xsl:if test="$PUrl = translate(Link, $uppercletters, $lowercletters)">
                    <xsl:value-of select="item"/>

Friday, May 11, 2012

how to create object in

We can create the object of a class from any where either in the same class or from the other class.When created with in  a class we created under main method.As it was the entry point
Syntax to create an object
<class> <obj>=new <class>([<arglist>])
program p=new program()
Here program p is object ,
program p=new program() is for allocate memory

Thursday, May 10, 2012

How to dynamically add CSS file in ASP.NET

Here i will show how to add css file to page in code behind.For this i have created a custom HTML link control and assign the styles sheet URL ,set remaining properties. We can see one more thing here is creating HTML control dynamically
In aspx page:
<link href="~/styles.css" rel="Stylesheet" type="text/css" />

       HtmlLink link = new HtmlLink();
link.Attributes.Add("type", "text/css");
link.Attributes.Add("rel", "stylesheet");
link.Attributes.Add("href", "~/Styles.css");
This.Header is used to add the link to aspx page

Wednesday, May 9, 2012

Convert a Generic List into a Datatable in

According to my application requirement ,i need to bind the data to data table from List in using this i just create table dynamically then bind the data using loop iteration on list.
In the below we can see two methods which are CreateDataTable which is used to create a data table and AddDataToTable which is used to bind the data .
public DataTable converttoTable(List<string> list, string tableName)
DataTable table;
table = CreateDataTable(); 
if (list.Count > 0)
foreach (string item in list)
AddDataToTable(item, table);
return table;
This function will execute when the items are added to data table.
private void AddDataToTable(string rowItem, DataTable myTable)
DataRow row;
row = myTable.NewRow();
string[] itemStringArray = SplitByString(rowItem, "[]");
row["Iame"] = itemStringArray[0];
row["Id"] = itemStringArray[1];
row["Address"] = itemStringArray[2] == "" ? "0" : itemStringArray[2];
row["Year"] = itemStringArray[3];
row["salary"] = itemStringArray[4];
catch (Exception e)
//create a table dynamically
private DataTable CreateDataTable()
DataTable myDataTable = new DataTable();
DataColumn myDataColumn;

myDataColumn = new DataColumn();
myDataColumn.DataType = Type.GetType("System.String");
myDataColumn.ColumnName = "Name";

myDataColumn = new DataColumn();
myDataColumn.DataType = Type.GetType("System.Int32");
myDataColumn.ColumnName = "Id";

myDataColumn = new DataColumn();
myDataColumn.DataType = Type.GetType("System.String");
myDataColumn.ColumnName = "Address";

myDataColumn = new DataColumn();
myDataColumn.DataType = Type.GetType("System.Int32");
myDataColumn.ColumnName = "Year";

myDataColumn = new DataColumn();
myDataColumn.DataType = Type.GetType("System.Int32");
myDataColumn.ColumnName = "Salary";

return myDataTable;

Tuesday, May 8, 2012

Copy data from one data table to another data table in

Title:How to copy data from one table to other table in


We have two different methods two copy the data form one data table to another data table .First one is to add the rows directly from one to other,second one is using Import Row method.In first we get the copied data into data row array,then it will go thorough for each row and add to another data table

DataRow[] selectedrows = Orders.Select("Customer = 'Bhaskar'");
DataRow AddNewRow;
foreach (DataRow row in selectedrows)
AddNewRow = CustomersDetails.NewRow();
AddNewRow["customername"] = row["customer"];
ImportRow() Method:
By using this method we just import  the rows   into destination data table from source data table.
DataTable Orders;
DataTable Ordersdetails;
DataRow[] Rows =  Orders.Select("city='Hyd'");
foreach (DataRow Row in Rows)

Monday, May 7, 2012

How to manipulate the gridview cell

Here i will show how to manipulate the grid view cell styles in windows forms application.For this i will get all grid view rows and compare the grid view header cell value with drop down selected value. Then the related data cells back colour will be changed to Green.In foreach loop we have one more for loop to get the entire column cells of related header in grid view.

foreach(DataGridViewRow row in this.Gvorders.Rows)
if (row.HeaderCell.Value == txtorder.Text)
for (int i = 0; i < Gvorders.Columns.Count; i++)
this.Gvorders.CurrentCell = row.Cells[i];
row.Cells[i].Style.BackColor = Color.Green;
For Each row As DataGridViewRow In Me.Gvorders.Rows
 If row.HeaderCell.Value = txtorder.Text Then
  For i As Integer = 0 To Gvorders.Columns.Count - 1
   Me.Gvorders.CurrentCell = row.Cells(i)
   row.Cells(i).Style.BackColor = Color.Green
 End If

Sunday, May 6, 2012

Exception handling in

Title:How to use Exception handling in using

To handle the exceptions we are provided two different blocks of code known as key,catch blocks which should be used as following

Statements which may cause you the exception
Statements which are related with the exception
Statements that should execute when exception occurs(error message)
Once we enclose the code under try and catch blocks the execution of the programs will be as following
If all statements under try are executed successfully,the control jumps to the end of the catch block with out executing the catch blocks
If any of the statement under try executes an exception,the control from that hold the exception object or not,if they control hold abnormal termination occurs
using System

Class trycatchdemo
static void main()
int x,y,z;
console.write("Enter X value");
console.Write("enter y value");
console.Write("The result is" +z););
catch (DivideByZeroException ex)
console.Write("Can not divide by zero");
catch(FromatException ex1)
console.Write("Can not divide by char");
catch(exception ex2)
console.Write("error occur");

Friday, May 4, 2012

how to add a list item into a list to sharepoint site in sharepoint 2010

Here i  will show  how to add a item to a list dynamically to share point root site.Then We have to get  the share point root site then add the items to list.The existing lists  will get by using GetList()  method .Finally we have to submit the changes of data context.

using (var dataContext = new MySharePointSite1L2spDataContext("http://localhost/test"))
  var Existingitems = dataContext.GetList<Item>("ItemMain");  
  Item Nitem = new Item();
  Nitem.Title = "Item for test";
  Nitem.Path = "/Lists/ItemMain";  

Thursday, May 3, 2012

How to binding the data to a chart in

Title:How to bind data to chart control in using

Binding data to a chart control is pretty simple in below example will show how to set the  student marks and exam types.For this two arrays String[],Double[] are used to get the count of class subject and exams which are given to chart x,y axis values
String[] sItems = new String[10];
Double[] iValue = new Double[10];
int j;
string s = "select count (*) as count from class_subject where classid='4'";
cmd = new SqlCommand(s, Con);
dr = cmd.ExecuteReader();
while (dr.Read())
count = int.Parse(dr["count"].ToString());
string sql = "select count (*) as count from exams e, marks m
where m.examid=e.examid and m.admissionno='" +
Session["admissionnumber"] + "'";
cmd = new SqlCommand(sql, Con);
dr = cmd.ExecuteReader();
while (dr.Read())
exams = int.Parse(dr["count"].ToString());
string sql1 = "select e.examtype as examname,ms.marks as obtainedmarks,mm.maximumfrom  marks_subject ms,marks m,exams
e,maxmarks mm  where e.examid=m.examid and  m.marksid=ms.marksid and
e.examid=mm.examid and  m.admissionno='" + Session["admissionnumber"]
+ "' and ms.subjectid='17'";
SqlDataAdapter da = new SqlDataAdapter(sql1, Con);
for (j = 0; j < exams; j++)
sItems[j] = ds.Tables[0].Rows[j][0].ToString();
obt = int.Parse(ds.Tables[0].Rows[j][1].ToString());
max = int.Parse(ds.Tables[0].Rows[j][2].ToString());
totalmarks = count * max;
percentage = (double)obt / totalmarks * 100;
string rounded = percentage.ToString("#0.00");
iValue[j] = double.Parse(rounded.ToString());
sItems[j] = "maximum % ";
iValue[j] = 100;
// axis values
markschart.YAxisValues = iValue;
markschart.YAxisItems = sItems;
markschart.Visible = true;
markschart.ChartTitle = "Marks chart:";
markschart.XAxisTitle = "(units display percentage)";