Tuesday, January 3, 2012

Inserting Listitem inside a SubFolder using Javascript Querying SharePoint

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default15.aspx.cs" Inherits="Default15" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>Untitled Page</title>
    <script language="javascript" type="text/javascript" src="http://agmsm:9999/sites/Venkat/Sample/My%20Documents/SPAPI_Core.js"></script>
    <script language="javascript" type="text/javascript" src="http://agmsm:9999/sites/Venkat/Sample/My%20Documents/SPAPI_Lists.js"></script>
    <script language="javascript" type="text/javascript">
    function saveRecordInsideSubFolder()
    {
    var strUrl="http://agmsm:9999/sites/Venkat/Sample/";
        var lists = new SPAPI_Lists(strUrl);
        var FolderUrl=strUrl+"Lists/MyList/Testfolder2/"+document.getElementById("ddlSubFolderName").options(document.getElementById("ddlSubFolderName").selectedIndex).value;
        //alert(FolderUrl);
        //var res=lists.quickAddListItem();
        var strSaveItem=document.getElementById("txtSaveRecord").value;
        var res = lists.quickAddListItem('MyList', [{ Title:strSaveItem}],FolderUrl);
        if(res.status==200)
        {
            alert('Insertion Successful');
            alert(res.responseText);
        }
        else
        {
            alert('There was an error' +res.responseText);
        }

            document.getElementById("txtSaveRecord").value="";
    }
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <select id="ddlSubFolderName">
    <option value="Select">Select</option>
    <option value="Test001">Test001</option>
    <option value="Test002">Test002</option>
    <option value="Test003">Test003</option>
    <option value="Test004">Test004</option>
    <option value="Test005">Test005</option>
    <option value="Test006">Test006</option>
    <option value="Test007">Test007</option>
    <option value="Test008">Test008</option>
    <option value="Test009">Test009</option>
    <option value="Test010">Test010</option>
    <option value="Test011">Test011</option>
    <option value="Test012">Test012</option>
    <option value="Test013">Test013</option>
    <option value="Test014">Test014</option>
    <option value="Test015">Test015</option>
    <option value="Test017">Test017</option>
    <option value="Test020">Test020</option>
    </select>
        <br />
        <input type="text" id="txtSaveRecord" />
        <br />
        <input type="button" onclick="saveRecordInsideSubFolder();" value="Save Record " id="Button1"/>
    </div>
    </form>
</body>
</html>

Creating a SubFolder Using JavaScript Querying SharePoint

<script language="javascript" type="text/javascript" src="http://agmsm:9999/sites/Venkat/Sample/My%20Documents/SPAPI_Core.js"></script>
    <script language="javascript" type="text/javascript" src="http://agmsm:9999/sites/Venkat/Sample/My%20Documents/SPAPI_Lists.js"></script>
    <script language="javascript">
function CreateSubFolder()
{
var lists = new SPAPI_Lists('http://agmsm:9999/sites/Venkat/Sample/');
    
var res = lists.createFolder('MyList', document.getElementById("txtCreateSubFolder").value, 'http://agmsm:9999/sites/Venkat/Sample/Lists/MyList/Testfolder2');
if (res.status == 200)
{
  alert('The folder was created.');
}
else
{
 alert('Folder Already Existing');
}
}

    </script>

Retrieving subsites under the topsite to a spgridview

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using Webs;
using System.Xml;
public partial class Default11 : System.Web.UI.Page
{
    DataSet dset = new DataSet();
    //DataSet dset1 = new DataSet();
    //DataTable dt = new DataTable();   
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
           
            Webs.Webs web_Service = new Webs.Webs();
            web_Service.UseDefaultCredentials=true;
            web_Service.Url = "http://agmsm:9999/sites/mnet/venkat/_vti_bin/webs.asmx";
            System.Xml.XmlNode nodeListItems = web_Service.GetWebCollection();
            DataSet ds = getData(nodeListItems);
            DataTable  dt = ds.Tables["Web"];
            GridView1.DataSource = dt;
            GridView1.DataBind();
            Response.Write("<Table>");
            Response.Write("<Tr>");
            Response.Write("<Td>");
            Response.Write("Subsites List");
            Response.Write("</Td>");
            Response.Write("</Tr>");
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                string strTitle = dt.Rows[i]["Title"].ToString();
                string strUrl = dt.Rows[i]["Url"].ToString();
                Response.Write("<Tr>");
                Response.Write("<Td>");
                Response.Write("<A href='"+strUrl+"'>"+strTitle+"</A>");
                Response.Write("</Td>");
                Response.Write("</Tr>");
            }
            Response.Write("</Table>");
        }
    }
    public DataSet getData(XmlNode xmlnodeinput)
    {
        if (xmlnodeinput != null)
        {
            XmlTextReader xtr = new XmlTextReader(xmlnodeinput.OuterXml, XmlNodeType.Element, null);
            //dataset = new DataSet();
            dset.ReadXml(xtr);
        }
        return dset;
    }
    /*public DataSet getData1(XmlNode xmlnodeinput)
    {
        if (xmlnodeinput != null)
        {
            XmlTextReader xtr = new XmlTextReader(xmlnodeinput.OuterXml, XmlNodeType.Element, null);
            //dataset = new DataSet();
            dset1.ReadXml(xtr);
        }
        return dset1;
    }*/
    
}

Binding Events to calendar based on Calendar Date

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using Prasad;
using System.Xml;
public partial class Default10 : System.Web.UI.Page
{
    DataSet dset = new DataSet();
    protected void Page_Load(object sender, EventArgs e)
    {

    }

    protected void Calendar1_SelectionChanged(object sender, EventArgs e)
    {
     
       
     DateTime dtNow=  Calendar1.SelectedDate;
     string toDayFormat = dtNow.ToString("u");
     string[] EventStartDate = toDayFormat.Split(new Char[] { ' ' });
    
      
        Prasad.Lists listService = new Prasad.Lists();
        listService.UseDefaultCredentials=true;
        listService.Url = "http://agmsm:9999/sites/mnet/venkat/_vti_bin/Lists.asmx";
        string strListName = "Events";
        System.Xml.XmlDocument xmlDoc = new System.Xml.XmlDocument();
        System.Xml.XmlElement query = xmlDoc.CreateElement("Query");

        System.Xml.XmlElement viewFields = xmlDoc.CreateElement("ViewFields");
        System.Xml.XmlElement queryOptions = xmlDoc.CreateElement("QueryOptions");
        viewFields.InnerXml = "<FieldRef Name=\"ID\" /><FieldRef Name=\"Title\" /><FieldRef Name=\"EventDate\" /><FieldRef Name=\"Location\" />";
        //string strDate=Calendar1.s
        //2010-08-10T00:00:00Z
        //8/11/2010 12:00:00 AM
        query.InnerXml = "<OrderBy><FieldRef Name='ID' Ascending='False' /></OrderBy><Where><Eq><FieldRef Name='EventDate' /><Value Type='DateTime'>" + EventStartDate[0] + "</Value></Eq></Where>";
        System.Xml.XmlNode nodeListItems = listService.GetListItems(strListName, null, query, viewFields, null, null, null);
        //System.Xml.XmlNode nodeListItems = listService.GetListItems(listName, viewName, query, viewFields, rowLimit, queryOptions, null);
        DataSet ds = getData(nodeListItems);
        DataTable dt = ds.Tables["row"];
        GridView1.DataSource = dt;
        GridView1.DataBind();
        System.Xml.XmlElement batchElement = xmlDoc.CreateElement("Batch");
        batchElement.SetAttribute("OnError", "Continue");
        batchElement.SetAttribute("ListVersion", "1");
    }
    public DataSet getData(XmlNode xmlnodeinput)
    {
        if (xmlnodeinput != null)
        {
            XmlTextReader xtr = new XmlTextReader(xmlnodeinput.OuterXml, XmlNodeType.Element, null);
            //dataset = new DataSet();
            dset.ReadXml(xtr);
        }
        return dset;
    }
    protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            e.Row.Cells[2].Text = Convert.ToDateTime(e.Row.Cells[2].Text).ToShortDateString();
        }
    }
}

Uploading a document to a document library

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Net;
using System.IO;
using System.Xml;
using MySite;
using System.Text;
public partial class Add_New_Document : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void btnUpload_Click(object sender, EventArgs e)
    {
        
        

        //Create a filestream containing the document you want to upload

    FileStream oSourceFile = File.OpenRead(fuBrowse.PostedFile.FileName);

  //Create a webrequest pointing to the site and document library you want to

     //upload the document to. In addition specify the document name
         string strOnlyFile = fuBrowse.PostedFile.FileName;

        //onlyFile=onlyFile.Substring
        strOnlyFile = strOnlyFile.Substring((fuBrowse.PostedFile.FileName).LastIndexOf(@"\") + 1);
        string strCompleteFile="http://agmsm:9999/sites/mnet/venkat/UserPages/"+strOnlyFile;
     WebRequest oWr = WebRequest.Create(strCompleteFile);

     oWr.Method = "PUT";

     oWr.Headers.Add("Overwrite", "F");

     //oWr.Timeout = Timeout.Infinite;

   oWr.Credentials = CredentialCache.DefaultCredentials;

    

    //Literally copy the bytes of the filestream into the request stream to "upload" the document to the library

  byte[] oBytes = new byte[1024];

  using (Stream oRq = oWr.GetRequestStream())

  {

           for (; ; )

           {

               int iBytes = oSourceFile.Read(oBytes, 0, oBytes.Length);

               if (iBytes <= 0)

                  break;

               oRq.Write(oBytes, 0, iBytes);

          }

           oSourceFile.Close();

    }

    WebResponse oResponse = oWr.GetResponse();

    

    //Now create the XML to submit to the list service web service

    StringBuilder oSb = new StringBuilder();

    oSb.Append("<Method ID='1' Cmd='Update'>");

    oSb.Append("  <Field Name='ID'/>");

    oSb.Append("  <Field Name='FileRef'>"+strCompleteFile+"</Field>");

    //Change the title of the document - replace or add to the document properties as necessary

    oSb.Append("  <Field Name='Title'>New Title</Field>");

    oSb.Append("</Method>");

    

    XmlDocument oDoc = new System.Xml.XmlDocument();

    XmlElement oXBatch = oDoc.CreateElement("Batch");

    oXBatch.SetAttribute("OnError", "Continue");

    oXBatch.SetAttribute("PreCalc", "TRUE");

    oXBatch.SetAttribute("ListVersion", "0");

    oXBatch.InnerXml = oSb.ToString();

    

    //Do the update replace the ListWebService object with your web service object

    MySite.Lists oLstSvc = new MySite.Lists();

    oLstSvc.Credentials = CredentialCache.DefaultNetworkCredentials;

    XmlNode oRet = oLstSvc.UpdateListItems("UserPages", oXBatch);
    Page.RegisterClientScriptBlock("alert", "<Script language='Javascript'>alert('Document Uploaded Successfully');</Script>");
        
    }
}

Binding data to Asp.Net GridView

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using SharePoint2010Test;
using System.Xml;
public partial class SharePoint_2010_Default2 : System.Web.UI.Page
{
    DataSet dset = new DataSet();
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            SharePoint2010Test.Lists listService = new SharePoint2010Test.Lists();
            listService.UseDefaultCredentials=true;
            listService.Url = "http://agmsm:9999/sites/venkat/_vti_bin/Lists.asmx";
            //string strListName = "{296A9F52-5A48-4CB9-9294-47F93DF2F85F}";
            string strListName = "Tasks";
            System.Xml.XmlDocument xmlDoc = new System.Xml.XmlDocument();
            System.Xml.XmlElement query = xmlDoc.CreateElement("Query");

            System.Xml.XmlElement viewFields = xmlDoc.CreateElement("ViewFields");
            System.Xml.XmlElement queryOptions = xmlDoc.CreateElement("QueryOptions");
            viewFields.InnerXml = "<FieldRef Name=\"ID\" /><FieldRef Name=\"Title\" /><FieldRef Name=\"Status\" /><FieldRef Name=\"Priority\" /><FieldRef Name=\"AssignedTo\" />";

            query.InnerXml = "<OrderBy><FieldRef Name='ID' Ascending='False' /></OrderBy>";
            System.Xml.XmlNode nodeListItems = listService.GetListItems(strListName, null, query, viewFields, "5", null, null);
            //System.Xml.XmlNode nodeListItems = listService.GetListItems(listName, viewName, query, viewFields, rowLimit, queryOptions, null);
            DataSet ds = getData(nodeListItems);
            DataTable dt = ds.Tables["row"];
            GridView1.DataSource = dt;
            GridView1.DataBind();
            System.Xml.XmlElement batchElement = xmlDoc.CreateElement("Batch");
            batchElement.SetAttribute("OnError", "Continue");
            batchElement.SetAttribute("ListVersion", "1");
            Response.Write("<Table width='100%'>");
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                string strID = dt.Rows[i]["ows_ID"].ToString();
                string strTitle = dt.Rows[i]["ows_Title"].ToString();
                string strStatus = dt.Rows[i]["ows_Status"].ToString();
                string strPriority = dt.Rows[i]["ows_Priority"].ToString();
                string strAssignedTo = dt.Rows[i]["ows_AssignedTo"].ToString();
                strAssignedTo = strAssignedTo.Substring(strAssignedTo.IndexOf('#') + 1);
                Response.Write("<Tr>");
                Response.Write("<Td>");
                Response.Write(strID);
                Response.Write("</Td>");
                Response.Write("<Td>");
                Response.Write(strTitle);
                Response.Write("</Td>");
                if (strStatus == "Not Started")
                {
                    Response.Write("<Td bgcolor='Red'>");

                }
                else if (strStatus == "Completed")
                {
                    Response.Write("<Td bgcolor='Green'>");
                }
                else if (strStatus == "In Progress")
                {
                    Response.Write("<Td bgcolor='Orange'>");
                }
                else if (strStatus == "Deferred")
                {
                    Response.Write("<Td bgcolor='Pink'>");
                }
                Response.Write("<Strong>");
                Response.Write("<Font Color='White'>");
                Response.Write(strStatus);
                Response.Write("</Font>");
                Response.Write("</Strong>");
                Response.Write("</Td>");
                Response.Write("<Td>");
                Response.Write(strPriority);
                Response.Write("</Td>");
                Response.Write("<Td>");
                Response.Write(strAssignedTo);
                Response.Write("</Td>");
                Response.Write("</Tr>");
                Response.Write("<Tr>");
                Response.Write("<Td bgcolor='blue' colspan='5'>");
                Response.Write("</Td>");
                Response.Write("</Tr>");

            }
            Response.Write("</Table>");
            try
            {
                //listService.UpdateListItems(listName, batchElement);
                //XmlNode strNode = listService.UpdateListItems(strListName, batchElement);
                //Response.Write("Response " + strNode.OuterXml);
            }
            catch (System.Web.Services.Protocols.SoapException ex)
            {
                Response.Write("Message:" + ex.Message);
            }
        }

    }
    public DataSet getData(XmlNode xmlnodeinput)
    {
        if (xmlnodeinput != null)
        {
            XmlTextReader xtr = new XmlTextReader(xmlnodeinput.OuterXml, XmlNodeType.Element, null);
            //dataset = new DataSet();
            if (xtr != null)
            {
                dset.ReadXml(xtr);
            }
        }
        return dset;
    }
    protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        e.Row.Cells[3].Text = e.Row.Cells[3].Text.Substring(e.Row.Cells[3].Text.IndexOf('#') + 1);
    }
}

Insertion into a SharePoint List

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using SharePoint2010Test;
using InsertSampleService;
using System.Xml;
public partial class SharePoint_2010_Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        
    }
    protected void btnSave_Click(object sender, EventArgs e)
    {
        string strInsertCommand = string.Empty;
        strInsertCommand = "<Method ID='1' Cmd='New'><Field Name='Title'>" + txtUserName.Text + "</Field><Field Name='Test'>" + txtPassword.Text + "</Field></Method>";
        InsertSampleService.Lists objLogin = new InsertSampleService.Lists();
        objLogin.UseDefaultCredentials=true;
        objLogin.Url = "http://agmsm:9999/sites/Venkat/_vti_bin/Lists.asmx";
        string strListName = "Test";
        XmlDocument xmlDoc = new System.Xml.XmlDocument();

        System.Xml.XmlElement elBatch = xmlDoc.CreateElement("Batch");

        elBatch.SetAttribute("OnError", "Continue");

        elBatch.SetAttribute("ListVersion", "1");

        elBatch.InnerXml = strInsertCommand;

        XmlNode ndReturn = objLogin.UpdateListItems(strListName, elBatch);

        string result = ndReturn.OuterXml.ToString();
        txtUserName.Text = "";
        txtPassword.Text = "";
        txtUserName.Focus();
    }
}