Saturday, June 30, 2012

Adding Foriegn Key to DataTbale Programmatically in Asp.net

Here i will show how to assign foreign key to Data table dynamically  using C#.For this we will the data of two table(Orders,Customers) from sqlserver.Then the data is bind to data set.The FK is assigned to OrderId in Customers table using ForeignKeyConstraint class.The Rules(delete,edit) of key also set dynamically in below peace of code

SqlConnection cn=New SqlConnection("server=./sqlexpress;user id=sa;password=ds;database=test");
SqlDataSet ds=New SqlDataSet();
SqlDataAdapter daOrder = new SqlDataAdapter("select *from Orders", cn);
SqlDataAdapter daCustomers = new SqlDataAdapter("select *from Customers", cn);
dadept.Fill(ds, "Orders");
daemp.Fill(ds, "Customers");
ForeignKeyConstraint fkc = null;
fkc = new ForeignKeyConstraint(ds.tables("Orders").Columns("OrderId"), ds.Tables("Customers").Columns("OrderId"));
fkc.DeleteRule = Rule.Cascade;
fkc.DeleteRule = Rule.SetNull;
fkc.EditRUle = Rule.Cascade;
ds.Tables("Customers").Constraint.ADD(fk);
gvOrders = ds.Tables("Orders");
gvCustomers = ds.Tables("Customers");

how to create dynamic dropdown list in asp.net

Here in this post i will show how to create a drop down list and add items dynamically in asp.net.We  can do this functionality in two ways one is using List  and other one is directly adding the items to drop down.The "ddllist"  is the list which will be bind to drop down list
Usign list to bind  items to dropdownlist:
DropDownList ddlcountry = new DropDownList();
List<string> ddllist = new List<string>();
ddllist.Add("India");
ddllist.Add("us");
ddllist.Add("uk");
ddlcountry.DataSource = ddllist;
dddlcountry.DataBind();
this.Controls.Add(ddlcountry);

Simple item binding to dropdownlist:
DropDownList ddlcity = new DropDownList();
ddlcity.Items.Add("Hydreabad");
ddlcity.Items.Add("Mumbai");
ddlcity.Items.Add("chennai");
this.Controls.Add(ddlcity);

Friday, June 29, 2012

move items from one listbox to another listbox in asp.net

Now i will show how to add the items to one list box to another list box.In this example i have taken two list boxs with two button.if i click on the MoveRight button the left list box item is passed to right side list box.The reverse process has done for Moveleft button.In this code i removed the item which will be passed to another list box
Aspx:
<form runat="server" id="test">
<h2>
List Box Example
</h2>
<table><tr><td><asp:ListBox ID="listLeft" runat="server">
<asp:ListItem>Bhaskar</asp:ListItem>
<asp:ListItem>Siva</asp:ListItem>
<asp:ListItem>Venky</asp:ListItem>
<asp:ListItem>Ram</asp:ListItem>
<asp:ListItem>Balu</asp:ListItem>
<asp:ListItem>Krishna</asp:ListItem></asp:ListBox></td>
<td>
<asp:Button ID="MoveRight" runat="server" Text=">>" onclick="MoveRight_Click1" /><br />
<asp:Button ID="MoveLeft" runat="server" Text="<<" onclick="MoveLeft_Click1" /></td>
<td> <asp:ListBox ID="listRight" runat="server"></asp:ListBox></td></tr></table>
</form>
CodeBehind:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class _Default : System.Web.UI.Page
{
protected void MoveRight_Click1(object sender, EventArgs e)
{
if (listLeft.SelectedItem != null)
{
ListItem li = listLeft.SelectedItem;
listLeft.Items.Remove(li);
li.Selected = false;
listRight.Items.Add(li);
}
}
protected void MoveLeft_Click1(object sender, EventArgs e)
{
if (listRight.SelectedItem != null)
{
ListItem li = listRight.SelectedItem;
listRight.Items.Remove(li);
li.Selected = false;
listLeft.Items.Add(li);
}
}
}

Thursday, June 28, 2012

AJAX autocompleteExtender Textbox using web service

In this post i will show how to assign the data to autocomplete textbox from web service in asp.net.Fo this i have used a webservice "FirstAutoComplete.asmx",which has one method GetdeptName() is used to get the data from database based user input.
The ajax tool kit provides a control to perform this kind things./i:e autocomplete extender.It has one property to acces the web servoce which is"ServicePath"
<form id="test" runat="ServeR">
<div>
<asp:ScriptManager ID="sm" runat="Server">
</asp:ScriptManager>
<asp:TextBox od="txttest" runat="Server"></asp:TextBox>
</div>
<Ajaxtest:AutoCompleteExtender ID="ac" runat="Server" TargetControlID="txttest" Servicemethod="GetdeptName" ServicePath="FirstAutoComplete.asmx "
MinimumPrefixLenth="1" EnableCaching="true" CompletionSetCount="12">
</Ajaxtest:AutoCompleteExtender>
</form>
Web service:
Here the web method class has placed app_codefolder.
[System.Web.Script.Serivces.ScriptService()]
public class FirstAutoComplete:System.Web.Services.Webservice
{
[WebMethod]
public string[] GetdeptName(string inputText)
{
        string sqlstr = "select MAINCODE, MAINNAME from MstMainMaster where maincode like 'ddp%' and  MAINNAME like @inputText";
        SqlDataAdapter da = new SqlDataAdapter(sqlstr, ConfigurationManager.ConnectionStrings["Con"].ToString());
        da.SelectCommand.Parameters.Add("@prefixText", SqlDbType.VarChar, 50).Value  ="%"+ inputText + "%";
        DataTable dt = new DataTable();
        da.Fill(dt);
        string[] outputitems = new string[dt.Rows.Count];
        int i = 0;
        foreach (DataRow dr in dt.Rows)
        {
            outputitems.SetValue(dr["MAINNAME"].ToString(), i);
            i++;
        }
        return outputitems;
    }

}

how to get browser name in Jquery/javascript

Title: JQuery Get browser name in Asp.net

Description:
While working with web application we need to set or get some browser compatibility settings as per requirement.Now i would like to describe how to resolve some design issues of asp button  control based on browser using JQuery.In Java script we have an object "navigator" ,which can be used to get the browser name in java script.Here i converted the navigator user value  to upper case letters ,then based on  condition i will filter the browser.
Javascript:
<script>
window.onload(GetBrowserDemo());
function GetBrowserDemo()
{
var btnid=document.getElementById("<%=btntest.ClientID%>");
var browservalue = navigator.userAgent.toUpperCase(); 
if(browservalue .indexOf("FIREFOX") > -1)
{ 
alert('FireFox');
btnid.val="Test"
} 
else if(browservalue .indexOf("MSIE") > -1)
{ 
alert('IE');
btnid.val="Edit";
} 
else if (browservalue .indexOf("CHROME") > -1)
{
alert('Chrome');
btnid.val="update";
} 
}
</script>
Jquery:
$(document).ready(function() {
if ($.browser.msie){
alert('It is IE');
}
if( $.browser.opera){
alert('It is Opera');
}
if ($.browser.mozilla){
alert('It is Mozilla);
}
if( $.browser.safari ){
alert('It is Safari');
}
});
}
In JQuery ,It has an object "browser" to get the current browser name .if we use the JQuery ,we  have to add the jquery reference library . Please refer this link 

Jquery browser Objet with examples

Wednesday, June 27, 2012

Difference between Respost.Redirect and Server.Transfer

In this post i will given the difference between respose.redirect and server .Transefer
Server.Tranfer:
1.It can be used only for switching from one web form to another web form of the same application
2.It retains the context in which the actually requested web form is executing
3.This method can carry the current page values to new page
4.This method does not update the browser about new page that it is navigated to.
5.Page with our web application must be specified not the other web application
Respose.Redirect:
1.Redirect submits the respose to the browser asking browser to send a request for the new url and thus all the context of the previous is lost when the new url is excuting
2.It can be used for switching from web form of one web application to web form of another web application


Note:On refresh If Redirect is used it will the request for the new page where as if transfer is used browser submits the request for original page

Monday, June 25, 2012

How to set Reference for javascript/css file in ASP.NET MVC

When i work with MVC i don't know how to add the js and css files to application.I just give the reference for the files as per asp.net.But it is not a right method to give the reference in MVC.While adding a java script ,css or images are any file which we refer using the source tag "src" we need to use the following syntax in MVC using Asp.net
For java script:

<script type="text/javascript" src="@Url.Content("~/Scripts/jquery-1.7.2.min.js")"></script>
<script type="text/javascript" src="@Url.Content("~/Scripts/jquery.datepicker.addevents.js")"></script>

For Css files:
<link href="@Url.Content("~/csslib/reset.css" rel="stylesheet")" type="text/css" />
<link href="@Url.Content("~/csslib/styles.css" rel="stylesheet")" type="text/css" />

Sunday, June 24, 2012

How to Read Excel File data from Document Library in sharepoint 2010

Here i will show how to reading the of excel file which is in Document library.The "url" is the path of excel file in library .To do the excel application process we have to add the Microsoft.Interop.Excel.dll.Then get the data form the file and transfer to values.
ApplicationClass Mexcel = new ApplicationClass();
string wbPath = url;
Workbook Workbook = Mexcel.Workbooks.Open(wbPath, 0, false, 5, "", "", false, XlPlatform.xlWindows, "\t", true, false, 0, true, 0, 1);
Sheets ss = Workbook.Worksheets;
Worksheet ws = (Worksheet)sts.get_Item(1);
for (int i = 1; i <= ws.Rows.Count; i++)
{
 Range rn= worksheet.get_Range("C" + i.ToString(), "F" + i.ToString());
 var values = (System.Array)range.Cells.Value2;
}

Thursday, June 21, 2012

how to sort data in sql

When we insert random data into any table, now in order to sort those elements in the table we can use the following query.TO achieve this we create a temporary table using sql statement.
declare @sorttable table(names char(10))
After creating the table we insert the data into table we created above.
insert into @sorttable select 'bhaskar' union all select 'siva' union all select 'krishna' union all select 'anil'
Now to sort the above data we use the following statement
select names  from @sorttable  order by left(names,1)

Wednesday, June 20, 2012

how to encrypt a file in c#

Encryption is a secure process ,which is used to transfer the data into code by appending a key .The resultant of the process is the encryption information. Here i will show how to encrypt a file in csharp.To do this process we have to add a name space "System.Security.Cryptography" .In this function i have used a key "pkey" to encrypt the data and the "outputpath" is resultant encrypted data
FileStream fs= new FileStream(Outputpath,FileMode.Create,FileAccess.Write);
DESCryptoServiceProvider DEScs = new DESCryptoServiceProvider();
DEScs.Key = ASCIIEncoding.ASCII.GetBytes(pKey);
DEScs.IV = ASCIIEncoding.ASCII.GetBytes(pKey);
ICryptoTransform desencrypt = DEScs.CreateEncryptor();
CryptoStream cstream = new CryptoStream(fs,desencrypt,CryptoStreamMode.Write);
fs.Close();
FileStream fsInput = new FileStream(Inputpath,FileMode.Open,FileAccess.Read)
byte[] ba = new byte[fsInput.Length];
fsInput.Read(ba, 0, ba.Length);
fsInput.Close();
cstream.Write(ba, 0, ba.Length);

Tuesday, June 19, 2012

Silverlight Client Object Model in SharePoint 2010

Silver light Object model is introduced in Microsoft SharePoint 2010 along with ECMASCRIPT and managed Client side model .Silver Light Object model supports its implementations in three possible contexts .

1) Within the silver light web part applications .
2) With in the silver light cross domain data access system .
3)Modifying the  Client Access cross domain policy ( High Security risk and not supported by Share Point Foundation )
                                Since the query execution is asynchronous when you use the SharePoint Foundation Silverlight object model, you must pass delegates for callback methods as parameters in the ExecuteQueryAsync(ClientRequestSucceededEventHandler, ClientRequestFailedEventHandler) method, similarly to query execution in the JavaScript object model.
                                 However ,in order to make changes in the User Interface through silver light object model ,you must delegate this work to the Dispatcher object of the thread that created the UI by calling Begin Invoke method .

Monday, June 18, 2012

JavaScript Client object model in SharePoint 2010

ECMASCRIPT(JavaScript or Jscript )client  object model  is introduced in Microsoft SharePoint 2010 along with Silverlight and managed client object models. The JavaScript Object models will let you work on the objects without deploying the code on the server .This helps the application with reduced stress of server and bound to easy loading of the application .
                                  
                                     This type of models efficiently run for sandbox solutions and server side hierarchy applications. Since Java Script works on the Client context ,that is it works just for the current context there is no scope for the object availability for cross site scripting or the access of the object model away from the current context ,which will enhance the already existing security feature of the application . to reduce the stress on the server ,this client object model doesn't load all the object properties when a object is created .  
                                       
                                    The Data retrieval is done on client load function using the methods like set_ and get_ based on the availability to retrieve or set the value of the property. The JavaScript Class Library contains the reference material and properties for the objects .Due to lots of similarities in managed object model and java script object model .They both share the similar Orientation .

Saturday, June 16, 2012

Upper case to lower case and lower case to upper case in XSLT

Here i will show how to cover the lower case characters to upper case and upper case characters to lower case in xslt.There simple way i have used to create variable for both lower and upper letters ,then URL string replace will be done using those variable
<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
     <xsl:variable name="lcletters">abcdefghijklmnopqrstuvwxyz</xsl:variable>
    <xsl:variable name="ucletters">ABCDEFGHIJKLMNOPQRSTUVWXYZ</xsl:variable>
    <xsl:template match="/">
        <xsl:variable name="PUrlLower" select="translate($PUrl, $ucletters, $lcletters)">
        </xsl:variable>
         <a>
           <xsl:attribute name="href">
                <xsl:value-of select="$PUrl"/>
            </xsl:attribute>
            <xsl:attribute name="title">
                <xsl:value-of select="$PTitle"/>
            </xsl:attribute>
            <xsl:value-of select="$PTitle"/>
        </a>
        </xsl:template>
</xsl:stylesheet>

Thursday, June 14, 2012

How to hide and show the fileds or controls in sharepoint 2010

Here i wanna show how to hide the control in editable form in share point at server side.Here i have requirement to show the salesperson name and hide the salesperson id when the form in edit mode.For this there is pretty simple property used in share point to hide controls or Field i:e ShowInEditForm.I just set the property to true for salesperson name field to show and false for id field to hide
SPSite ss = new SPSite(url)
SPWeb sw = ss.OpenWeb())
SPList slist = sw.Lists["Orders"];  
SPField salespname = slist.Fields["salesPerson"];
SPField salesid = slist.Fields["SID"];
//show the salesperson name field in edit mode   
salespname.ShowInEditForm = true;
//to hide the sales person field in edit mode  
salesid.ShowInEditForm = false;  
salesid.Update(); 
salespname.Update();

Wednesday, June 13, 2012

how to install a skin in dotnetnuke

In prevous post we have seen how to create a page in DNN.Here i will show how to upload or add a built-in skin to our dnn site portal.The installed skin can see in portals folder in file structure.For this we have to do following steps
1.Login into DNN site as admin,Then go to Admin tab on page function menu and click on the extension property

2.You have to mouse over on the manage tab which is displayed when the site is in edit mode,then select Install Extension Wizard

3.Here We have property to upload zip file to portal.So i will add my existing zip file to portal as seen in below screen.Then click on Next button


4. We have to select whether the upload zip file is skin file or not ,then click on the next button up to  Review licence pop up

5.In this we have to accept the licence of built in skin ,then click on the  next button

6.Finally we installed skin under skins in installed extensions..This skin can assign to any desired page in site

Tuesday, June 12, 2012

how to add or create a new page in dotnetnuke

we can create a page using  two  different methods in DNN.The administrator can only add or delete pages in application.So the admin should be login into site and then do the below steps.Whenever login into the application you can see the page functions menu on top of the page.
First Method:
1.When ever mouse over on admin menu item which is in page function tab ,we can get a pop with multiple options.In this we have to select Page management

2.Here you can see the parent node as Home  because it is an application name

3.Right click on the home tab ,the select the option Add pages

4.Here we get an option to give the desired page name.Then click on Create Page(s)

You can see the message the Page Test created and circled  is added page under home page

Second method:we can create a page with direct option  which is in page functions menu.For this we need to go for pages option on page function tab and select add option
Here it provides all manipulation of pages like add,delete,import or export page in DNN site.we can also update the page which already created in site

Monday, June 11, 2012

how to increase the maximum file upload size in dnn

It is pretty easy to increase the upload file size in DotnetNuke.when i am working on this one,i have a question is why will i increase the file size ?The answer is  By default it has fixed to 1mb for upload the maximum file size in dnn.so when we upload more than 1 mb we will get an error like this "The size of uploaded file exceeds max size allowed".
So To resolve this error we have to increase the size as per requirement.Here i increased  up to 20 mb for Document(.doc,.pdf etc) files and 3 mb for image file.
Please follow the below steps in DNN:
1.Login as a super user.Go to Host-->HTML Editor manager

2.In html editor manager we have an option Every one which circled in below image

3.Whenever select the option we get Editor configuration with all manager settings

4.Expand the default manager and change the Max File Size option with your desired value

5.Finally you have to change the file size in web.config.In web .config we have a option in http Run time

Saturday, June 9, 2012

How to hide view in SharePoint 2010

Here I will hide the one of view which get from the existing List in SharePoint. India_orders is the view ,get from the orders list then hide ursing hidden property of view
SPsite ss = SPcontext.Current.Site;
Spweb sw = SPContext.Current.Web;
SPList sl = sw.Lists["Order"];
SPView Indview = sl.Views["India_orders"];
Indview.Hidden = true;
Indview.Update();
Console.Writeline("Hide the desired View");

Friday, June 8, 2012

How to get user permissions in sharepoint 2010

he user has automatically get some roles and permission when he registered into any enterprise level website.In this article i will explain how to retrieve the current user permission in share point 2010.In share point we have GetByName method which is used to get the roles based on user and get the permissions using roles
ClientContext clc = new ClientContext(url);
RoleDefinition Rdef = clc.Web.RoleDefinitions.GetByName("Test");
clc.Load(Rdef);
clc.ExecuteQuery();
BasePermission Bper = Rdef.BasePermissions;
Console.Writeline(Bper);

Tuesday, June 5, 2012

Get all subsites using client object model in sharepoint

Here i will show how to get all sub sites using client object model in share point.Here we have know why we are using Openweb method.Using this method we can get the websites from web collection .We will get title,description and web for the each website in collection using context query and display the information using loop
ClientContext clc = new ClientContext(url);
sp.Web w = clc.Site.OpenWeb("url/sitename");
clc.Load(w,ws => ws.Webs,ws => website.Title, ws => ws.Description,);
clc.ExecuteQuery();
for (int j = 0; j != w.Webs.Count;j++)
{
Console.WriteLine(ws.Webs[j].Title);
}

Monday, June 4, 2012

how to round a number in sql server

Here i will  give a simple query to round  the number in sql.For this we have a sql function  ROUND() is used to convert to near number if the number is decimal number
Query:
select CEILING(21.8) as FirstRounupvalue

Result:22
In the above image i just give an example to round  three number in one statement.you can see the output as in below columns in results.The ceiling is convert the decimal number to nearest maximum number.If you want round to number minmum number ,we have to use FLOOR.
Query:
select FLOOR(21.8) as AfterFloorNumber

Result:21


Sunday, June 3, 2012

how to upload a file using client object model in sharepoint 2010

Here i will show how to upload a file using client object model in share point 2010.The location of the file has been assigned to a variable "filepath" .
string filepath=@"d:\projects\testshareupload\orderdata.doc";
ClientContext clc = new ClientContext(siteurl);
Web w = clc.Web;
FileCreationInformation Fi = new FileCreationInformation();
Fi.Content = System.IO.File.ReadAllBytes(filepath);
Fi.Url = "orderdata.doc";
List datafiles = web.Lists.GetByTitle("Files");
SP.File uFile = docs.RootFolder.Files.Add(Fileinfo);
clc.Load(uFile);
clc.ExecuteQuery();
 
After all we may get any error regarding file size,we have increase the maximum upload file size by using the below code
SPWebService sws = SPWebService.ContentService;
SPClientRequestServiceSettings SpCclientSettings = sws.ClientRequestServiceSettings; 
SpCclientSettings.MaxReceivedMessageSize = 5242880; 
sws.Update(); 
 

Saturday, June 2, 2012

Avoid duplicate files into Document library in sharepoint 2010

Here i will show how to prevent the same file to be uploaded multiple times into document library in share point 2010.This process will apply when the Itemadding event occurred.To get the all the details about list items events in share point website we have to use excute a query to get listitemcollection.The file name is getting from url then it will pass to spquery and get the count of files with this file name,then check the file is already exist or not .
//Before url is get the url of item before event
string fRawUrl = p.BeforeUrl;
string fName = fRawUrl.Substring(fRawUrl.LastIndexOf('/') + 1);
slist=p.List;
SPQuery squery = new SPQuery();
squery.Query = string.Format("<where><eq><fieldref name="FileLeafRef"></fieldref><value type="Text">Docname</value></eq></where>",fName);
SPListItemCollection sitem = slist.GetItems(query);
//check wether the file is already existing or not 
if (sitem.Count > 0)
{
p.Cancel = true;
p.ErrorMessage="Item already existed"
}

Bel