Tuesday, October 14, 2008

Move my blog

Hello, I'm going to be moving my blog to http://weblogs.asp.net
Please update your subscriptions


Regards

Tuesday, September 30, 2008

Rosario VS2010

Reveals extensive enhancements for simplified application life-cycle management, provides sneak peek at all key focus areas for Visual Studio 2010("Rosario") and the .NET Framework 4.0.


Stay tuned to http://channel9.msdn.com/VisualStudio/  for all of the action


Regards :)

Microsoft and JQuery

Microsoft will be shipping jQuery with Visual Studio going forward. jQuery will be distributed as JavaScript library as-is, and it will not be forking or changing the source from the main jQuery branch. The files will continue to use and ship under the existing jQuery MIT license.

Microsoft will also distribute intellisense-annotated versions that provide great Visual Studio intellisense and help-integration at design-time

The jQuery intellisense annotation support will be available as a free web-download in a few weeks (and will work great with VS 2008 SP1 and the free Visual Web Developer 2008 Express SP1).


For more info, check Scott's post

For more info about JQuery, click here


Regards

Tuesday, August 26, 2008

Friday, June 20, 2008

Bind a custom List to a DropDownList

using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using Microsoft.SharePoint;
using System.Configuration;
namespace TrackingClassLib.Sharepoint
{
public class Clients
{
public static DataTable GetClients()
{
DataTable dtClients;
using (SPSite site = new SPSite(ConfigurationManager.AppSettings["ClientListSiteName"].ToString()))
//Get the url of the site from web.config
{
using (SPWeb web = site.OpenWeb())
{
SPList clientsList = web.Lists["Clients"];
if (clientsList != null)
dtClients = clientsList.Items.GetDataTable();
else
dtClients = null;
return dtClients;
}
}
}
}
}
-------------------------------------------------------------------------------
private void LoadCompanies()
{
ddlCompany.DataSource = Clients.GetClients();
ddlCompany.DataTextField = "Title";
ddlCompany.DataValueField = "Id";
ddlCompany.DataBind();
}


Regards

Tuesday, April 22, 2008

Attaching Event to Custom List

I have a 2 custom Lists “Projects” and “Project Folders Type”
Projects have the following columns: Project Name, Project Description
Project Folders Type has the following columns: Title

I have a document library called “Project Details” with a column “Name”

Problem: The moment I add new project to Projects List, I need to create a folder with name of the projects and sub folders (from Project Folders Type List) in Project Details.

Solution: Create an Item Added event and attach it to Projects List


First:
Create a class Library, Add reference to Microsoft.Sharepoint.dll, and Inherit from SPEventItemReceiver


namespace EventRecieverDemo
{
public class DemoListEvents : SPItemEventReceiver
{
public override void ItemAdded(SPItemEventProperties properties)
{
string toolTipFieldInternalName = "";

using (SPWeb web = properties.OpenWeb())//Open the web you want to use
{
//Get a reference to the "Project Name" Column in "Projects" List
toolTipFieldInternalName = web.Lists[properties.ListId].Fields["Project Name"].InternalName;

//Get the projectTitle just Added
string projectTitle = properties.AfterProperties[toolTipFieldInternalName].ToString();

//Get the "Project Details" document Library where you want to add the folders
SPList myList = web.Lists["Project Details"];

//Create a folder in "Project Details" document library with the name of the project
SPFolderCollection projectFolder = web.GetFolder("Project Details").SubFolders;
projectFolder.Add(projectTitle);

//Get a refernce where you want to add subfolders
SPFolderCollection subfolders = web.GetFolder("Project Details/" + projectTitle).SubFolders;

//Get a reference to "Project Folders Type" where the names of the folders exist
SPList folderNames = web.Lists["Project Folders Type"];

//Loop through "Project Folders List"
foreach (SPListItem folderType in folderNames.Items)
{
//Add Sub Folders
subfolders.Add(folderType["Title"].ToString());
}
}
}
}
}

Build your solution and throw the dll in GAC (c:\windows\assembly), to get the publictoken key right click your dll in the GAC and hit properties

Second: Add another class to the class library and inherit from SPFeatureReceiver
namespace EventRecieverDemo
{
class FeatureReciever :SPFeatureReceiver
{
public override void FeatureActivated(SPFeatureReceiverProperties properties)
{
SPWeb web = properties.Feature.Parent as SPWeb;
try
{
SPList list = web.Lists["Projects"];
list.EventReceivers.Add(SPEventReceiverType.ItemAdded, "EventRecieverDemo, Version=1.0.0.0, Culture=neutral, PublicKeyToken=a1942c85f62a2b8d", "EventRecieverDemo.DemoListEvents");
list.Update();
}
finally
{
web.Dispose();
}
}
public override void FeatureDeactivating(SPFeatureReceiverProperties properties)
{
SPWeb web = properties.Feature.Parent as SPWeb;
try
{
SPList list = web.Lists["Projects"];
list.EventReceivers[0].Delete();
list.Update();
}
finally
{
web.Dispose();
}

}
}
}
Build your solution again and throw the dll in GAC




Third:
Add an XML file to the class library named Feature.XML, click on the properties tab/Schemas and press ADD and browse to C:\Program Files\Common Files\Microsoft Shared\web server extensions\12\TEMPLATE\XML and select wss.xsd, now you can have intellisense in your XML File


<?xml version="1.0" encoding="utf-8" ?>
<Feature xmlns="http://schemas.microsoft.com/sharepoint/"
Id="0491ECA8-2ED8-4e9c-B5CF-8E8FCDFFBF16"
Title="Projects Feature"
Description="Create Folders and sub folders for the project"
ReceiverAssembly="EventRecieverDemo, Version=1.0.0.0, Culture=neutral, PublicKeyToken=a1942c85f62a2b8d"
ReceiverClass="EventRecieverDemo.FeatureReciever"
Scope="Web"/>

The Id of the feature is GUID, you can get it from the Create GUID tool in visual studio

Forth:
Browse to “C:\Program Files\Common Files\Microsoft Shared\web server extensions\12\TEMPLATE\FEATURES” and create a folder “ProjectsFeature” and throw feature.XML inside it


Fifth:
Now we need to install the feature
Open command prompt and browse to:” C:\Program Files\Common Files\Microsoft Shared\web server extensions\12\BIN”
stsadm –o installfeature –name ProjectsFeature

Reset your IIS
Open you portal go to Site settings/Site Features and activate ProjectsFeature.

Test it :)

Monday, April 21, 2008

Code Behind in Sharepoint Designer

Create a new class Library
namespace CodeBehindTest
{
public class Sample : Page
{
protected Label lblText;//the same name as in SPD
protected Button btn;//the same name as in SPD

protected override void OnInit(EventArgs e)
{
btn.Click += new EventHandler(btn_Click);//Attach the event to the button
}
protected void btn_Click(object sender, EventArgs e)

{
lblText.Text = "Testing successfully";
}

}
}
Sign you assembly using the signing tool in VS
Build your solution, and drag drop the dll to GAC (c:\windows\assembly)
restart your IIS iisreset /noforce
Register you assembly as safe control in the web.config of the site
<SafeControl Assembly="CodeBehindTest, Version=1.0.0.0, Culture=neutral, PublicKeyToken=eef1ac0da5ab2a1f" Namespace="CodeBehindTest" TypeName="*" Safe="True" />
Create your ASPX Page in Sharepoint Designer
<%@ Page Language="C#" MasterPageFile="~masterurl/default.master"Inherits="CodeBehindTest.Sample,CodeBehindTest, Version=1.0.0.0, Culture=neutral, PublicKeyToken=eef1ac0da5ab2a1f" %>
<asp:Content ContentPlaceHolderID="PlaceHolderMain" runat="server"> <asp:Label ID="lblText" runat="server"></asp:Label> <asp:Button runat="server" Text="Click Me" ID="btn"></asp:Button> </asp:Content>

Regards



Saturday, April 12, 2008

Get "Currently Logged in" Manager

I posted in my earlier posts a sample on creating a custom webpart .
Today im gonna write a sample on how to use sharepoint object model to get the manager of the currently logged in user.
------------------------------------------------------------------------
Create a class library and inherit WebPart, check creating a custom webpart .

Add the following references to your class library:
using Microsoft.Office.Server;
using Microsoft.SharePoint;
using Microsoft.Office.Server.UserProfiles;

Create a label to hold the value of the manager:
Label lbl;
protected override void CreateChildControls()
{
lbl = new Label();
lbl.Text = GetManager();
this.Controls.Add(lbl);
}

Get Manager
private string GetManager()
{
using (SPSite site = new SPSite("
http://moss"))
{
string manager=string.Empty;
ServerContext context = ServerContext.GetContext(site);//Get the context for this site
UserProfileManager profileManger = new UserProfileManager(context);
SPUser user=SPContext.Current.Web.CurrentUser; //Get the current logged in user
try
{
UserProfile prof=profileManger.GetUserProfile(user.LoginName); //Get the profile for the current logged in user
manager = (prof[PropertyConstants.Manager].Value == null)
? "" : prof[PropertyConstants.Manager].Value.ToString(); //Get the manager
}
catch (Exception)
{
manager = "Manager was not found";

}
return manager;

}

Render the Label
protected override void RenderContents(System.Web.UI.HtmlTextWriter writer)
{
lbl.RenderControl(writer);
}


Monday, April 7, 2008

Make the Application Offline

Add app_offline.htm to the root of your Application and your application will be offline


HTH

Tuesday, March 4, 2008

Get GridViewRow's Index on button click

Below is a sample how to catch the rowindex of a gridview on button click located in a template column.

Here's the gridview:


<asp:GridView ID="GridView1" runat="server">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Button" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Code Behind:


protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
LoadData();
}
}
private void LoadData()
{
GridView1.DataSource=UsersAccess.Instance.SelectTable();
GridView1.DataBind();
}
protected void Button1_Click(object sender, EventArgs e)
{
GridViewRow row=((Button)sender).Parent.Parent as GridViewRow;
//Now I have the rowIndex
//I can : GridView1.Rows[row].FindControl("");
Response.Write(row.RowIndex);
}


Best Regards
Bilal Shouman

Monday, February 11, 2008

Selecting Text


You can do selection like above image by holding "alt" key and doing the selection

Regards

Format your code

You can format your code by selecting the code you want to format
and pressing ctl + K +F.

This shortcut can also be applied to html


Regards

Adding required validator to DropDownList

You can set a required field validator to a drop down list as follows

<asp:DropDownList ID="ddlItems" runat="server">
<asp:ListItem Text="<--Select Item-->" Value=""></asp:ListItem>
<asp:ListItem Text="Item 1" Value="1"></asp:ListItem>
<asp:ListItem Text="Item 2" Value="2"></asp:ListItem>
<asp:ListItem Text="Item 3" Value="3"></asp:ListItem>
</asp:DropDownList>

<asp:RequiredFieldValidator ID="RequiredFieldValidator1" ControlToValidate="ddlItems" runat="server" ErrorMessage="Please select an item" Text="Pelase select an Item"></asp:RequiredFieldValidator>

Friday, February 8, 2008

Create custom web part (part I)

Add a class library and set its output path (right click on the project name, properties, Built tab) to the bin folder of the sharepoint web site you want to deploy it on (wwwrootwss\VirtualDirectories\ [port#])

Add reference to System.Web
Add the following using statements
System.Web.UI
System.Web.UI.WebControls
System.Web.UI.WebControls.WebParts
Inherit your class from WebPart class
------------------------------------------------------------
Sample:

namespace BilalWebParts
{
public class MyWebPart : WebPart
{
GridView gv;
protected override void CreateChildControls()
{
gv = new GridView();
this.Controls.Add(gv);
BindStudents();
}
protected override void Render(HtmlTextWriter writer)
{
writer.Write("<table border='1' bordercolor='black'>");
writer.Write("<tr><td>");
writer.Write("Students List");
writer.Write("</tr></td>");
writer.Write("<tr><td>");
gv.RenderControl(writer);
writer.Write("</tr></td>");
writer.Write("</Table>");
}
protected void BindStudents()
{
string connectionString = "UID=sa;PWD=P@ssw0rd;Initial Catalog=test;Data Source=MOSS;";
SqlConnection con = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand("select * from Students", con);
cmd.CommandType = CommandType.Text;

DataTable dt = new DataTable();
SqlDataAdapter adp = new SqlDataAdapter(cmd);
adp.Fill(dt);

gv.DataSource = dt;
gv.DataBind();
}
}
--------------------------------------------------------------
Build your application
--------------------------------
Add the following line to safe control block in the web.config of the sharepoint website you want to add the webpart to.
<SafeControl Assembly="BilalWebParts" Namespace="BilalWebParts" TypeName="*" Safe="True" />
---------------------------------
Modify trust tag in web.config
<trust level="WSS_Medium" originUrl="" />
---------------------------------
Adding WebPart:
Open sharepoint site
Go to site settings, then go to webparts link under Galleries tab, click new and check BilalWebParts.MyWebPart then click populate gallery.
Go back to you site and Edit Page then Add a webpart, search for MyWebPart and click ok.Students List will apear
------------------------------------------------------------------

Best Regards

Thursday, February 7, 2008

Importing data from active directory

DirectoryEntry oRoot = new DirectoryEntry
("LDAP://OU=Development,OU=Engineering,dc=MOSS2007,dc=com");
//My domain name is called MOSS2007.com
//I have OU Engineering and below I have Development

DirectorySearcher oSearcher = new DirectorySearcher(oRoot);
SearchResultCollection oResults;
oResults = oSearcher.FindAll();

for (int i = 0; i < oResults.Count; i++)
{
if (oResults[i].GetDirectoryEntry().Properties["cn"].Value != null)
Response.Write(oResults[i].GetDirectoryEntry().Properties["cn"].Value + " , ");
}
------------------------------------------------------------------------------
Variables you can use:
[0]: "homemdb"
[1]: "countrycode"
[2]: "cn"
[3]: "msexchuseraccountcontrol"
[4]: "mailnickname"
[5]: "msexchhomeservername"
[6]: "msexchhidefromaddresslists"
[7]: "msexchalobjectversion"
[8]: "usncreated"
[9]: "objectguid"
[10]: "msexchrequireauthtosendto"
[11]: "whenchanged"
[12]: "memberof"
[13]: "accountexpires"
[14]: "displayname"
[15]: "primarygroupid"
[16]: "badpwdcount"
[17]: "objectclass"
[18]: "instancetype"
[19]: "msmqdigests"
[20]: "objectcategory"
[21]: "samaccounttype"
[22]: "whencreated"
[23]: "lastlogon"
[24]: "useraccountcontrol"
[25]: "msmqsigncertificates"
[26]: "samaccountname"
[27]: "userparameters"
[28]: "mail"
[29]: "msexchmailboxsecuritydescriptor"
[30]: "adspath"
[31]: "lockouttime"
[32]: "homemta"
[33]: "description"
[34]: "msexchmailboxguid"
[35]: "pwdlastset"
[36]: "logoncount"
[37]: "codepage"
[38]: "name"
[39]: "usnchanged"
[40]: "legacyexchangedn"
[41]: "proxyaddresses"
[42]: "userprincipalname"
[43]: "admincount"
[44]: "badpasswordtime"
[45]: "objectsid"
[46]: "msexchpoliciesincluded"
[47]: "mdbusedefaults"
[48]: "distinguishedname"
[49]: "showinaddressbook"
[50]: "givenname"
[51]: "textencodedoraddress"
[52]: "lastlogontimestamp"


HTH

Confirmation before leaving a page

What if the user didn't hit save before navigating to another page, what will happen then?

Below is a solution for this commonly asked question, hope it will help.
-------------------------------------------------------------------------------------

Add the following javascript to your page
<script type="text/javascript">
var needToConfirm = false;//Flag to check if save button is hit or changes has happened
window.onbeforeunload = confirmExit;//calling confirmExit function onbefore unload
function confirmExit()
{
if (needToConfirm==true)//Save button was not hit or changes to the page has happened
return "--------------------------------------------------\n" +
"Warning:\n" +
"If you have made any changes to this page without clicking the Save button, your changes will be lost\n" +
"--------------------------------------------------";
}
</script>

-Add some controls to your page

-Setting needToConfirm flag to true if any changes happened(code behind)
private void AddAttributes()
{
txtName.Attributes.Add("onkeyup", "needToConfirm=true");
txtEmail.Attributes.Add("onkeyup", "needToConfirm=true");
txtAddress.Attributes.Add("onkeyup", "needToConfirm=true");
ddlTests.Attributes.Add("onchange", "needToConfirm=true");
}
-----------------------------------------------------------------------------------
Now Open your page and write anything in any textbox, donot hit save and close your browser.

Confirmation message will appear asking you if you really want to leave the page or not

HTH

Sunday, February 3, 2008

My First Blog

Hello everyone....

This is my first post......

This blog will mostly contain information regarding .net technologies.

Hope my information will be helpful.

Keep your eyes here ....


Regards