Search This Blog

Monday, July 26, 2010

Introduction Sharepoint

Microsoft SharePoint is a web-oriented platform for collaboration and documents management. The solution can be used to create different web-sites with shared documents or dedicated applications (i.e. Wiki, blogs, forums). SharePoint functionality is presented to the User by control elements that display the data which can also be edited. Such webparts are placed on pages which in turn are placed on the Portal and are available to the User via browser.

SharePoint is presented in two main products:

- Windows SharePoint Services;

- Microsoft Office SharePoint Server.

1.1 Windows SharePoint Services

Windows SharePoint Services (WSS) – is a platform for deployment and content management by Microsoft. WSS has the following features:

- is a basis of files and folders;

- gives basic option for information search;

- gives content management system;

- management of access rights definition;

- gives an option for webpart extension.


After the application deployment the standart or customized webparts can be used. Blogs, private address books, documents store websites, internet shops, news websites, pages with audio and video players can be easily created with the help of the applications. All the above functionality can also be combined on the single portal. Our developers can alter any website component per your requirments.
The Lists can be set up to display various document types in different views as per the User's specific tasks. Microsoft SQL Server is used as DBMS for applications based on SharePoint.


1.2 Microsoft Office SharePoint Server


Microsoft Office SharePoint Server (MOSS) is the best component for integration SharePoint functionality into MS Office applications. It expands Windows SharePoint Services with new options. If a document have to be saved as parts of web-applications, the solution to use is MOSS. Client Office applications (including Word, Excel, Outlook, InfoPath) can be easily used in composition of Corporate solutions, build on SharePoint. All MOSS functions can be extended by our developers for a wide range of products realization: from the simple web-panels to the complex web-applications.


2. SharePoint advantages


SharePoint products and technologies give the wide range of advantages not only for developers, but also for separate users and organizations of any level:

- Full functionality of the portal right after the installation

All SharePoint Server options are available right after the installation. Though the set of Server options is wider and includes news, catalogues, topic areas, private web-sites- “my site”, supposed audience selection, tools for searching and viewing employees, work groups and information as well as web-sites creation that gives the necessary structure for building a single workspace. SharePoint is based on Microsoft Windows SharePoint Services, that is why tools of Windows SharePoint Services for co-working will be available at once.

- Performance and scalability

SharePoint Server supposes the following flexible means of deployment that provides distributed structure and optimal work of the portal: SharePoint supports server farms creation with distributed task servers, database severs, search option and option of indexation by different external services. Shared Services could provide from the single center and employ on the several portal farms the services like search or support of private web-sites. Besides SharePoint Server can serve up to 1,000,000 Users simultaneously registered in Active Directory, and it has capacity of 250 pages per second.

- Private sites (“My sites” section)

Private site is a site which may have a private view where User stores data inaccessable to others, i.e. unfinished documents, private pieces of news and weblinks; and a general view where data for other Users is stored, i.e. presentations or finished reports. Information in the general view of private sites can be indexed by Administrator with the help of catalogue services, i.e. Active Directory, which provides Users with an option to search for the information and examples to help them complete their tasks, within all the company.
Single signon system
Singe signon allows the users to receive personal data from any system part with just a single login to the system. When Users login the portal, SharePoint saves User data in a secure place. When the portal applications require information from other business-applications, i.e. system of planning company resourses, CRM system of third-party providers, SharePoint uses User data with verifying them in Active Directory. So the User doesn’t need to login into external business-application.


- Flexibility, personalization, adaptation of web-component based pages.


SharePoint provides additional web-components and flexible means of their management, which allow Users to set up portal pages in the necessary way with simple drag-and-drop of the components to the page. In Microsoft Office FrontPage there is a complete support of web-components and web-component based pages including adding, editing and setting up of web-components, web-components zone and differents web-component pages;


- Subject parts


SharePoint provides for subject sorting, which is highly intuitive when searching for survey of random data from documents and people information to web-sites on base of Windows. A document or link can be refered to several subjects, subject parts may contain documents stored in SharePoint, as well as links to the information from outher sources. Management policy has hierarchical distributed structure that allows experts in this field to create and maintain the most favourable parts.


- Active Directory untegration with Microsoft Office products


SharePoint scan through Active Directory catalogues, gathering User data. Users can manage information about them in the portal and get alerts when other Users publish or change information.
SharePoint makes Users’ work more comfortable regardless of the application they use. The User can create and maintain web-sites, i.e. website of the document working area, add news and events to SharePoint web-sites on the portal and get alerts with the help of web-browser.


- Search


SharePoint allows Users to search by key words in the whole text and in the document properties. Users can search for not only the information, but also other people, work groups and web-sites of the portal.


- Key features of Windows SharePoint Services


Private websites, workgroup websites and subject areas of the SharePoint portal has all the features of Windows SharePoint Services document libraries, supporting version alert, simple routing and confirmation mechanism. Users can check in and check out documents or return to previous document versions using their usual applications.
SharePoint provides a wide range of calendar events, addvertisemnets, links, tasks and also an option to define new lists (which serves as a flexible tool for different tasks solving). Additionally SharePoint provides with web-sites creation, uses meeting web-sites and document workspace right from the applications of Microsoft Office group. The websites created with the help of checked templates make it easier to conduct discussion and meetings, improving co-working of the work groups and companies.
Besides SharePoint provides a list of additional facilities:


- Has a custom design option;

- Has an option of IE, FireFox, Safari, Opera browsers usage;

- Has wide options of User rights distribution;

- Has a high safety level of the data transfer.


3. Creating applications using SharePoint


Process of web-application development using SharePoint is similar to the process of application development using more traditional means (i.e. PHP). Nevertheless, product development stage goes much faster and as a result cheaper to the Client.
Simplified process of web-applications creation with the use of SharePoint can be given with the following set of actions:


- SharePoint deployment and web-site creation by default;

- After Windows SharePoint Services deployment the web-site is created by default;

- Web-sites collection for the application with a template is created by default;

- Then there is a creation of the necessary types, lists and user groups;

- User rights are defined for the lists. The full safety of User information is provided.

- Necessary application components (i.e. wikis, blogs, calendars, etc.) are added and set up.

- Web-site interface is setup per Client’s wishes.



Using the action sequence, our developers can shortly create web-applications starting from Corporate web-sites to internet-portals with wide functionality.
Note: SharePoint is a powerful tool which enables creation of web-sites and a big number of applications that use

Export To Excel

public void GenerateExcelReport()
{
HttpContext.Current.Response.Clear();
this.GridView1.AllowPaging = false;
this.GridView1.AllowSorting = false;
this.GridView1.DataSource = GetCustomMadeDataTable();
this.GridView1.DataBind();
HttpContext.Current.Response.Write("");
HttpContext.Current.Response.Write("");
HttpContext.Current.Response.Write("
Training History Report
");

HttpContext.Current.Response.Write("");
System.IO.
StringWriter stringWrite = new System.IO.StringWriter();
System.Web.UI.
HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);
HttpContext.Current.Response.AddHeader("content-disposition", "attachment; filename=TrainingHistoryReport.xls");
HttpContext.Current.Response.Charset = "";
HttpContext.Current.Response.ContentType = "application/vnd.xls";
// Create a form to contain the grid
System.Web.UI.HtmlControls.
HtmlForm frm = new System.Web.UI.HtmlControls.HtmlForm();
this.GridView1.Parent.Controls.Add(frm);
frm.Attributes[
"runat"] = "server";
frm.Controls.Add(
this.GridView1);
frm.RenderControl(htmlWrite);
HttpContext.Current.Response.Write(stringWrite.ToString());
HttpContext.Current.Response.End();

}

Saturday, July 17, 2010

Structure of Sharepoint

Sharepoint Architecture Diagram (MOSS 2007 Architecture)

For understanding, What is Sharepoint?

Sharepoint is 3-Tier Application.
1. The Presentation Layer resides as .Aspx Pages (Asp.net Application)
2. Logic resides in .Net Assemblies.
3. Data resides in SQL Server Database.

Sharepoint is installed at "C:\Program Files\Common Files\Microsoft Shared\web server extensions\12", this root is popularly know as "12 Hive". You can find all resources related to sharepoint application here, which are prime focus to Developers.




MOSS 2007 Architecture Diagram


Structure of Sharepoint Sites


Friday, July 16, 2010

SharePoint Designer or Visual Studio?

If you are confused about when to use SharePoint Designer and Visual Studio then here are some guidelines which may help you choosing the right technology at the right time. The short answer is


Web Designer=SharePoint Designer whereas Web Developer=Visual Studio



  • First of all please note that these are two completely different tools to solve two completely different types of problems.

  • SharePoint Designer is focused on Presentation and Branding.  Although, you can some what program a logic to solve some issues (like designing sequential workflows) but it is not good for programming and it is designed to do code free work.

  • SharePoint Designer is an excellent tool for rebranding the site, customizing the layout, updating CSS and designing Master Pages.


  • SharePoint Designer can talk to SharePoint natively and can display the pages with full rendering (at least 90%) of web parts.

  • SharePoint Designer is best suitable for web designers.

  • Visual Studio 2005/2008 is the tool of choice when you want to extend SharePoint functionality by writing your own custom code.

  • If you want to design portable workflows, then user Visual Studio.

  • If you want to create event handlers, custom features, site definitions, custom lists or web parts then use Visual Studio.
  • SharePoint Workflow – When To Use SharePoint Designer and When To Use Visual Studio

    SharePoint Workflow
    There are a few basic differences and assumptions between the two products and how they can produce workflow that should be kept in mind when deciding which tool to use.

    * Ease of use – SharePoint Designer is focused on web designers and as such has a lower technical for entry and use than does Visual Studio which is purely developer focused.
    * Portability – When you create a workflow in SharePoint Designer it is limited to an individual library or list. You cannot re-use the workflow elsewhere or globally. Workflow created in Visual Studio 2005 Designer on the other hand can be created as a re-usable template. You can then use/re-use that template across many sites/subsites as well as libraries and lists.
    * Workflow variables/modifications/options – When you access the out of the box web based workflow templates you are able to make choices. That is because these re-usable templates were created using Visual Studio 2005 Designer. Workflow created in SharePoint Designer is fixed and does not allow for end user choices in the workflow.
    * State and sequence – When creating a workflow within SharePoint Designer you can only create sequential ones. In Visual Studio 2005 Designer you can actually create sequential workflows as well as workflows based on state.

    In general it should be clear that when creating complex, re-usable workflow for SharePoint the clear choice is Visual Studio 2005 Designer. However if you are not a developer but need to create a rich workflow for your particular application/site then SharePoint Designer is the way to go.

    If you want to get your hands wet with a guided lab that will walk you through setting up workflow in SharePoint then see the online Technet lab Creating Workflows for Windows SharePoint Services. It's short and best of all its free so give it a whirl.

    Wednesday, July 14, 2010

    Deploy the workflow

    Deploy the workflow
    So, that's it – your workflow works and you're ready to deploy. This is the easy bit! In essence the deployment of your workflow has already happened, if you're using Visual Studio 2008 the workflow will have been automatically deployed to the site collection you specified as the development site when you first created the workflow project. However should you need to deploy the workflow to a different server or site collection then these are the steps that you'll need.

    The following steps will deploy your workflow to a site collection.

    1. Copy the DLL your workflow creates from the build directory ( inDebug) to the Global Assembly Cache (GAC)

    2. Create a directory in the features directory [C:Program FilesCommon Filesmicrosoft sharedWeb Server Extensions12TEMPLATEFEATURES] and drop both the feature.xml and workflow.xml files into the directory.

    3. Install the feature on your farm, using the following command line statements

    stsadm -o installfeature -name DocumentMoveAndShortcut

    Figure 18 – Install the feature

    4. Activate the feature to a site collection

    stsadm -o activatefeature -name DocumentMoveAndShortcut -url http://moss2007win2008

    Figure 19 – Activate the feature

    NOTE: You can usually find the STSADM command in the directory C:Program FilesCommon Filesmicrosoft sharedWeb Server Extensions12BIN

    Sequential Vs State workflows, what is the difference?

    Sequential Vs State workflows, what is the difference?
    Sequential workflow is nothing like it sounds. It does not mean that there is a single thread of activity with fixed route from start to end. A sequential workflow can have parallel tasks, can branch depending on state, properties, user response…In this case sequential simple means that the workflow has a single start point follows through a number of steps to reach a goal.

    State (machine) workflows basically mean a workflow whereby the core component (a task, a document…) can have a number of states (draft, for review, reviewed, released, approved) and the movement between each of those states is controlled, for example it may be inappropriate to move state between draft and approved without passing the other state first. State workflow has a start and a number of activities that govern state but do not necessarily have to have an end state i.e. Approval can be the best state for content but after approval it's entirely possible that the content may be reverted to draft for update.

    Check dublicate username(sql2005)

    Check dublicate username(sql2005)
    CREATE PROCEDURE UspCheckForDuplicates
    (
    @UserName VARCHAR(50) = NULL,
    @FirstName VARCHAR(50) = NULL,
    @LastName VARCHAR(50) = NULL,
    @Duplicates INT = 0
    )
    AS
    SET @Duplicates =(SELECT COUNT(*) FROM NorthWindUsers
    WHERE UserName = @UserName
    OR FirstName = @FirstName AND LastName = @LastName)
    RETURN @Duplicates

    Check ValidEmail

    Check ValidEmail - JavaScript
    function isValidEmail(emailAddressControl)
    {
    var emailPat = /^(\".*\"|[A-Za-z]\w*)@(\[\d{1,3}(\.\d{1,3}){3}]|[A-Za-z]\w*(\.[A-Za-z]\w*)+)$/;
    var emailid = emailAddressControl.value;

    var matchArray = emailid.match(emailPat);

    if (matchArray == null) {

    alert("Invalid e-mail address");

    emailAddressControl.focus();

    return false;

    }
    return true; }
    }
    ---------------------------------------------------------------
    In your web form Page_Load, you can add the following code
    --------------------------------------------------------

    if (!Page.ClientScript.IsClientScriptIncludeRegistered(typeof(pgOrders), "MyScript"))

    {

    Page.ClientScript.RegisterClientScriptInclude(typeof(pgOrders), "MyScript", "JScript.js");

    }

    ---------Explain------------------------------------------
    typeof(pgOrders)

    In this example, pgOrders is the actual type of the page in which the JavaScript is being included. This works better, because you are statically typing the reference to the page at compile time rather than dynamically determining the type of the page at runtime.
    Check ValidEmail - JavaScript
    function isValidEmail(emailAddressControl)
    {
    var emailPat = /^(\".*\"|[A-Za-z]\w*)@(\[\d{1,3}(\.\d{1,3}){3}]|[A-Za-z]\w*(\.[A-Za-z]\w*)+)$/;
    var emailid = emailAddressControl.value;

    var matchArray = emailid.match(emailPat);

    if (matchArray == null) {

    How can set the maximum limit of selections in a CheckBoxList

    How can set the maximum limit of selections in a CheckBoxList?
    hi
    this client code (js)
    --------------------------
    protected void Page_Load(object sender, EventArgs e)
    {
    string control = "chck=0; for (i=0; i < " + CheckBoxList1.Items.Count + "; ++i) if (document
    .getElementById('"+ CheckBoxList1.ClientID +"$' + i).checked) chck++; if (chck > 3){ alert('warning!!!'); return false;} else return true;";
    Button1.Attributes.Add("onclick", control);
    }

    this server side code
    -------------------------
    protected void Button1_Click1(object sender, EventArgs e)
    {
    byte check = 0;
    foreach (ListItem item in CheckBoxList1.Items)
    {
    if (item.Selected)
    check++;
    }
    if (check > 3)
    return;
    }

    protected void CustomValidator1_ServerValidate(object source, ServerValidateEventArgs args)
    {
    byte check = 0;
    foreach (ListItem item in CheckBoxList1.Items)
    {
    if (item.Selected)
    check++;
    }
    if (check > 3)
    {
    CustomValidator1.ErrorMessage = "Warning !!! ";
    args.IsValid = false;
    return;
    }
    args.IsValid = true;
    }

    CREATE GLOBAL ASSEMBLY(GAC)

    CREATE GLOBAL ASSEMBLY(GAC)
    step 1:
    create Assmbly using class library project
    step 2:
    go to visual studio command prompt -> generate Strong name key
    1.add the follwing code ==> sn -k "[DriveLetter]:\[DirectoryToPlaceKey]\[KeyName].snk"
    2.example -->sn -k "E:\Example\TestAssm\TestAssm\test.snk"

    step 3: open class libray project -> go to->Solution explorer open-> assemblyinfo.cs
    Add the code -->[assembly: AssemblyKeyFile("E:\Example\TestAssm\TestAssm\test.snk")]
    and then save to build prjoect

    step 4: again open the prompt and type the follsing command -->
    1.gacutil -I "[DriveLetter]:\[PathToBinDirectoryInVSProject]\gac.dll"
    2.gacutil -I "E:\Example\TestAssm\TestAssm\debug\testassm.dll"

    step 5:
    1.gacutil –I
    2.gacutil –I "testassm.dll"
    In this command, assembly name is the name of the assembly to install in the global assembly cache.

    note : check the Assembly : run-->c:\\windows\assembly

    Tuesday, July 13, 2010

    SPList Management by Code




    Introduction

    Working with MOSS 2007 is simple and easy since you can create your own lists and manage them through SharePoint website settings. But when we start building a website under SharePoint, we need to manage and customize these lists from the code. I created a small website using Microsoft.SharePoint.dll, to manage SharePoint lists. 

    Background 

    My website starts by accessing a SharePoint website created locally on my computer. The first step is to access the SPSite and get the current SharePoint Website (SPWeb). After this we can start with reading all the website lists and start managing them through SPList and each list has a list of SPListItem.  

    Using the code 



    Using Microsoft.SharePoint namespace, we start by getting the current SPWeb. For the SPSite we need to specify the url for the SharePoint website we are using:  

    Collapse
    public static SPWeb GetCurrentWeb()
    {
    SPSite site = new SPSite("http://localhost:48/");

    SPWeb myWeb = site.OpenWeb();

    //to enable editing from this website
    myWeb.AllowUnsafeUpdates = true;

    return myWeb;
    }

    SPWeb myWeb = SPCalenderManagerLib.SharepointManager.GetCurrentWeb();

    //fill the grid with the list of SPList
    dgvLists.DataSource = myWeb.Lists;
    dgvLists.DataBind();


    AllUnsafeUpdates is set to true since we are modifying the website lists from outside the SharePoint.

     

    As shown in the picture above, we will get all the Lists build in, or custom lists available in the current website. Now we can manage any list we need by clicking on the Edit button, or we can add a new list also from this page.

    To add a new SPList, we can use the following function: 

    Collapse
    public static Guid CreateNewList(string listName, string listDescription, SPListTemplateType type)
    {
    Guid guid = Guid.Empty;
    try

    {
    SPWeb myWeb = GetCurrentWeb();
    guid = myWeb.Lists.Add(listName, listDescription, type);
    }
    catch { }
    return guid;
    }


    Every list in SharePoint has its unique identifier, this function returns this as a guid that can be used for other purposes.  Every list has its Title, description and SPListTemplateType 

    Now to edit an existing list, we have to check first the list of available fields in this list and to determine with fields are read only, required, editable...To get the list information, we only need to know its Title or List name using the following function: 

    Collapse
    public static SPList GetList(string listName)
    {
    SPList list = null;
    try

    {
    SPWeb myWeb = GetCurrentWeb();
    list = myWeb.Lists[listName];
    }
    catch { }
    return list;
    }

    After we get the SPList, we can loop over the list Fields using the SPField list, and create a dummy table that contains the list of items that can be modified by the user (not read only fields).

    Collapse
     SPList list = SPCalenderManagerLib.SharepointManager.GetList(txtListName.Text);
    if (list != null)
    {
    dgvFields.DataSource = list.Fields;
    dgvFields.DataBind();

    DataTable dt = new DataTable();
    foreach (SPField field in list.Fields)
    {
    if (field.Title == "Property Bag")
    continue;

    if (!field.ReadOnlyField || field.Title == "ID")
    {
    DataColumn col = new DataColumn();

    col.ColumnName = field.Title;
    col.ExtendedProperties.Add("Type", field.TypeAsString);
    col.ExtendedProperties.Add("Required", field.Required);

    if (!dt.Columns.Contains(col.ColumnName))
    dt.Columns.Add(col);
    }
    }

    foreach (SPListItem item in list.Items)
    {
    DataRow row = dt.NewRow();
    foreach (SPField field in item.Fields)
    {
    if (field.Title == "Property Bag")
    continue;

    if (!field.ReadOnlyField || field.Title == "ID")
    {
    row[field.Title] = item[field.Title];
    }
    }
    dt.Rows.Add(row);
    }
    Session["CurrentTable"] = dt;
    dgv.DataSource = dt;// list.Items.GetDataTable();

    dgv.DataBind();
    }

    This step, we need to fill up the 2 grids in the page, the first one contains the List of SPField's in the SPList we are editing, and the second one contains a custom DataTable build according to a selected fields that are not  ReadOnlyField. Or if we can use the default generated DataTable:


    dgv.DataSource = list.Items.GetDataTable(); 
    dgv.DataBind();



    As shown in the figure above, you can see now the 2 grids. The second one includes only the editable data in every SPList.

    We can also add new fields to this List:

    SPList list = SPCalenderManagerLib.SharepointManager.GetList(txtListName.Text);
    if (list != null)
    {
    int type = 0;
    int.TryParse(ddlFieldTypes.SelectedValue, out type);

    list.Fields.Add(txtField.Text, (SPFieldType)type, chkRequired.Checked);
    list.Update();
    }

    For every newly added field, we need to specify the field name, SPFieldType, and whether it is required or not. list.Update() is used to add the modification to the SharePoint database. The SPFieldType is various, it can be Number, Text, another List... 

    Now, in the second grid, if we click on edit or add, then we can modify the exiting data of this SPListItem: 

    As you can see, the fields are automatically generated depending on the type of each field, the Text is replaced a textbox, the boolean is replaced by a Yes/No radiobuttons and the unknown types or readonly fields are replaced by labels.

     protected void dgv_RowCommand(object sender, GridViewCommandEventArgs e)
    {
    if (e.CommandName == "Modify")
    {
    int index = Convert.ToInt32(e.CommandArgument);
    DataTable dt = (DataTable)Session["CurrentTable"];

    DataRow row = dt.Rows[index];
    List<SpecificItem> items = new List<SpecificItem>();

    txtId.Value = row["ID"].ToString();

    foreach (DataColumn col in dt.Columns)
    {
    SpecificItem item = new SpecificItem();

    item.ID = int.Parse(row["ID"].ToString());
    item.ItemDisplay = col.ColumnName;
    item.ItemType = col.ExtendedProperties["Type"].ToString();
    item.ItemValue = row[col.ColumnName];

    items.Add(item);
    }
    Session["CurrentRow"] = items;

    rptItems.DataSource = items;
    rptItems.DataBind();
    listItems.Visible = true;
    }
    else if (e.CommandName == "Remove")
    {
    int index = Convert.ToInt32(e.CommandArgument);
    DataTable dt = (DataTable)Session["CurrentTable"];

    DataRow row = dt.Rows[index];
    int id = 0;
    int.TryParse(row["ID"].ToString(), out id);

    SPList list = SPCalenderManagerLib.SharepointManager.GetList(txtListName.Text);
    if (list != null)
    {
    list.Items.DeleteItemById(id);

    FillGrids();
    }
    }
    }

    SpecificItem is a class was created to access a custom list that will be given to the repeater in order to allow the modifications of the SPListItem easily. This class includes: 

     

    public class SpecificItem
    {
    public int ID
    {
    get;
    set;
    }
    public string ItemType
    {
    get;
    set;
    }
    public string ItemDisplay
    {
    get;
    set;
    }
    public object ItemValue
    {
    get;
    set;
    }
    }



    Now the repeater will have a datasource that includes list of  SpecificItem. For each SpecificItem, we can check the type and add the suitable control to allow the editing of the SPListItem.  


    The backward step is used upon saving. We will check the SpecificItem given to the repeater and match the types with the SPListItem and then save the SPListItem 

    SPList list = SPCalenderManagerLib.SharepointManager.GetList(txtListName.Text);
    int id = 0;
    int.TryParse(txtId.Value, out id);

    List<SpecificItem> items = new List<SpecificItem>();
    SPListItem item = null;
    if (id > 0)
    {
    item = list.Items.GetItemById(id);
    items = (List<SpecificItem>)Session["CurrentRow"];
    }
    else

    {
    item = list.Items.Add();
    DataTable dt = (DataTable)Session["CurrentTable"];
    foreach (DataColumn col in dt.Columns)
    {
    SpecificItem i = new SpecificItem();

    i.ItemDisplay = col.ColumnName;
    i.ItemType = col.ExtendedProperties["Type"].ToString();
    // i.ItemValue = row[col.ColumnName];


    items.Add(i);
    }
    }

    //
    foreach (SpecificItem i in items)
    {
    foreach (string key in Request.Form.AllKeys)
    {
    if (key.IndexOf("txt" + i.ItemType + "_" + i.ID + "_" + i.ItemDisplay.Replace(" ", "")) >= 0)
    {
    if (key.IndexOf("DateTime") >= 0)
    {
    DateTime date = new DateTime();
    DateTime.TryParse(Request.Form[key], out date);

    if (date != DateTime.MinValue)
    item[i.ItemDisplay] = date;
    }
    else

    item[i.ItemDisplay] = Request.Form[key].ToString();
    break;
    }

    if (key.IndexOf("chk" + "_" + i.ID + "_" + i.ItemDisplay.Replace(" ", "")) >= 0)
    {
    item[i.ItemDisplay] = Request.Form[key] == "yes";// Convert.ToBoolean(Request.Form[key]);

    break;
    }

    if (key.IndexOf("txt" + i.ItemType + "_" + i.ID + "_" + i.ItemDisplay.Replace(" ", "")) >= 0 && (key.IndexOf("Integer") > 0 || key.IndexOf("Number") > 0))
    {
    if (key.IndexOf("Integer") >= 0)
    {
    int val = 0;
    int.TryParse(Request.Form[key].ToString(), out val);

    item[i.ItemDisplay] = val;
    }
    else

    {
    double d = 0;
    double.TryParse(Request.Form[key].ToString(), out d);
    item[i.ItemDisplay] = d;
    }
    break;
    }
    }
    }

    item.SystemUpdate();

    The SPListItem item is an array of fields, to modify every field, we need to get the field Title and place its value. item.SystemUpdate() will save the list item into the database.   

    We can also delete the SPListItem from the list after we get the SPListItem Id, 

    list.Items.DeleteItemById(id); 

    In this way we have viewed, edited, deleted, fully managed any SPList without accessing the SharePoint website.  

    Wednesday, July 7, 2010

    backup and Restore sites[SharePoint]

    For backup use :
    step 1:
    cd C:\Program Files\Common Files\Microsoft Shared\web server extensions\12\BIN

    Step2 :
    stsadm -o backup -url "http://Siteurl" -filename C:\Backup\BackupSite.bak

    For Restore :

    stsadm -o restore -url "http://retsoredsite" -filename C:\Backup\BackupSite.bak

    Tuesday, July 6, 2010

    Clear Controls- ASP.Net

    private void ClearControls(Control parent)
    {
    foreach (Control _ChildControl in parent.Controls)
    {
    if ((_ChildControl.Controls.Count > 0))
    {
    ClearControls(_ChildControl);
    }
    else
    {
    if (_ChildControl is TextBox)
    {
    ((TextBox)_ChildControl).Text = string.Empty;
    }
    if (_ChildControl is DropDownList)
    {
    ((DropDownList)_ChildControl).SelectedIndex = 0;
    }


    }
    }
    }

    ----------------------------------------------------------------------------------
    private void ResetFormControlValues(Control parent)
    {
    foreach (Control c in parent.Controls)
    {
    if (c.Controls.Count > 0)
    {
    ResetFormControlValues(c);
    }
    else
    {
    switch(c.GetType().ToString())
    {
    case "System.Web.UI.WebControls.TextBox":
    ((TextBox)c).Text = "";
    break;
    case "System.Web.UI.WebControls.CheckBox":
    ((CheckBox)c).Checked = false;
    break;
    case "System.Web.UI.WebControls.RadioButton":
    ((RadioButton)c).Checked = false;
    break;

    }
    }
    }
    }
    ----------------------------------------------------------------
    protected void btnClearASP_Click(object sender, EventArgs e)
    {
    ResetFormControlValues(this);
    }

    Thursday, July 1, 2010

    Custom Master Page


    Create a Feature: Add Custom Master Pages to your Site Collections



    1. Navigate to the Features directory on your web server:


      Local Drive:\Program Files\Common
      Files\Microsoft Shared\web server extensions\12\TEMPLATE\FEATURES

    2. Locate the PublishingLayouts Feature directory. 
      Copy this folder and paste it at the root of Features
      Rename the folder to a unique name of your choice.  For my example I
      used CustomMasterPages.


      Location of custom feature folder

    3. Open your new Feature directory. At this point you can leave all the
      default folders, or you can choose to clear out what you don't want to use.
      You only have to keep Feature.xml and
      ProvisionedFiles.xml
      . To create a clean file set, at a minimum
      clear out the contents of each sub folder in the directory (en-us (or your
      language), Images, MasterPages, PageLayouts, Styles).

    4. To start, we need at least one master page file in the Feature folder.
      You can copy one of the existing master pages, paste the copy in the
      directory, and rename the copy to your unique name, or alternately paste
      in your custom master page, or create a new blank file with the extension of
      .master.


      Feature folder contents



      Tip! To just get a master page going,
      copy the sample code
      from this
      article
      and paste it in your custom master page file.  That will
      get you up and running for this article and give you a good starting point
      for your customizations once the master page has been applied to your site. 
      If you do this, after pasting the code into your master page file, locate
      this line of code and add a missing quotation mark:
      <asp:ContentPlaceHolder id="PlaceHolderTitleBreadcrumb"
      runat="server"/>






    5. Next, open the ProvisionedFiles.xml file in Notepad or a similar
      editing application.

      Local Drive:\Program Files\Common
      Files\Microsoft Shared\web server extensions\12\TEMPLATE\FEATURES\YourFeature

    6. We are going to delete out all of the content and only keep the

      OSGMasterPages
      Module tag and the
      PublishingLayoutsPreviewImages
      Module tag. 
      As opposed to listing out what to strip out, here is the code you need in
      this file:

      <!-- _lcid="1033"
      _version="12.0.4407" _dal="1" -->


      <!-- _LocalBinding -->

      <Elements xmlns="http://schemas.microsoft.com/sharepoint/">

      <Module Name="OSGMasterPages" Url="_catalogs/masterpage" Path="MasterPages"
      RootWebOnly="TRUE">

      <File Url="Sample.master" Type="GhostableInLibrary">

      <Property Name="ContentType" Value="My Sample Master
      Page
      " />


      <Property Name="PublishingPreviewImage" Value="~SiteCollection/_catalogs/masterpage/$Resources:core,Culture;/Preview
      Images/sample.png, ~SiteCollection/_catalogs/masterpage/$Resources:core,Culture;/Preview
      Images/sample.png" />

      <Property Name="MasterPageDescription" Value="This is
      my sample master page for use with collaboration or publishing sites.
      "
      />

      </File>


      </Module>

      <Module Name="PublishingLayoutsPreviewImages" Url="_catalogs/masterpage"
      IncludeFolders="??-??" Path="" RootWebOnly="TRUE">

      <File Url="Sample.png" Name="Preview Images/Sample.png"
      Type="GhostableInLibrary">

      </File>


      </Module>

      </Elements>

    7. Update the properties to reflect the new master page details:

      1. Change the URL to your custom master page.:

        <File Url="Sample.master" Type="GhostableInLibrary">


      2. Change the Preview Images to a custom image:

        <Property Name="PublishingPreviewImage" Value="~SiteCollection/_catalogs/masterpage/$Resources:core,Culture;/Preview
        Images/
        Sample.png, ~SiteCollection/_catalogs/masterpage/$Resources:core,Culture;/Preview
        Images/
        Sample.png" />

        Add the custom image to the following directory:

        Local Drive:\Program Files\Common
        Files\Microsoft Shared\web server extensions\12\TEMPLATE\FEATURES\PublishingLayouts\en-us


      3. Update the Description.  Enter a description for
        your master page:

        <Property Name="MasterPageDescription" Value="This is
        my sample master page for use with collaboration or publishing sites.
        "
        />

      4. Update the image names:

        <File Url="Sample.png" Name="Preview Images/Sample.png"
        Type="GhostableInLibrary">




    8. Save the ProvisionedFiles.xml file.

    9. Create a preview image in the language folder (in this case,
      en-us
      ).


      Preview image location

    10. Next, open the Feature.xml file in Notepad or a similar
      editing application.

      Local Drive:\Program Files\Common
      Files\Microsoft Shared\web server extensions\12\TEMPLATE\FEATURES\YourFeature

    11. There are four things you need to edit in this file:

      1. Change the Feature ID to a unique GUID.  You
        can generate GUIDs in Visual Studio (Tools - Create GUID - Registry
        Format - Copy). Paste the new GUID for the ID and remove the curly
        brackets.


        <Feature Id="FDFCD4C4-F0D9-43b5-8739-A33681049657"

      2. Update the title:

        Title="Custom Master Pages"

      3. Update the description:

        Description="Custom master
        pages for use across multiple site collections.
        "


      4. Change the Hidden state to False:

        Hidden="False"



    12. Save the Feature.xml file.


    13. Recycle the Application Pool for the site you plan to install the
      Feature on, or reset IIS (Command Prompt - IISRESET).

    14. You are now ready to install the new Feature on the web server. Open a
      Command Prompt and enter the following:

      1. Change directories to the BIN folder in the
        12
        hive so you can use STSADM.exe:



        cd C:\Program Files\Common Files\Microsoft Shared\web server extensions\12BIN

      2. Launch STSADM and install the feature:


        stsadm -o installfeature -name YourFeatureDirectoryName


      Tip! To access STSADM quicker, refer to

      Andrew Connell's SharePoint Developer Tip
      .


    15. Now we will activate the feature on the site.

      1. Open your site and navigate to the Site Collection Features settings
        page. Site Actions - Site Settings -
        Modify All Site Settings -
        Site Collection Features (under the Site Collection
        Administration
        submenu).


      2. The new feature will be listed:

        Custom feature in Feature list

      3. Select Activate.



    16. The master pages are now ready to use on the site. Navigate to the
      Master Page settings by selecting Site Settings in the
      breadcrumbs and choosing Master Page. (Or Site Actions -
      Site Settings -
      Modify All Site Settings -
      Master page (under the Look and Feel submenu).


    17. Depending on your requirements, in either or both the Site
      Master Page
      setting and the System Master Page setting, select your drop down box and choose your custom master page. 


      Master page selection drop down



      1. Select OK.



    18. The master page is applied to the site.  Note that I manually
      added the "Sample Master Page" text to the Sample.master file. It will not
      appear on yours by default.


      Sample Master Page



     


    Adding to our Feature: Adding More Custom Master Pages to your Feature


    If you ever need to add new master pages to this feature, you can edit the
    Feature and redeploy it.  Alternately, you can create a new Feature for
    each custom master page. For that scenario, just follow the steps above for
    creating a new feature. The following outlines how to update your Feature with
    new master pages.




    1. Navigate to your custom master page Feature directory and add the
      appropriate files for your new master pages.

    2. Navigate to and open the ProvisionedFiles.xml file. 
      Add a FILE tag block for each new master page for both the
      OSGMasterPages Module and the

      PublishingLayoutPreviewImages
      Module.  Save the file.

    3. Recycle the Application Pool for the site you plan to install the
      Feature on, or reset IIS (Command Prompt - IISRESET).

    4. You are now ready to reinstall the updated Feature on the web server. Open a
      Command Prompt and enter the following:

      1. Change directories to the BIN folder in the

        12
        hive so you can use STSADM.exe:


        cd C:\Program Files\Common Files\Microsoft Shared\web server extensions\12\BIN

      2. Launch STSADM and install the feature:

        stsadm -o installfeature -name YourFeatureDirectoryName -force



      Tip! To access STSADM quicker, refer to

      Andrew Connell's SharePoint Developer Tip
      .

    5. Now we will deactivate and reactivate the feature on the site.

      1. Open your site and navigate to the Site Collection Features settings
        page. Site Actions - Site Settings -
        Modify All Site Settings -
        Site Collection Features (under the Site Collection
        Administration
        submenu).


      2. Your existing feature will be listed:

        View of Active Feature

      3. Select Deactivate.

      4. A warning message will appear.  Select Deactivate the
        feature
        .


      5. The Feature list will reload.  Select Activate
        next to your custom feature.



    6. Your new master pages are ready for use.


     



    In my next article I will cover what to do next with your custom master
    page and how do you start customizing it.