Wednesday, 27 June 2012

Clear Team Site home.aspx by c# code

Here's how you clear the home.aspx page of a default Team Site programmatically
        public void clearContentOnMain()
        {
            try
            {
                using (SPSite site = new SPSite(TEAMSITEURL))
                {
                    using (SPWeb web = site.OpenWeb())
                    {
                        SPFile homePage = web.GetFile("SitePages/Home.aspx");
                        if (homePage.Exists)
                        {
                            homePage.Item[SPBuiltInFieldId.WikiField] = "";
                            homePage.Item.Update();

                        }
                    }
                }
            }
            catch (Exception ex)
            {
                throw new SPException("Error getting SitePages/Home.aspx " + ex.ToString());
            }

        }

Tuesday, 26 June 2012

User vs UserMulti

I spent almost a whole day trying to figure out why ViewFieldsOverride only imports the UserName of AssignedTo field in Content Query Web Part.

After trying various ways and banging my head against the table, it turns out that by changing Type="UserMulti" from Type="User", AssignedTo field will have the format 'ID;#UserName'.

Friday, 8 June 2012

Add Presence Icon to SPGridview

I spent hours trying to figure out why my presence image only appears for the last instance of the particular user, and I finally figured out why, id has to be unique.
to show image presence, I attached to rowdatabound event with the required javascript

       protected void gvProjOverview_RowDataBound(object sender, GridViewRowEventArgs e)
        { 
            if(e.Row.DataItem!=null)
            {
                SPWeb web = SPContext.Current.Web; 

                SPUser user = web.EnsureUser("DOMAIN\login");
 
                e.Row.Cells[4].Text = ""
                    + " "
                    + ""
                    + "" + user.Name +  ""
                    + "";
            }
        }

id='imn_" + e.Row.RowIndex <- this was where I had used user.ID which was not unique and thus the presence icon was only showing for one of the available users.

The lack of distinct ID causes some presence icon to disappear, that is, if user Andy is on two of the rows, the presence icon only appears for the last row where Andy is in.

Thursday, 7 June 2012

EditorWebPart wierd behavior

I was trying to implement EditorPart and I find that the webpart doesn't update when OK or Apply is clicked. Only when it's been refreshed then the changes appear.
Going through the code shows that the cycle order is : CreateChildControls ApplyChanges OnPreRender
So since I am setting the value in CreateChildControls, it was using the old value before the changes happen in ApplyChanges.
Moving code under CreateChildControls to be in OnPreRender sets automatic update when Apply/OK is clicked.

Wednesday, 6 June 2012

Extending the Content Query Web Part (ContentByQueryWebPart)

I was assigned a task to allow filtering of CQWP results without requiring the user to edit the webpart.
I figured out the following simple way to extend the CQWP by having the filtering done with a drop down list on the webpart itself.
At first I wanted to use the consumer/provider method but decided this was easier...
Here's the code:
namespace ExtendCQWP.FilterWP
{
    [ToolboxItemAttribute(false)]
    public class FilterWP: Microsoft.SharePoint.Publishing.WebControls.ContentByQueryWebPart
    {
        protected override void OnLoad(EventArgs e)
        { 
            if (this.Page.Request.QueryString["FilterField1"]!=null && this.Page.Request.QueryString["FilterValue1"]!=null)
            {
                this.FilterField1 = this.Page.Request.QueryString["FilterField1"].ToString(); 
                this.FilterValue1 = this.Page.Request.QueryString["FilterValue1"].ToString();
            }
        }
        protected override void CreateChildControls()
        {             
            DropDownList ddl = new DropDownList();
            ddl.Items.Add(new ListItem("All", "All"));            
            ddl.Items.Add(new ListItem("HR", "HR"));
            ddl.Items.Add(new ListItem("Finance", "Finance"));
            ddl.Items.Add(new ListItem("IT", "IT"));

            ddl.SelectedIndexChanged += new EventHandler(ddl_SelectedIndexChanged);
            ddl.AutoPostBack = true;
            ddl.EnableViewState = true;

            if (this.Page.Request.QueryString["FilterValue1"] != null)
            { 
                foreach(ListItem item in ddl.Items)
                    if(item.Text.Equals(this.Page.Request.QueryString["FilterValue1"].ToString()))
                    {
                        item.Selected = true;
                        break;
                    }
            }

            this.Controls.Add(ddl);            
            base.CreateChildControls();
        }

        void ddl_SelectedIndexChanged(object sender, EventArgs e)
        {
            DropDownList tmpddl = (DropDownList)sender;
            if(tmpddl.SelectedValue.Equals("All"))
                SPUtility.Redirect("http://mysite/SitePages/cq.aspx", SPRedirectFlags.Trusted, HttpContext.Current);
            else
                SPUtility.Redirect("http://mysite/SitePages/cq.aspx?FilterField1=Division&FilterValue1=" + tmpddl.SelectedValue, SPRedirectFlags.Trusted, HttpContext.Current);
        }
    }
}

Here's how the list and web part looks like.

Monday, 4 June 2012

Attempted to use an object that has ceased to exist

I received this error when trying to insert/edit web part
Attempted to use an object that has ceased to exist

The resolution was to remove USING statement when using SPContext.Current.Web;

This issue happened because SPContext.Current.Web disposes the web object automatically, and by adding a

using
statement, it will try to dispose it again when there's nothing to dispose.

SPMenuField disappears when/after Edit Mode

There has been an issue that has been bugging me when I create an SPMenuField, editing the page will result in the menu field columns disappearing.

After spending hours trialing and erroring, it was resolved by adding a .DataBind() in the Page_Load method.

UserControl.ascx.cs

        protected void Page_Load(object sender, EventArgs e)
        { 
          gvPPL.DataBind();
        }

UserControl.ascx


<SharePoint:MenuTemplate ID="gvPPLMenu" runat="server">
    <SharePoint:MenuItemTemplate ID="editMenu" runat="server" Text="Edit" ClientOnClickNavigateUrl="/_layouts/BPOSproperties/ProjectSettings.aspx?type=edit&url=%EDIT%" />
</SharePoint:MenuTemplate>
<SharePoint:SPGridView ID="gvPPL" runat="server" AutoGenerateColumns="false" DataSourceID="pplDataSource">
    <Columns>
        <SharePoint:SPMenuField HeaderText="NameMenu" TextFields="Name" MenuTemplateId="gvPPLMenu"
        NavigateUrlFields="Email" NavigateUrlFormat="{0}" TokenNameAndValueFields="EDIT=Email" />
        <SharePoint:SPBoundField HeaderText="Name" DataField="Name"  />
    </Columns>
</SharePoint:SPGridView>

<asp:ObjectDataSource ID="pplDataSource" runat="server" TypeName="BPOSsite.PeopleManager, BPOSsite, Version=1.0.0.0, Culture=neutral, PublicKeyToken=c9ab07f514f0925b" SelectMethod="GetPeople"  />

People.cs


namespace BPOSsite
{
    public class People
    {
        private string name;
        private string email;

        public People(string n, string e)
        {
            this.email = e;
            this.name = n;
        }

        public string Name
        {
            get { return name; }
            set { name = value; }
        }

        public string Email
        {
            get { return email; }
            set { email = value; }
        }
    }

    public class PeopleManager
    {
        public List<People> GetPeople()
        {
            List<People> list = new List<People>();
            list.Add(new People("John", "john@mail.com"));
            list.Add(new People("Nick", "nick@mail.com"));
            list.Add(new People("Tracy", "tracy@mail.com"));
            list.Add(new People("Dick", "dick@mail.com"));
            return list; 
        }    
    }
}

Friday, 1 June 2012

ObjectDataSource TypeName not found

In sharepoint i had to list ObjectDataSource this way

<asp:ObjectDataSource ID="pplDataSource" runat="server" TypeName="MyNameSpace.PeopleManager, MyNameSpace, Version=1.0.0.0, Culture=neutral, PublicKeyToken=c9ab07f514f0925b" SelectMethod="GetPeople"  />

else I will get 'TypeName not found' error.

Wednesday, 23 May 2012

How to create a word document with c# code

  • First download and install Open XML SDK 2.0 for Microsoft Office
  • Open the installed program, mine was located at C:\Program Files (x86)\Open XML SDK\V2.0\tool\OpenXmlSdkTool.exe
  • With the tool, open the desired word document that you want to generate with visual studio, temp.docx for example.
  • Click on 'Reflect Code' on the top pane. Notice how there will be code generated on the right hand frame.
  • In Visual Studio, create a new console application project, name it for example HelloWord. Add a new empty class WordDoc.cs and copy the above generated code to this new class file. Rename namespace to HelloWord and class to WordDoc. Here's how it looks like
  • Add the following two references
    • C:\Program Files (x86)\Open XML SDK\V2.0\lib\DocumentFormat.OpenXml.dll
    • WindowsBase from .NET (path: C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\v3.0\WindowsBase.dll)
  • add these two lines to the Main function
                WordDoc wd = new WordDoc();
                wd.CreatePackage(@"C:\temp\mydoc.docx");
    
  • Once you run the console, you should see mydoc.docx created in C:\temp.

Monday, 21 May 2012

Sharepoint 2010 Visio Workflow Visualization Error

I was faced with the following error when I tried to enable workflow visualization on SharePoint 2010

System.OperationCanceledException: The server failed to process the request. ---> System.ServiceModel.ServerTooBusyException: The HTTP service located at http://r9k7y7d:32843/80eb32d02df348f595a9d27e97f7238c/VisioGraphicsService.svc is too busy.  ---> System.Net.WebException: The remote server returned an error: (503) Server Unavailable.
   at System.Net.HttpWebRequest.EndGetResponse(IAsyncResult asyncResult)
   at System.ServiceModel.Channels.HttpChannelFactory.HttpRequestChannel.HttpChannelAsyncRequest.CompleteGetResponse(IAsyncResult result)
   --- End of inner exception stack trace ---

Server stack trace: 
   at System.ServiceModel.AsyncResult.End[TAsyncResult](IAsyncResult result)
   at System.ServiceModel.Channels.ServiceChannel.SendAsyncResult.End(SendAsyncResult result)
   at System.ServiceModel.Channels.ServiceChannel.EndCall(String action, Object[] outs, IAsyncResult result)
   at System.ServiceModel.Channels.ServiceChannelProxy.InvokeEndService(IMethodCallMessage methodCall, ProxyOperationRuntime operation)
   at System.ServiceModel.Channels.ServiceChannelProxy.Invoke(IMessage message)

Exception rethrown at [0]: 
   at System.Runtime.Remoting.Proxies.RealProxy.HandleReturnMessage(IMessage reqMsg, IMessage retMsg)
   at System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData& msgData, Int32 type)
   at Microsoft.Office.Visio.Server.GraphicsServer.IVisioGraphicsService.EndGetVectorDiagram(IAsyncResult asyncResult)
   at Microsoft.Office.Visio.Server.Administration.VisioGraphicsServiceApplicationProxy.GetVectorDiagram(VectorDiagramRequestContract vectorDiagramRequest)
   at Microsoft.Office.Visio.Server.ServiceWrapper.GetVectorDiagram(String visioFileUrl, Int32 pageNumber, Boolean disableRefresh, AddonDataSource[] dataSources)
   --- End of inner exception stack trace ---
   at Microsoft.Office.Visio.Server.ServiceWrapper.GetVectorDiagram(String visioFileUrl, Int32 pageNumber, Boolean disableRefresh, AddonDataSource[] dataSources)
   at Microsoft.Office.Visio.Server.GetDiagramAsyncTask.GetVectorDiagram()

After some tinkering and scratching my head, these are the steps I took which made it work!

  1. First follow the steps here: http://technet.microsoft.com/en-us/library/ee524058.aspx
  2. Create an apppool that uses LocalSystem.
  3. What I did at first was to use the wrong app pool for my service. When I changed the AppPool to the one with Identity: LocalSystem, it worked!

Tuesday, 15 May 2012

Auto field update for Infopath in SharePoint (part 2)

This time I have used some Jquery to decrease the lines of code,
<script src="http://code.jquery.com/jquery-latest.js">
</script>
<script type="text/javascript">

_spBodyOnLoadFunctionNames.push("FillOrWait");

var maxTime = 1000;
var waitPeriod = 500;
var totalWait = 0; 

function FillOrWait()
{

   if( $('input[title=OccupationField]').length==0 && totalWait<maxTime)
   {
      totalWait = totalWait + waitPeriod;       
      window.setTimeout(FillOrWait,waitPeriod);
   }
   else
   {
       var valueField = getQuerystring("Occupation");
       $('input[title=OccupationField]').val(valueField);
   }
}

function getQuerystring(key, default_)
{
 if (default_==null) default_="";
 key = key.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
 var regex = new RegExp("[\\?&]"+key+"=([^&#]*)");
 var qs = regex.exec(window.location.href);
 if(qs == null)
  return default_;
 else
  return qs[1];
}
 </script>

Auto field update for Infopath in SharePoint

Refering to http://hermansberghem.blogspot.com/2011/03/trick-use-query-string-values-to.html, I am able to set the title of an InfoPath form using the Advance tab. So what I did was using my previous post of javascript snippets to get the element via Input tag and Title to set the field values.

As what the reference link has indicated, my internet explorer loads javascript before the infopath form, thus the text field did not exist while the javascript was running, I have used a polling method to wait half a second interval till the element loads.


Using infopath designer, the title is set to OccupationField

This snippet is similiar from previous javascript post except for a few tweaks.

The url will be something like http://url/page.aspx?Occupation=Policeman



Monday, 14 May 2012

Infopath submit to list

Following from http://msdn.microsoft.com/en-us/library/cc162745(v=office.12).aspx

Project and EmailType list will be populated with entries from InfoPath.

So each list will require data connections of

  1. Template in xml format for retrieving data
  2. Retriving data from the SharePoint list
  3. Submit data type to the _vti_bin/lists.asmx service of the SharePoint site

Below I have for Project, AddProjectTemplate(1), TestProject(2), Web Service Submit Proj (3).
Similiarly for EmailSequence, AddEmailSequenceTemplate(1), TestEmailSequence(2), Web Service Submit(3)



FormCode.cs
using Microsoft.Office.InfoPath;
using System;
using System.Windows.Forms;
using System.Xml;
using System.Xml.XPath;
using mshtml;

namespace MyEmailType
{
    public partial class FormCode
    {
        public void InternalStartup()
        {
            EventManager.XmlEvents["/my:myFields/my:AddEmailType"].Changed += new XmlChangedEventHandler(AddEmailType_Changed);
            ((ButtonEvent)EventManager.ControlEvents["btnSubmit"]).Clicked += new ClickedEventHandler(btnSubmit_Clicked);             
            ((ButtonEvent)EventManager.ControlEvents["btnCancel"]).Clicked += new ClickedEventHandler(btnCancel_Clicked);
        }

        public void AddEmailType_Changed(object sender, XmlEventArgs e)
        {
            try
            {
                // Get a reference to the form's XmlNamespaceManager object.
                XmlNamespaceManager ns = this.NamespaceManager;

                // Create an XPathNavigator object for the form's main data
                // source.
                XPathNavigator xnDoc = this.MainDataSource.CreateNavigator();

                // If the check box is set to true, add a new row so the user 
                // can add a new contact.
                if (e.Site.Value == "true")
                {
                    XPathNavigator xnTable = xnDoc.SelectSingleNode("/my:myFields/my:gpEmailTypes", ns);
                    xnTable.AppendChild("");
                }
                else
                {
                    // If the user clears the check box, remove the added row.
                    ClearEnteredValues(xnDoc);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("AddEmailType_Changed error occurred: " + ex.Message);
                throw;
            }
        }
        private void ClearEnteredValues(XPathNavigator xnDoc)
        {
            try
            {
                // Get a reference to the form's XmlNamespaceManager object.
                XmlNamespaceManager ns = this.NamespaceManager;

                // Create an XPathNodeIterator object to get a count of the 
                // rows in the repeating table used to add new Contacts.
                XPathNodeIterator xi = xnDoc.Select(
                   "/my:myFields/my:gpEmailTypes/my:gpEmailType", ns);
                int rowCount = xi.Count;

                if (rowCount > 0)
                {
                    // Get the first and last rows (nodes) in the 
                    // repeating table.
                    XPathNavigator firstNode = xnDoc.SelectSingleNode(
                       "/my:myFields/my:gpEmailTypes/my:gpEmailType[1]", ns);
                    XPathNavigator lastNode = xnDoc.SelectSingleNode(
                       "/my:myFields/my:gpEmailTypes/my:gpEmailTypes[" +
                       rowCount + "]", ns);

                    // Delete the existing nodes using the DeleteRange method.
                    firstNode.DeleteRange(lastNode);
                }

                // Clear the check box. 
                xnDoc.SelectSingleNode(
                   "/my:myFields/my:AddEmailType", ns).SetValue("false");
            }

            catch (Exception ex)
            {
                MessageBox.Show("The following error occurred: " +
                   ex.Message);
                throw;
            }
        }

        public void btnSubmit_Clicked(object sender, ClickedEventArgs e)
        {
            try
            {                 
                XmlNamespaceManager ns = this.NamespaceManager;
 
                DataSource dsEmailSequence = this.DataSources["TestEmailSequence"];
 
                XPathNavigator xnEmailSequence = dsEmailSequence.CreateNavigator();

                XPathNodeIterator xiEmailSequence = xnEmailSequence.Select("/dfs:myFields/dfs:dataFields/d:SharePointListItem_RW", ns);
 
                DataSource dsCAML = this.DataSources["AddEmailSequenceTemplate"];
 
                XPathNavigator xnCAML = dsCAML.CreateNavigator();
 
                WebServiceConnection wsSubmit = (WebServiceConnection)this.DataConnections["Web Service Submit"];
 
                XPathNavigator xnDoc = this.MainDataSource.CreateNavigator();

                XPathNodeIterator xiNewEmailType = xnDoc.Select("/my:myFields/my:gpEmailTypes/my:gpEmailType", ns);
                string projectTitle = xnDoc.SelectSingleNode("//my:myFields/my:ProjectTitle", NamespaceManager).Value;
                if (xiNewEmailType.Count > 0)
                {
                    while (xiNewEmailType.MoveNext())
                    {
                        
                        xnCAML.SelectSingleNode("/Batch/Method/Field[@Name='Title']", ns).SetValue(projectTitle);
                        xnCAML.SelectSingleNode("/Batch/Method/Field[@Name='EmailType']", ns).SetValue(xiNewEmailType.Current.SelectSingleNode("my:EmailType",ns).Value);
                        xnCAML.SelectSingleNode("/Batch/Method/Field[@Name='SeqFrom']", ns).SetValue(xiNewEmailType.Current.SelectSingleNode("my:SeqFrom", ns).Value);
                        xnCAML.SelectSingleNode("/Batch/Method/Field[@Name='SeqTo']", ns).SetValue(xiNewEmailType.Current.SelectSingleNode("my:SeqTo", ns).Value);
                        
                        xnCAML.SelectSingleNode("/Batch/Method/@Cmd", ns).SetValue("New");
                        // Submit the new row.
                        if(xiNewEmailType.Current.SelectSingleNode("my:SeqTo", ns).Value.Length>0)
                            wsSubmit.Execute();
                    }
                }
                
                // submit form add to project's info Project list
                WebServiceConnection wsSubmitProject = (WebServiceConnection)this.DataConnections["Web Service Submit Proj"];
                DataSource dsCAMLproject = this.DataSources["AddProjectTemplate"];

                XPathNavigator xnCAMLproject = dsCAMLproject.CreateNavigator();

                xnCAMLproject.SelectSingleNode("/Batch/Method/Field[@Name='Title']", ns).SetValue(projectTitle);
                wsSubmitProject.Execute();
                this.Application.ActiveWindow.Close();
            }

            catch (Exception ex)
            {
                MessageBox.Show("The following error occurred: " + ex.Message);
                Console.WriteLine(ex.Message);
                throw;
            }
        }

        public void btnCancel_Clicked(object sender, ClickedEventArgs e)
        {
            this.Application.ActiveWindow.Close();
        }
    }
}

AddEmailSequenceTemplate.xml

<Batch OnError="Continue">
    <Method ID="1" Cmd="New">
        <Field Name='Title'></Field>
        <Field Name="EmailType"></Field>
        <Field Name="SeqFrom"></Field>
        <Field Name="SeqTo"></Field> 
        <Field Name="ID"></Field>
    </Method>
</Batch>

AddProjectTemplate.xml is similiar to above except with only Title and ID

Friday, 4 May 2012

Open an Infopath form template with Modal Dialog


<b><a onclick="javascript:openDialog();return false;" href="#" target="_self">

<span style="font-size: 12pt">Test Link</span></a> </b>

<script type="text/javascript">

function openDialog() 
{
 var options = {
      url: 'FormServerTemplates/MYINFOPATHURL',
      title: "Test",
      dialogReturnValueCallback: function (dialogResult) 
      {
                        SP.UI.ModalDialog.RefreshPage(dialogResult);
            if(dialogResult==1){     
                         }
      },
      allowMaximize:false
 };
 SP.UI.ModalDialog.showModalDialog(options);
} </script>







Infopath tutorial: http://msdn.microsoft.com/en-us/library/cc162745(v=office.12).aspx
Deploy infopath: http://msdn.microsoft.com/en-us/library/ms772110(v=office.12).aspx

Thursday, 3 May 2012

WCF DeleteObject

Because Orders table has a constaint to Order_Details table, the latter has to be deleted also with related Order.
        private void btnDelete_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                var custorder = lstOrders.SelectedItem;

                System.Type type = custorder.GetType();

                int orderid = (int)type.GetProperty("OrderID").GetValue(custorder, null);
                 
                Order odemo = ctx.Orders.Where(o => o.OrderID == orderid).ToList()[0];
                var odt = ctx.Order_Details.Where(od => od.OrderID == orderid).ToList();

                foreach(Order_Detail od in odt)
                        ctx.DeleteObject(od);

                ctx.DeleteObject(odemo);
                ctx.SaveChanges();
                MessageBox.Show("Deleted!");
                cmbCustomers_SelectionChanged(null, null);
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error: " + ex.ToString());
            }
        }

Basic Linqpad Example

Wednesday, 2 May 2012

An attempt to track an entity or complex type failed because the entity or complex type 'OrderEntryProject.NWservice.Customer' does not implement the INotifyPropertyChanged interface.

I got this error when working on a WCF application,
"An attempt to track an entity or complex type failed because the entity or complex type 'OrderEntryProject.NWservice.Customer' does not implement the INotifyPropertyChanged interface."
After editing the Reference.cs file for Customer class, based on http://msdn.microsoft.com/en-us/library/ms229614(v=vs.90).aspx,
I added the following code to implement INotifyPropertyChanged in the class Customer,

public partial class Customer :  INotifyPropertyChanged
    {
       public event PropertyChangedEventHandler PropertyChanged;

        private void NotifyPropertyChanged(String info)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(info));
            }
        }

 ......}
And the error disappears.

CAML joins revisited

Using the following list

Example:

Monday, 30 April 2012

Adding Web Part to Site Defination Default.aspx (continued)

Following the previous post, I was trying to automate adding my simple custom web part to the site defination so that the created site will appear as follow

so I tried looking at the page source using SharePoint designer, copy the defination to the default.aspx page, and it works!

The code boxed in green are the parts I copied to the default.aspx page.

Adding Web Part to Site Defination Default.aspx

Combined with examples from
http://msdn.microsoft.com/en-us/library/gg276356.aspx
http://social.msdn.microsoft.com/Forums/en/sharepointdevelopment/thread/858afd94-43cd-451f-87c4-d8530e94af4e
http://stackoverflow.com/questions/234302/how-to-add-a-web-part-page-to-a-site-definition

default.aspx

<%@ Page language="C#" MasterPageFile="~masterurl/default.master" Inherits="Microsoft.SharePoint.WebPartPages.WebPartPage,Microsoft.SharePoint,Version=14.0.0.0,Culture=neutral,PublicKeyToken=71e9bce111e9429c"  %>
<%@ Register Tagprefix="SharePoint" Namespace="Microsoft.SharePoint.WebControls" Assembly="Microsoft.SharePoint, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
<%@ Register Tagprefix="Utilities" Namespace="Microsoft.SharePoint.Utilities" Assembly="Microsoft.SharePoint, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
<%@ Register Tagprefix="asp" Namespace="System.Web.UI" Assembly="System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" %>
<%@ Register Tagprefix="WebPartPages" Namespace="Microsoft.SharePoint.WebPartPages" Assembly="Microsoft.SharePoint, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
<%@ Register TagPrefix="MyWebPartControls" Namespace="FilteredTaskSite.VisualWebPart1" Assembly="$SharePoint.Project.AssemblyFullName$" %>
<%@ Import Namespace="Microsoft.SharePoint" %>
<%@ Import Namespace="Microsoft.SharePoint.ApplicationPages" %>
<%@ Assembly Name="Microsoft.Web.CommandUI, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>

<asp:Content ContentPlaceHolderId="PlaceHolderPageTitle" runat="server">
    <SharePoint:ProjectProperty Property="Title" runat="server"/>
</asp:Content>

<asp:Content ID="Content1" ContentPlaceHolderId="PlaceHolderMain" runat="server">
<table width="100%">
    <tr>
        <td>
            <View List="108" BaseViewID="0" WebPartZoneID="Left" ContentTypeID="0x012001" WebPartOrder="4" ShowHeaderUI="FALSE"/>
        </td>
    </tr>
    <tr>
        <td>
            <MyWebPartControls:VisualWebPart1 runat="Server" />                   
        </td>     
    </tr>
    <tr>
        <td>
            <WebPartPages:WebPartZone ID="Right" runat="server" FrameType="TitleBarOnly" Title="Right" />
        </td>
    </tr>
</table>
</asp:Content>

onet.xml site

Friday, 27 April 2012

Showing Image from DB in ASP.NET

Using the Employees table within Northwind database, we are trying to get the image from the Photo column. Here are the source code: ImageHandler.ashx
using System;
using System.Web;
using System.Data.Sql;
using System.Data.SqlClient;

public class ImageHandler: IHttpHandler 
{
    public void ProcessRequest (HttpContext context) 
    {
        string _cnnString = System.Configuration.ConfigurationManager.ConnectionStrings["cnxstring"].ToString();
        SqlConnection myConnection = new SqlConnection(_cnnString); 
       
        string sql = "SELECT Photo FROM [Employees] WHERE [EmployeeID] = @ID"; 
        SqlCommand cmd = new SqlCommand(sql, myConnection);
        cmd.Parameters.Add("@ID", System.Data.SqlDbType.Int).Value = context.Request.QueryString["id"];
         
        myConnection.Open();
        byte[] pict = (byte[])cmd.ExecuteScalar();
        myConnection.Close();

        context.Response.ContentType = "image/jpg";
        context.Response.OutputStream.Write(pict, 78, pict.Length - 78); 
          
    } 
}


Default.aspx

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

<!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></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
           
        <asp:Label ID="lblResult" runat="server" ForeColor="#0066FF"></asp:Label>
    <br />
    <hr />

   <asp:Image ID="Image1" style="width:200px" Runat="server" />
       ID: <asp:TextBox ID="tbxID" runat="server"></asp:TextBox>
        <asp:Button ID="btnShow" runat="server" Text="Show" onclick="btnShow_Click" />
    </div>
    </form>
</body>
</html>

Default.aspx.cs
public partial class _Default : System.Web.UI.Page 
{
    public string _cnnString = ConfigurationManager.ConnectionStrings["NwConnectionString"].ToString();
    protected void Page_Load(object sender, EventArgs e)
    {
       
    }
    protected void btnShow_Click(object sender, EventArgs e)
    {
        Image1.ImageUrl = "~/ImageHandler.ashx?id=" + tbxID.Text;
        
    }

    
}
How it looks

View XML in IE (REST/OData call for WCF service)

When you type a REST URL on Internet explorer,
Example: http://localhost/test/_vti_bin/ListData.svc/MyContacts
you might see something like this


to view it in XML, go to Internet Explorer > Tools > Internet Options > Content > Settings > uncheck 'Turn on feed reading view'
and you will see the XML source on the browser (or you can always use the view source option)
For http://localhost/test/_vti_bin/ListData.svc/MyContacts(1)

Thursday, 26 April 2012

Edit Page Layout from SharePoint page

ListPages.aspx
<%@ Assembly Name="$SharePoint.Project.AssemblyFullName$" %>
<%@ Import Namespace="Microsoft.SharePoint.ApplicationPages" %>
<%@ Register Tagprefix="SharePoint" Namespace="Microsoft.SharePoint.WebControls" Assembly="Microsoft.SharePoint, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
<%@ Register Tagprefix="Utilities" Namespace="Microsoft.SharePoint.Utilities" Assembly="Microsoft.SharePoint, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
<%@ Register Tagprefix="asp" Namespace="System.Web.UI" Assembly="System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" %>
<%@ Import Namespace="Microsoft.SharePoint" %>
<%@ Assembly Name="Microsoft.Web.CommandUI, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="ListMasterPages.aspx.cs" Inherits="TestMasterPageList.Layouts.TestMasterPageList.ListMasterPages" DynamicMasterPageFile="~masterurl/default.master" %>

<asp:Content ID="PageHead" ContentPlaceHolderID="PlaceHolderAdditionalPageHead" runat="server">
PageHead
</asp:Content>

<asp:Content ID="Main" ContentPlaceHolderID="PlaceHolderMain" runat="server">

    <asp:Table ID="Table1" runat="server" Width="100%">
    <asp:TableRow><asp:TableCell Width="20%">
       
    <asp:GridView ID="gvMLPages" runat="server" OnRowDataBound="gvMLPages_RowDataBound">
    </asp:GridView>

    </asp:TableCell>
    
    <asp:TableCell  Width="80%">
       
    <asp:TextBox ID="tbxPageSource" runat="server" Rows="30" TextMode="MultiLine" Width="100%" BackColor="#FEE2C7" Font-Names="Lucida Console" ForeColor="#0033CC"></asp:TextBox>
    <br />
     <asp:Label ID="labelInfo" runat="server" Text="Label"></asp:Label>
     <br />
        <asp:Button ID="btnCheckOut" runat="server" Text="Check Out" OnClick="btnCheckOut_Click" />

        <asp:Button ID="btnUndoCheckout" runat="server" Text="Undo Check Out" OnClick="btnUndoCheckout_Click" />
        <asp:Button ID="btnSaveAndCheckIn" runat="server" Text="Save,CheckIn,Publish" OnClick="btnSaveAndCheckInPublish_Click" />
    <br />
        <asp:Label ID="lblCheckOut" runat="server" Text="Please check out before editing."></asp:Label>
    </asp:TableCell>
    
    </asp:TableRow>
    </asp:Table>

    
</asp:Content>

<asp:Content ID="PageTitle" ContentPlaceHolderID="PlaceHolderPageTitle" runat="server">
List Master Pages & Layouts
</asp:Content>

<asp:Content ID="PageTitleInTitleArea" ContentPlaceHolderID="PlaceHolderPageTitleInTitleArea" runat="server" >
PageTitleInTitleArea List Master Pages & Layouts
</asp:Content>


ListPages.aspx.cs
using System;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Publishing;
using Microsoft.SharePoint.WebControls;
using System.Collections.Generic;
using System.Net;
using System.Web.UI.WebControls;
using Microsoft.SharePoint.Utilities;

namespace TestMasterPageList.Layouts.TestMasterPageList
{
    public partial class ListPages : LayoutsPageBase
    { 
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                string layoutpagename = Request.QueryString["layoutpage"];

                gvMLPages.DataSource = getLayoutPages();
                gvMLPages.DataBind();

                givePageLayout(layoutpagename); 
            }
        }

        protected void gvMLPages_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {

                TableCellCollection cells = e.Row.Cells;

                foreach (TableCell cell in cells)
                {
                    cell.Text = Server.HtmlDecode(cell.Text);
                }

            }
            if (e.Row.RowType == DataControlRowType.Header)
            { 
                    e.Row.Cells[0].Text = "Page Layouts";
            }
        }
        protected void btnCheckOut_Click(object sender, EventArgs e)
        {
            lblCheckOut.Text = "Checked out " + Request.QueryString["layoutpage"];
            tbxPageSource.Enabled = true;
            string layopage = Request.QueryString["layoutpage"];
            if (layopage == null || layopage.Length == 0)
            {
                lblCheckOut.Text = "No layout page defined.";
                return;
            }
            SPWeb web = SPContext.Current.Web;
            PublishingWeb pubWeb = PublishingWeb.GetPublishingWeb(web); 

            PageLayout pagelayout = null;

            foreach (PageLayout p in pubWeb.GetAvailablePageLayouts())
            {
                if (p.Name.Equals(layopage))
                {
                    pagelayout = p;
                    
                }
            }
            SPFile aspxpage = pagelayout.ListItem.File;
            aspxpage.CheckOut();
            Response.Redirect(Request.RawUrl); 
        }


        protected void btnUndoCheckout_Click(object sender, EventArgs e)
        {
            string layopage = Request.QueryString["layoutpage"];
            tbxPageSource.Enabled = false;
            if (layopage == null || layopage.Length == 0)
            {
                lblCheckOut.Text = "No layout page defined.";
                return;
            }
            lblCheckOut.Text = "Checked out UNDO for " + Request.QueryString["layoutpage"];

            SPWeb web = SPContext.Current.Web;
            PublishingWeb pubWeb = PublishingWeb.GetPublishingWeb(web);
 

            PageLayout pagelayout = null;

            foreach (PageLayout p in pubWeb.GetAvailablePageLayouts())
            {
                if (p.Name.Equals(layopage))
                {
                    pagelayout = p;

                }
            }
            SPFile aspxpage = pagelayout.ListItem.File;
            aspxpage.UndoCheckOut();
            Response.Redirect(Request.RawUrl); 
        }

        protected void btnSaveAndCheckInPublish_Click(object sender, EventArgs e)
        {
            string layopage = Request.QueryString["layoutpage"];
            tbxPageSource.Enabled = false;
            if (layopage == null || layopage.Length == 0)
            {
                lblCheckOut.Text = "No layout page defined.";
                return;
            }

            SPWeb web = SPContext.Current.Web;
            PublishingWeb pubWeb = PublishingWeb.GetPublishingWeb(web); 

            PageLayout pagelayout = null;

            foreach (PageLayout p in pubWeb.GetAvailablePageLayouts())
            {
                if (p.Name.Equals(layopage))
                {
                    pagelayout = p;

                }
            }
            SPFile aspxpage = pagelayout.ListItem.File;

            try
            {
                System.Text.ASCIIEncoding enc = new System.Text.ASCIIEncoding();
                byte[] byteArrayFileContentsAfter = enc.GetBytes(tbxPageSource.Text);
                aspxpage.SaveBinary(byteArrayFileContentsAfter);


                aspxpage.CheckIn("page layout changed checkin ");
                aspxpage.Publish("page layout changed publish");
                aspxpage.Approve("page layout changed approved");
            }
            catch (Exception ex)
            {
                labelInfo.Text = "Error save, checkin, publish: " + ex.ToString();
            }
             

            Response.Redirect(Request.RawUrl);
        }


        private List getLayoutPages()
        {
            List webpages = new List(); 
            SPWeb web = SPContext.Current.Web;
            PublishingWeb pubWeb = PublishingWeb.GetPublishingWeb(web);
              

            foreach (PageLayout p in pubWeb.GetAvailablePageLayouts())
            {
                webpages.Add("<a href=' " + returnRaw(Request.RawUrl) + "?layoutpage=" + p.Name + "'>" + p.Name + "</a>");
            }
            return webpages;
        }
         

        private string givePageLayout(string layoutpagename)
        {
            if (layoutpagename == null || layoutpagename.Equals(""))
                layoutpagename = "pagelayoutcustom.aspx";
            SPWeb web = SPContext.Current.Web;
            PublishingWeb pubWeb = PublishingWeb.GetPublishingWeb(web); 

            PageLayout pagelayout = null;

            foreach (PageLayout p in pubWeb.GetAvailablePageLayouts())
            {
                if (p.Name.Equals(layoutpagename))
                {
                    pagelayout = p;
                    break;
                }
            }

            labelInfo.Text = pagelayout.Title;
            SPFile aspxpage = pagelayout.ListItem.File;
            using (System.IO.StreamReader reader = new System.IO.StreamReader(aspxpage.OpenBinaryStream()))
            {
                tbxPageSource.Text = reader.ReadToEnd();
            }
            string raw = Request.RawUrl;
            int lengthraw = raw.Length - (raw.Length - raw.IndexOf("?layout"));
            labelInfo.Text = layoutpagename + " [checkout status: " + aspxpage.CheckOutType.ToString() + "]" ;

            if (aspxpage.CheckOutType.Equals(SPFile.SPCheckOutType.Online))
                btnCheckOut.Enabled = false;
            if (aspxpage.CheckOutType.Equals(SPFile.SPCheckOutType.None))
            {
                tbxPageSource.Enabled = false;
                btnSaveAndCheckIn.Enabled = false;
                btnUndoCheckout.Enabled = false;
            }
            return "";
        }

        private string returnRaw(string url)
        {
            if (url.IndexOf("?layout") < 0)
                return url;
             
            return url.Substring(0, url.IndexOf("?layout"));
        
        }
    }
}

Wednesday, 25 April 2012

Windows Form ComboBox Text Filtering Drop Down


       static string[] x = { "Afghanistan", "Afgff", "Albania", "Bahrain", "Bhutan", "Cambodia", "Denmark", 
                                  "Egypt", "Finland", "Guyana", "Guinea", "Haiti", "Iceland", "Ireland", "Jamaica", "Jordan" };
       ArrayList flist = new ArrayList(x);
       public Form1()
       {
           InitializeComponent();

           this.cbxList.DropDownStyle = ComboBoxStyle.DropDown;
           this.cbxList.Items.AddRange(x);
           this.cbxList.AutoCompleteSource = AutoCompleteSource.ListItems;
           this.cbxList.AutoCompleteMode = AutoCompleteMode.Suggest;
       }


Breakdown of the ComboBox settings with help from MSDN
this.cbxList.DropDownStyle = ComboBoxStyle.DropDown;
http://msdn.microsoft.com/en-us/library/system.windows.forms.combobox.dropdownstyle.aspx
The DropDownStyle property specifies whether the list is always displayed or whether the list is displayed in a drop-down. That is, the different styles allowed are,
  • Simple - list has no drop down arrow, text editable
  • DropDown - list displayed by clicking down arrow and text is editable
  • DropDownList - Similiar to DropDown but text is not editable
this.cbxList.Items.AddRange(x);
This just adds array of items to the ComboBox. http://msdn.microsoft.com/en-us/library/system.windows.forms.combobox.objectcollection.addrange.aspx
this.cbxList.AutoCompleteSource = AutoCompleteSource.ListItems;
Gets or sets a value specifying the source of complete strings used for automatic completion. http://msdn.microsoft.com/en-us/library/system.windows.forms.textbox.autocompletesource.aspx. Values available are,
  • FileSystem
  • HistoryList
  • RecentlyUsedList
  • AllUrl
  • AllSystemSources
  • FileSystemDirectories
  • CustomSource
  • None
  • ListItems
More information at http://msdn.microsoft.com/en-us/library/system.windows.forms.autocompletesource.aspx
this.cbxList.AutoCompleteMode = AutoCompleteMode.Suggest;
Type of auto complete available
  • None
  • Suggest - filter appears at drop down
  • Append - just appends the most likely string to the text
  • SuggestAppend - Suggests AND Append
http://msdn.microsoft.com/en-us/library/system.windows.forms.autocompletemode.aspx

Tuesday, 24 April 2012

Closing popup from SharePoint modal dialog

Closing popup from SharePoint modal dialog



this.Context.Response.Write("<script type='text/javascript'>window.frameElement.commitPopup();</script>");
this.Context.Response.End();

Tuesday, 17 April 2012

Word 2010 Auto Insert Text VBA

UpdateAll() from http://www.gmayor.com/installing_macro.htm



Option Explicit

Sub ToggleHyperlinkCtrlClick()
SetFormText

UpdateAll

End Sub


Sub UpdateAll()
Dim oStory As Range
For Each oStory In ActiveDocument.StoryRanges
oStory.Fields.Update
If oStory.StoryType <> wdMainTextStory Then
While Not (oStory.NextStoryRange Is Nothing)
Set oStory = oStory.NextStoryRange
oStory.Fields.Update
Wend
End If
Next oStory
Set oStory = Nothing
End Sub



Sub SetFormText()
Dim theString As String
theString = InputBox("Type Text Please", "")
ActiveDocument.FormFields(1).TextInput.Default = theString
End Sub





To get {REF Text1}, type REF Text1, highlight and type cntrl+F9

Friday, 13 April 2012

Android switching screens

Tutorial from http://learnandroid.blogspot.com/2008/01/opening-new-screen-in-android.html

With minor changes so it works for me, I use Android 2.3.3

TestScreenActivity.java


package test.android;

import android.app.Activity;
import android.os.Bundle;
import android.content.Intent;
import android.view.View;
import android.widget.Button;
public class TestScreenActivity extends Activity
{
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

Button b = (Button)findViewById(R.id.btnClick);

b.setOnClickListener(new View.OnClickListener()
{

@Override
public void onClick(View v)
{
Intent i = new Intent(TestScreenActivity.this, Screen2.class);
startActivity(i);
}
});
}
}




main.xml


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >

<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello" />

<Button
android:id="@+id/btnClick"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button" />

</LinearLayout>


Screen2.java


package test.android;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

public class Screen2 extends Activity
{
public void onCreate(Bundle icicle)
{
super.onCreate(icicle);
setContentView(R.layout.screen2);
Button b = (Button) findViewById(R.id.btnClick2);
b.setOnClickListener(new View.OnClickListener()
{
public void onClick(View arg0) {
setResult(RESULT_OK);
finish();
}
});
}
}


screen2.xml (Note that Screen2.xml is not accepted...)


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="You are in the New Screen"
/>
<Button
android:id="@+id/btnClick2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Close"
/>

</LinearLayout>



AndroidManifest.xml



<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="test.android"
android:versionCode="1"
android:versionName="1.0" >

<uses-sdk android:minSdkVersion="10" />

<application android:icon="@drawable/ic_launcher" android:label="@string/app_name" >
<activity android:name=".TestScreenActivity" android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".Screen2" android:label="@string/app_name">
<intent-filter>
<category android:name="android.intent.category.DEFAULT"/>
</intent-filter>
</activity>
</application>
</manifest>




Thursday, 12 April 2012

Add CEWP into NewForm.aspx


InsertWebPartIntoNewFormPage("http://site/test/", "Lists/SubjectList/NewForm.aspx");


public void InsertWebPartIntoNewFormPage(string siteUrl, string pageFile)
{
using (SPSite site = new SPSite(siteUrl))
{
using (SPWeb web = site.OpenWeb())
{
ContentEditorWebPart wp = new ContentEditorWebPart();

using (SPLimitedWebPartManager manager = web.GetLimitedWebPartManager(web.Url + pageFile, PersonalizationScope.Shared))
{
manager.AddWebPart(wp, "Left", 0);
}
}
}
}

Include JavaScript with Code in CEWP

I was trying to programmatically insert a JavaScript src code into a Content Editor Web Part.


The problem was that using the Content Link, when I insert the link to the file, it worked, but when I try a

 <script src="/test/SiteAssets/World.js" type="text/javascript"></script> 


No hello box appeared!

Cost me about 3 hours when I thought I try to use

alert ('hello');

without the <script> tag in my World.js file. That worked!

Wednesday, 11 April 2012

Powershell restart features

Help function from http://sharepoint.stackexchange.com/questions/13051/powershell-script-to-check-feature-status-enabled-disabled-before-activating



function CheckSPFeatureActivated
{
param([string]$Id=$(throw "-Id parameter is required!"),
[Microsoft.SharePoint.SPFeatureScope]$Scope=$(throw "-Scope parameter is required!"),
[string]$Url)
if($Scope -ne "Farm" -and [string]::IsNullOrEmpty($Url))
{
throw "-Url parameter is required for scopes WebApplication,Site and Web"
}
$feature=$null

switch($Scope)
{
"Farm" { $feature=Get-SPFeature $Id -Farm }
"WebApplication" { $feature=Get-SPFeature $Id -WebApplication $Url }
"Site" { $feature=Get-SPFeature $Id -Site $Url –ErrorAction SilentlyContinue}
"Web" { $feature=Get-SPFeature $Id -Web $Url –ErrorAction SilentlyContinue}
}

#return if feature found or not (activated at scope) in the pipeline
$feature -ne $null
}


foreach($felement in $FEATURE_ARRAY)
{

$fActive = $FALSE
if($felement -eq "SpecialFeature")
{
$fActive = CheckSPFeatureActivated -Id $felement -Scope "Web" -Url $SUB_SITE_URL
}
else
{
$fActive = CheckSPFeatureActivated -Id $felement -Scope "Site" -Url $MAIN_URL
}

if($fActive)
{
Write-Host "Feature"$felement" is already activated. Restarting Feature." -foregroundcolor DarkCyan
if($felement -eq "SpecialFeature")
{

Write-Host "Deactivating...."
Disable-SPFeature -Identity $felement -url $SUB_SITE_URL -Confirm:$false
Write-Host "Activating..."
Enable-SPFeature -Identity $felement -url $SUB_SITE_URL

}
else
{
Write-Host "Deactivating...."
Disable-SPFeature -Identity $felement -url $MAIN_URL -Confirm:$false
Write-Host "Activating..."
Enable-SPFeature -Identity $felement -url $MAIN_URL
}
Write-Host $felement" Activated." -foregroundcolor Green
}
else
{
Write-Host $felement" not activated. " -foregroundcolor Yellow
if($felement -eq "SpecialFeature")
{
Enable-SPFeature -Identity $felement -url $SUB_SITE_URL
}
else
{
Enable-SPFeature -Identity $felement -url $MAIN_URL
}
Write-Host $felement" Activated." -foregroundcolor Green
}
}


Tuesday, 10 April 2012

Creating List Programmatically from List Defination

Referencing from http://passionatetechie.blogspot.com/2011/01/creating-list-using-list-definition.html

using (SPSite site = new SPSite(SUB_MOM_URL))
{
using (SPWeb web = site.OpenWeb())
{
web.AllowUnsafeUpdates = true;

web.Lists.Add("SubjectList", "SubjectList", "Lists/SubjectList", "4a83c786-819a-4a42-928c-15ede45a4d11", 10111, "101");
web.Update();
SPList list = web.Lists["SubjectList"];
list.OnQuickLaunch = true;
list.Update();
web.AllowUnsafeUpdates = false;

}
}



"4a83c786-819a-4a42-928c-15ede45a4d11" - Feature ID of my custom list defination

10111 - TemplateType that I have set for SubjectList when defining

Friday, 30 March 2012

Add web part to page programmatically

From
http://www.habaneros.com/blog/posts/Programmatically_change_content_on_a_Wiki_Page_in_SharePoint_2010.aspx

Adjusted slightly to work for me



protected void lblAddWP_Click(object sender, EventArgs e)
{
AddWebPartToPage(SPContext.Current.Site.OpenWeb(), lblInfo.Text + "/SitePages/Home.aspx", "ActionSubjectGridy", "Top", 0);
lblAdd.Text = "Added WP ";
}

public void AddWebPartToPage(SPWeb web, string pageUrl, string webPartName, string zoneID, int zoneIndex)
{

InsertWebPartIntoWikiPage("TopWebPart");

InsertWebPartIntoWikiPage("ActionSubjectGridy");


}



public void InsertWebPartIntoWikiPage(string webPartName)
{
string replaceToken = "{{1}}";
using (SPSite site = new SPSite(lblInfo.Text))
{
using (SPWeb web = site.OpenWeb())
{
using (SPLimitedWebPartManager manager = web.GetLimitedWebPartManager(web.Url + "/SitePages/Home.aspx", PersonalizationScope.Shared))
{
using (System.Web.UI.WebControls.WebParts.WebPart webPart = CreateWebPart(web, webPartName, manager))
{
SPFile wikiFile = web.GetFile("SitePages/Home.aspx");
string str = (string)wikiFile.Item["WikiField"];

SPLimitedWebPartManager limitedWebPartManager = wikiFile.GetLimitedWebPartManager(PersonalizationScope.Shared);

Guid storageKey = Guid.NewGuid();

string str2 = StorageKeyToID(storageKey);
webPart.ID = str2;

limitedWebPartManager.AddWebPart(webPart, "wpz", 0);

string str3 = string.Format(CultureInfo.InvariantCulture, "<div class='ms-rtestate-read ms-rte-wpbox' contentEditable='false'><div class='ms-rtestate-read {0}' id='div_{0}'></div><div style='display:none' id='vid_{0}'/></div>", new object[] { storageKey.ToString("D") });
if (str == null)
{
str = str3;
}
else
{
if (!str.Contains(replaceToken)) { str = str + str3; } else { str = str.Replace(replaceToken, str3); }
}
wikiFile.Item["WikiField"] = str;
wikiFile.Item.Update();
}
}
}
}



}

public static string StorageKeyToID(Guid storageKey) { if (!(Guid.Empty == storageKey)) { return ("g_" + storageKey.ToString().Replace('-', '_')); } return string.Empty; }

public static System.Web.UI.WebControls.WebParts.WebPart CreateWebPart(SPWeb web, string webPartName, SPLimitedWebPartManager manager)
{
SPQuery query = new SPQuery();
query.Query = String.Format(CultureInfo.CurrentCulture,
"<Where><Eq><FieldRef Name='Title'/><Value Type='Text'>{0}</Value></Eq></Where>",
webPartName);

SPList webPartGallery = null;

if (null == web.ParentWeb)
{
webPartGallery = web.GetCatalog(
SPListTemplateType.WebPartCatalog);
}
else
{
webPartGallery = web.Site.RootWeb.GetCatalog(
SPListTemplateType.WebPartCatalog);
}

SPListItemCollection webParts = webPartGallery.GetItems(query);

XmlReader xmlReader = new XmlTextReader(webParts[0].File.OpenBinaryStream());
string errorMessage;
System.Web.UI.WebControls.WebParts.WebPart webPart = manager.ImportWebPart(xmlReader, out errorMessage);

return webPart;
}

Working List Defination (Without Content Type)

schema.xml


<?xml version="1.0" encoding="utf-8"?>
<List xmlns:ows="Microsoft SharePoint" Title="MomListDefination" FolderCreation="FALSE" Direction="$Resources:Direction;" Url="Lists/MomListDefination" BaseType="0" xmlns="http://schemas.microsoft.com/sharepoint/">
<MetaData>

<Fields>
<Field ID="" Name="LinkTitle" Type="Text" DisplayName="Title" Required="TRUE"></Field>
<Field ID="" Name="Attendees" Type="UserMulti" DisplayName="Attendees" Required="False"></Field>
<Field ID="" Name="URL" Type="Text" DisplayName="URL" Required="False"></Field>
<Field ID="" Name="Start_x0020_Date_x0020_Time" Type="DateTime" Format="DateTime" DisplayName="InitiatedDate" Required="TRUE">
<Default>[today]</Default>
</Field>

</Fields>
<Views>
<View BaseViewID="0" Type="HTML" MobileView="TRUE" TabularView="FALSE">
<Toolbar Type="Standard" />
<XslLink Default="TRUE">main.xsl</XslLink>
<RowLimit Paged="TRUE">30</RowLimit>
<ViewFields>
<FieldRef Name="LinkTitleNoMenu"></FieldRef>
</ViewFields>
<Query>
<OrderBy>
<FieldRef Name="Modified" Ascending="FALSE"></FieldRef>
</OrderBy>
</Query>
<ParameterBindings>
<ParameterBinding Name="AddNewAnnouncement" Location="Resource(wss,addnewitem)" />
<ParameterBinding Name="NoAnnouncements" Location="Resource(wss,noXinviewofY_LIST)" />
<ParameterBinding Name="NoAnnouncementsHowTo" Location="Resource(wss,noXinviewofY_ONET_HOME)" />
</ParameterBindings>
</View>
<View BaseViewID="1" Type="HTML" WebPartZoneID="Main" DisplayName="$Resources:core,objectiv_schema_mwsidcamlidC24;" DefaultView="TRUE" MobileView="TRUE" MobileDefaultView="TRUE" SetupPath="pages\viewpage.aspx" ImageUrl="/_layouts/images/generic.png" Url="AllItems.aspx">
<Toolbar Type="Standard" />
<XslLink Default="TRUE">main.xsl</XslLink>
<RowLimit Paged="TRUE">30</RowLimit>
<ViewFields>
<FieldRef Name="LinkTitle"></FieldRef>
<FieldRef Name="Attendees"></FieldRef>
<FieldRef Name="URL"></FieldRef>
<FieldRef Name="Start_x0020_Date_x0020_Time"></FieldRef>
</ViewFields>
<Query>
<OrderBy>
<FieldRef Name="ID"></FieldRef>
</OrderBy>
</Query>
<ParameterBindings>
<ParameterBinding Name="NoAnnouncements" Location="Resource(wss,noXinviewofY_LIST)" />
<ParameterBinding Name="NoAnnouncementsHowTo" Location="Resource(wss,noXinviewofY_DEFAULT)" />
</ParameterBindings>
</View>
</Views>
<Forms>
<Form Type="DisplayForm" Url="DispForm.aspx" SetupPath="pages\form.aspx" WebPartZoneID="Main" />
<Form Type="EditForm" Url="EditForm.aspx" SetupPath="pages\form.aspx" WebPartZoneID="Main" />
<Form Type="NewForm" Url="NewForm.aspx" SetupPath="pages\form.aspx" WebPartZoneID="Main" />
</Forms>
</MetaData>
</List>




Thursday, 29 March 2012

Check if user field is multiple or single user



Type fieldType = sliAction.Fields[fieldName].FieldValueType;
if (fieldType.Name.Equals("SPFieldUserValue"))
{
if (sliAction[fieldName] != null)
{
SPFieldUserValueCollection userValues = new SPFieldUserValueCollection(web, sliAction[fieldName].ToString());
string usr = "";
foreach (SPFieldUserValue userV in userValues)
{
usr = usr + userV.LookupValue;
}
dr[fieldName] = usr;
}
if (sliAction["RespExt"] != null)
dr[fieldName] = sliAction["RespExt"].ToString();
}
else if(fieldType.Name.Equals("SPFieldUserValueCollection"))
{
if (sliAction[fieldName] != null)
{
SPFieldUserValueCollection userValues = new SPFieldUserValueCollection(web, sliAction[fieldName].ToString());
foreach(SPFieldUserValue spu in userValues)
dr[fieldName] = dr[fieldName] + "," + spu.User.Name;
dr[fieldName] = dr[fieldName].ToString().Substring(1, dr[fieldName].ToString().Length - 1);
}
if (sliAction["RespExt"] != null)
dr[fieldName] = sliAction["RespExt"].ToString();
}
else if (fieldType == typeof(DateTime))
{
if (sliAction[fieldName] != null)
{
string dateString = sliAction.Fields[fieldName].GetFieldValueForEdit(sliAction[fieldName]);
dr[fieldName] = dateString;
}
else
{
dr[fieldName] = "-";
}
}

else
dr[fieldName] = sliAction[fieldName];
}

Send email from SharePoint web part



protected void Button1_Click(object sender, EventArgs e)
{
try
{
MailAddress[] ma = { new MailAddress("mail@mail.com") };
SendEmail(ma, "hello world from C# ", "this is sp");
SendEmailFromSP("mail@mail.com", "hello subject from SP", "hello body");
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}

}


private void SendEmailFromSP(string address, string sub, string bd)
{
SPSite site = SPContext.Current.Site;
SPWeb thisWeb = site.OpenWeb();
string toField = address;
string subject = sub;
string body = bd;
bool success = SPUtility.SendEmail(thisWeb, true, true, toField, subject, body);
Console.WriteLine(success);
}

private void SendEmail(MailAddress[] masTo, string subject, string body)
{
using (MailMessage mail = new MailMessage())
{
mail.From = new MailAddress(SPContext.Current.Site.WebApplication.OutboundMailSenderAddress);
foreach (MailAddress ma in masTo)
mail.To.Add(ma);
mail.Subject = subject;
mail.IsBodyHtml = true;
mail.Body = body;
SmtpClient smtp = new SmtpClient(SPContext.Current.Site.WebApplication.OutboundMailServiceInstance.Server.Address);
smtp.UseDefaultCredentials = true;
smtp.Send(mail);
Label1.Text = "OK";
}
}

Wednesday, 14 March 2012

SharePoint 2010 REST with ASP.NET

From http://extendtheenterprise.com/2010/11/03/using-sharepoint-2010-rest-apis-in-asp-net/
with some changes to make it work for me.



Default.aspx


<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="SPRest._Default" %>

<!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></title>
<style type="text/css">
table.gridtbl {
background-color: orange;
font-family: tahoma;
}
table.gridtbl TR {
background-color: white;
font-family: tahoma;
}
table.gridtbl TH {
background-color:Gray;
PADDING:4px;
color: White;
font-family: tahoma;
}
table.gridtbl TD {
PADDING:4px;
font-family: tahoma;
}
</style>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:GridView ID="GridView1" runat="server" CSSClass="gridtbl" CellSpacing="1" GridLines="None"/>
</div>
</form>
</body>
</html>





Default.aspx.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using SPRest.SUB1DataContext;
using System.Net;
namespace SPRest
{
public partial class _Default : System.Web.UI.Page
{
SPRest.SUB1DataContext.SUB1DataContext context = new SPRest.SUB1DataContext.SUB1DataContext(new Uri("http://blah/_vti_bin/listdata.svc"));

protected void Page_Load(object sender, EventArgs e)
{
context.Credentials = CredentialCache.DefaultNetworkCredentials;
BindData();
}

protected void BindData()
{
var custItems = from c in context.Customer.ToList()
join d in context.Purchases.ToList()
on c.CustomerID equals d.PurchaserID into TMP
from subTMP in TMP.DefaultIfEmpty()
select new
{
c.CustomerID,
c.Name,
OrderNum =(subTMP==null)? "NA" : subTMP.OrderNumber,
Product = (subTMP==null)? "NA" : subTMP.Product,
Qty = (subTMP==null)? null : subTMP.Quantity,
Price = (subTMP==null)? null : subTMP.Price
};

GridView1.DataSource = custItems;
GridView1.DataBind();
}
}
}



Result

JQuery: SharePoint field for editform.aspx

Setting fields via JQuery route.



<script src="http://code.jquery.com/jquery-latest.js"></script>


<script type="text/javascript">


$(document).ready(function () {

$("#ctl00_m_g_1596db13_5dea_457d_9096_ec6073656ee4_ctl00_ctl05_ctl01_ctl00_ctl00_ctl04_ctl00_ctl00_TextField").val("hello");
$('input[title="Name"]').val('just testing');

});</script>



How it looks, note the HTML for the input fields.

Javascript: SharePoint field for editform.aspx

This gets the parameter value of NextSubjectID and set INPUT element with Title=SubjectID on the form to desired value.

getQueryString function found here

http://stackoverflow.com/questions/901115/get-query-string-values-in-javascript





Tuesday, 13 March 2012

JQuery with Template

Tutorial from
http://weblogs.asp.net/jan/archive/2010/10/05/getting-started-with-jquery-templates-and-sharepoint-2010.aspx

 


<script src="http://code.jquery.com/jquery.min.js" type="text/javascript"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.templates/beta1/jquery.tmpl.min.js" type="text/javascript"></script>


<script id="tasktemplate" type="text/x-jquery-tmpl">
<li>
<b class="ms-rteFontSize-4">${Title}</b> - ${StatusValue}
<div>{{html Description}}</div>
</li>
</script>

<ul id="tasksUL"></ul>

<script type="text/javascript">
$(document).ready(function () {
$.getJSON(
"../_vti_bin/listdata.svc/Tasks?$filter=StatusValue ne 'Completed'", null,
function (data) {
alert("hello " + data.d.results);
$("#tasktemplate").tmpl(data.d.results).appendTo("#tasksUL");

});
});</script>

Monday, 12 March 2012

CAML LEFT JOIN

Trying to do a left join with CAML and found out that the only way to do it is if the lists are join with the ID field.

My Lists are set up this way,




Data for ActionList



Data for SubjectList


Here is the code that returns the data table for two columns from those two list.


private DataTable getActionSubjectListData()
{
string[] fields = { "Title", "SubjectName" };
foreach (string s in fields)
{
BoundField bf = new BoundField();
bf.DataField = s;
bf.HeaderText = s;
spgActionSubjectList.Columns.Add(bf);
}

DataTable dt = new DataTable();

dt.Columns.Add(new DataColumn("Title", Type.GetType("System.String")));
dt.Columns.Add(new DataColumn("SubjectName", Type.GetType("System.String")));

SPSite oSite = SPContext.Current.Site;
SPWeb oWeb = SPContext.Current.Web;

SPList actionList = oWeb.Lists["ActionList"];
SPList subjectList = oWeb.Lists["SubjectList"];
SPField actionSubjectID = actionList.Fields["SubjectID"];
SPField subjectTitle = subjectList.Fields["Title"];
SPField subjectIDD = subjectList.Fields["SubjectID"];
SPQuery query = new SPQuery();

query.Joins = "<Join Type='LEFT' ListAlias='SubjectList'>" +
"<Eq>" +
"<FieldRef Name='" + actionSubjectID.InternalName + "' RefType='Id'/>" +
"<FieldRef List='SubjectList' Name='ID'/>" +
"</Eq>" +
"</Join>";

query.ProjectedFields = "<Field Name='SubjectName' Type='Lookup' List='SubjectList' ShowField='" + subjectTitle.InternalName + "'/> ";


query.ViewFields = "<FieldRef Name='SubjectName' />" +
"<FieldRef Name='Title' />" ;

query.Query = "";

SPListItemCollection items = actionList.GetItems(query);

foreach(SPListItem sli in items)
{
SPFieldLookupValue lkpSubjectName = new SPFieldLookupValue(sli["SubjectName"].ToString());

dt.Rows.Add(sli.Title, lkpSubjectName.LookupValue);
}
return dt;
}



Web Part

Friday, 9 March 2012

JavaScript CEWP Query and Set Data

JavaScript help from http://www.mredkj.com/tutorials/tablebasics3.html

Create a simple list call Books, and then try pasting this into a CEWP.


<table id="mytbl">
<thead>
<tr>
<th colspan="2">header...</th>
</tr>
</thead>
<tbody></tbody>
</table>
<script type="text/javascript">




SP.SOD.executeOrDelayUntilScriptLoaded(example, 'SP.js');

function example() {
var ctx = new SP.ClientContext.get_current();
var oBooksList = ctx.get_web().get_lists().getByTitle('Books');
var caml = new SP.CamlQuery();
caml.set_viewXml("<View></View>");
this.allBooks = oBooksList.getItems(caml);
ctx.load(this.allBooks);

ctx.executeQueryAsync(
Function.createDelegate(this, this.onSucceededCallback),
null);
}

function onSucceededCallback(sender, args) {
var enumerator = this.allBooks.getEnumerator();
while (enumerator.moveNext()) {
var listItem = enumerator.get_current();
addRowInnerHTML("mytbl","ID: " + listItem.get_id() + ", Title: " +
listItem.get_item("Title"));
}
}

function addRowInnerHTML(tblId, txt)
{
var tblBody = document.getElementById(tblId).tBodies[0];
var newRow = tblBody.insertRow(-1);
var newCell0 = newRow.insertCell(0);
newCell0.innerHTML = '<input type="input" value="book" style="color: blue;" />';
var newCell1 = newRow.insertCell(1);
newCell1.innerHTML = txt;
}</script>

JavaScript CEWP with Client Context

This gets the last inserted item in table TestJS which has columns ID, Title, URL.


<a href="javascript:TEST()">Click ME!</a><script type="text/javascript">


function TEST()
{
// var myQueryString = '<View/>';

var myQueryString = "<View><Query><OrderBy><FieldRef Name='Created' Ascending='False' /></OrderBy></Query><RowLimit>1</RowLimit></View>";

var myContext = new SP.ClientContext.get_current();
var myWeb = myContext.get_web();
var myList = myWeb.get_lists().getByTitle('TestJS');
var myQuery = new SP.CamlQuery();
myQuery.set_viewXml(myQueryString);
myItems = myList.getItems(myQuery);

myContext.load(myItems,'Include(ID, Title, URL)');

myContext.executeQueryAsync(Function.createDelegate(this, TestSuccess), null);

}

function TestSuccess(sender,args)
{
var county = myItems.get_count();

var tEnumerator = myItems.getEnumerator();


var tDetails = '';

var currentEnum;
while(tEnumerator.moveNext())
{
currentEnum = tEnumerator.get_current();
tDetails = tDetails + ' ' + currentEnum.get_item('Title')
+ ' ' + currentEnum.get_item('URL');

}


alert("Query Result: " + tDetails);

alert("Last value: " + currentEnum.get_item('URL'));

}</script>


Thursday, 8 March 2012

Outer Join with Linq SharePoint 2010

With help from http://www.dotnetmafia.com/blogs/dotnettipoftheday/archive/2008/10/15/my-500th-post-left-outer-joins-with-linq.aspx, this is my outer join linq



var outerX = from cust in dataContext.Customers.ToList()
join ord in dataContext.Orders.ToList()
on cust.CustomerID.ToString().Trim()
equals ord.CustomerID.CustomerID.ToString().Trim()
into CustomerInformationGroup
from item in CustomerInformationGroup.DefaultIfEmpty(
new OrdersItem { Title="-",OrderID=0,OrderDate=DateTime.Now,Quantity=0,ProductID=new ProductsItem(),CustomerID=new CustomersItem()})
select new
{
CustomerID = cust.CustomerID,
Title = cust.Title,
City = cust.City,
CustomerCountry = cust.CustomerCountry,
JoiningDate = cust.JoiningDate,
OrderTitle = item.Title
};

dataGrdCustomer.DataSource = outerX.ToList();
dataGrdCustomer.Columns.Clear();

DataGridViewTextBoxColumn custName = new DataGridViewTextBoxColumn();
custName.DataPropertyName = "Title";
custName.Name = "Title";
custName.HeaderText = "Name";

dataGrdCustomer.Columns.Add(custName);

DataGridViewTextBoxColumn custID = new DataGridViewTextBoxColumn();
custID.DataPropertyName = "CustomerID";
custID.Name = "CustomerID";
custID.HeaderText = "CustomerID";
dataGrdCustomer.Columns.Add(custID);

DataGridViewTextBoxColumn custCity = new DataGridViewTextBoxColumn();
custCity.DataPropertyName = "City";
custCity.Name = "City";
custCity.HeaderText = "City";
dataGrdCustomer.Columns.Add(custCity);

DataGridViewTextBoxColumn custCountry = new DataGridViewTextBoxColumn();
custCountry.DataPropertyName = "CustomerCountry";
custCountry.Name = "CustomerCountry";
custCountry.HeaderText = "Country";
dataGrdCustomer.Columns.Add(custCountry);

DataGridViewTextBoxColumn prodTitle = new DataGridViewTextBoxColumn();
prodTitle.DataPropertyName = "OrderTitle";
prodTitle.Name = "OrderTitle";
prodTitle.HeaderText = "OrderTitle";
dataGrdCustomer.Columns.Add(prodTitle);


Here's the output table,

Inner join with LINQ in SharePoint 2010



var x = from cust in dataContext.Customers.ToList()
join ord in dataContext.Orders.ToList()
on cust.CustomerID.ToString().Trim() equals
ord.CustomerID.CustomerID.ToString().Trim()
select new
{
CustomerID = cust.CustomerID,
Title = cust.Title,
City = cust.City,
CustomerCountry = cust.CustomerCountry,
JoiningDate = cust.JoiningDate,
OrderTitle = ord.Title
};
dataGrdCustomer.DataSource = x.ToList();

Tuesday, 6 March 2012

Caml Query Client Object

I was wondering why the list query returns ALL of my list when the reason was that I have left out the <Query> tag! This is the working version...




SP.List oList = context.Web.Lists.GetByTitle("Projects");
CamlQuery camlQuery = new CamlQuery();
camlQuery.ViewXml = "" + projectCode + "";
ListItemCollection collListItem = oList.GetItems(camlQuery);
context.Load(collListItem);
context.ExecuteQuery();

Monday, 5 March 2012

Customizing SPGridView style (with hover alt rows)

ascx


<style type="text/css">

.GridViewHeaderStyle {
background-color:#c3dde0;
border-width: 1px;
padding: 8px;
border-style: solid;
border-color: #a9c6c9;
}

.GridViewAltRowStyle
{
background-color: #F0F8FF;
font-weight: bold;
color: black;
}

.GridRowStyle
{
background-color: #E6E6FA;
font-weight: bold;
color: black;
}

.GridViewAltRowStyle:hover, .GridRowStyle:hover
{
background-color: yellow;
color: black;
font-weight: bold;
}

</style>


<SharePoint:SPGridView ID="myGridView"
runat="server" AutoGenerateColumns="false" >
</SharePoint:SPGridView>




ascx.cs


public partial class SPGridViewTestUserControl : UserControl
{
protected void Page_Load(object sender, EventArgs e)
{
string[] fields = { "ID","Name","Country","Total"};
foreach (string s in fields)
{
BoundField bf = new BoundField();
bf.DataField = s;
bf.HeaderText = s;
myGridView.Columns.Add(bf);
}


myGridView.GroupField = "Name";
myGridView.AllowGrouping = true;
myGridView.AllowGroupCollapse = true;
myGridView.AlternatingRowStyle.CssClass = "GridViewAltRowStyle";
myGridView.RowStyle.CssClass = "GridRowStyle";

myGridView.DataSource = SelectData();
myGridView.DataBind();

// if this is set before databind, it won't include the column where the grouping is (top left)
foreach (DataControlField dcf in myGridView.Columns)
{
dcf.HeaderStyle.CssClass = "GridViewHeaderStyle";
}
}


public DataTable SelectData()
{
DataTable dataSource = new DataTable();

dataSource.Columns.Add(new DataColumn("ID", Type.GetType("System.Int32")));
dataSource.Columns.Add(new DataColumn("Name", Type.GetType("System.String")));
dataSource.Columns.Add(new DataColumn("Country", Type.GetType("System.String")));
dataSource.Columns.Add(new DataColumn("Total", Type.GetType("System.Int32")));

dataSource.Rows.Add(1, "Jack", "USA", 10000);
dataSource.Rows.Add(2, "Jack", "Thailand", 15000);
dataSource.Rows.Add(3, "Jack", "Australia", 5000);
dataSource.Rows.Add(4, "Sam", "USA", 7000);
dataSource.Rows.Add(5, "Sam", "Thailand", 30000);
dataSource.Rows.Add(6, "Sam", "Australia", 8700);
dataSource.Rows.Add(7, "Andy", "USA", 3000);
dataSource.Rows.Add(8, "Andy", "Thailand", 50000);
dataSource.Rows.Add(9, "Andy", "Australia", 25000);

return dataSource;
}
}




How it looks,

Wednesday, 29 February 2012

Replace to HTML










Monday, 27 February 2012

Load a List Table dynamically with columns

This took me a while to figure out, for predefined fields like ID, Modified, Created, Title, it will still have a Hidden=True even though it is not shown in AllItems.aspx. Thus I have to check it by using the Exists method.


public void loadHeaderActionTable()
{
SPWeb web = SPContext.Current.Web;
SPList actionList = web.Lists[ActionListName];
SPListItemCollection actions = actionList.GetItems(myActionListView);

TableRow header = new TableRow();
foreach (SPField fItem in actions.Fields)
{

if (!fItem.Hidden
&& myActionListView.ViewFields.Exists(fItem.InternalName))
{

TableCell cItem = new TableCell();
cItem.Text = fItem.Title.ToString();
cItem.CssClass = "ms-vh-div";
header.Cells.Add(cItem);
myActionColumnTitle.Add(cItem.Text);

}
}
tblACList.Rows.Add(header);

}

Friday, 24 February 2012

Working List Defination

Elements.xml


<?xml version="1.0" encoding="utf-8"?>
<Elements xmlns="http://schemas.microsoft.com/sharepoint/">
<Field ID="{9814D5C4-1A49-42A7-8229-06288E2E4C3F}" Name="ActionID" Type="Text" DisplayName="ActionID" Required="TRUE"></Field>
<Field ID="{271C7377-6800-4CD8-8120-D794BA90B023}" Name="Title" Type="Text" DisplayName="Title" Required="TRUE"></Field>
<Field ID="{FAE223E3-D53F-4886-9021-286C96728696}" Name="AssignedTo" Type="UserMulti" DisplayName="Resp" Required="False"></Field>
<Field ID="{A31215AF-BCD1-401D-899F-F6B2A7F77AAD}" Name="InitiatedDate" Type="DateTime" Format="DateOnly" DisplayName="InitiatedDate" Required="TRUE">
<Default>[today]</Default>
</Field>
<Field ID="{CFEE2340-8D7F-4BE9-8FE7-15DA5A255B50}" Name="TargetDate" Type="DateTime" Format="DateOnly" DisplayName="TargetDate" Required="FALSE">
<Default></Default>
</Field>
<Field ID="{E40F6006-2A64-43B9-B11F-BADD96C1ECCE}" Name="ClosedDate" Type="DateTime" Format="DateOnly" DisplayName="ClosedDate" Required="FALSE">
<Default></Default>
</Field>
<Field ID="{50B78056-F0B3-4B5B-B71F-DABD97E8D49F}" Name="Comments" Type="Note" DisplayName="Comments" Required="FALSE" NumLines="5"></Field>
<Field ID="{21D31AC1-2959-4794-84F5-C5C2CC48D06D}" Name="SubjectID" Type="Lookup" DisplayName="SubjectID" List="Lists/SubjectList" ShowField="SubjectID" Required="TRUE"></Field>

<ContentType
ID="0x0100A5D7A562B9B440FEBA25E181C4A3A098"
Name="ActionList"
Group="Action Content Type"
Description="Action List"
Version="0">
<FieldRefs>
<FieldRef ID="{9814D5C4-1A49-42A7-8229-06288E2E4C3F}" />
<FieldRef ID="{271C7377-6800-4CD8-8120-D794BA90B023}" />
<FieldRef ID="{FAE223E3-D53F-4886-9021-286C96728696}" />
<FieldRef ID="{A31215AF-BCD1-401D-899F-F6B2A7F77AAD}" />
<FieldRef ID="{CFEE2340-8D7F-4BE9-8FE7-15DA5A255B50}" />
<FieldRef ID="{E40F6006-2A64-43B9-B11F-BADD96C1ECCE}" />
<FieldRef ID="{50B78056-F0B3-4B5B-B71F-DABD97E8D49F}" />
<FieldRef ID="{21D31AC1-2959-4794-84F5-C5C2CC48D06D}" />
</FieldRefs>
</ContentType>

<!-- Do not change the value of the Name attribute below.
If it does not match the folder name of the List Definition
project item, an error will occur when the project is run. -->
<ListTemplate
Name="ListDefinition1"
Type="10001"
AllowDeletion="TRUE"
DisallowContentTypes="FALSE"
BaseType="0"
OnQuickLaunch="FALSE"
SecurityBits="11"
Sequence="410"
DisplayName="ActionList"
Description="My Action List Definition"
Image="/_layouts/images/itgen.gif"/>
</Elements>


Schema.xml



<?xml version="1.0" encoding="utf-8"?>
<List EnableContentTypes="TRUE" xmlns:ows="Microsoft SharePoint" Title="ActionList" FolderCreation="FALSE" Direction="$Resources:Direction;" Url="Lists/ActionList-ListDefinition1" BaseType="0" xmlns="http://schemas.microsoft.com/sharepoint/">
<MetaData>
<ContentTypes>
<ContentTypeRef ID="0x0100A5D7A562B9B440FEBA25E181C4A3A098" />
<ContentTypeRef ID="0x01">
<Folder TargetName="Item" />
</ContentTypeRef>
<ContentTypeRef ID="0x0120" />
</ContentTypes>

<Fields>
<Field ID="{9814D5C4-1A49-42A7-8229-06288E2E4C3F}" Name="ActionID" Type="Text" DisplayName="ActionID" Required="TRUE" ></Field>
<Field ID="{271C7377-6800-4CD8-8120-D794BA90B023}" Name="Title" Type="Text" DisplayName="Title" Required="TRUE"></Field>
<Field ID="{FAE223E3-D53F-4886-9021-286C96728696}" Name="AssignedTo" Type="UserMulti" DisplayName="Resp" Required="False"></Field>
<Field ID="{A31215AF-BCD1-401D-899F-F6B2A7F77AAD}" Name="InitiatedDate" Type="DateTime" Format="DateOnly" DisplayName="Initiated Date" Required="TRUE">
<Default>[today]</Default>
</Field>
<Field ID="{CFEE2340-8D7F-4BE9-8FE7-15DA5A255B50}" Name="TargetDate" Type="DateTime" Format="DateOnly" DisplayName="TargetDate" Required="FALSE">
<Default></Default>
</Field>
<Field ID="{E40F6006-2A64-43B9-B11F-BADD96C1ECCE}" Name="ClosedDate" Type="DateTime" Format="DateOnly" DisplayName="ClosedDate" Required="FALSE">
<Default></Default>
</Field>
<Field ID="{50B78056-F0B3-4B5B-B71F-DABD97E8D49F}" Name="Comments" Type="Note" DisplayName="Comments" Required="FALSE" NumLines="5"></Field>
<Field ID="{21D31AC1-2959-4794-84F5-C5C2CC48D06D}" Name="SubjectID" Type="Lookup" DisplayName="SubjectID" List="Lists/SubjectList" ShowField="SubjectID" Required="TRUE"></Field>

</Fields>
<Views>
<View BaseViewID="0" Type="HTML" MobileView="TRUE" TabularView="FALSE">
<Toolbar Type="Standard" />
<XslLink Default="TRUE">main.xsl</XslLink>
<RowLimit Paged="TRUE">30</RowLimit>
<ViewFields>
<FieldRef Name="LinkTitleNoMenu"></FieldRef>
</ViewFields>
<Query>
<OrderBy>
<FieldRef Name="Modified" Ascending="FALSE"></FieldRef>
</OrderBy>
</Query>
<ParameterBindings>
<ParameterBinding Name="AddNewAnnouncement" Location="Resource(wss,addnewitem)" />
<ParameterBinding Name="NoAnnouncements" Location="Resource(wss,noXinviewofY_LIST)" />
<ParameterBinding Name="NoAnnouncementsHowTo" Location="Resource(wss,noXinviewofY_ONET_HOME)" />
</ParameterBindings>
</View>
<View BaseViewID="1" Type="HTML" WebPartZoneID="Main" DisplayName="$Resources:core,objectiv_schema_mwsidcamlidC24;" DefaultView="TRUE" MobileView="TRUE" MobileDefaultView="TRUE" SetupPath="pages\viewpage.aspx" ImageUrl="/_layouts/images/generic.png" Url="AllItems.aspx">
<Toolbar Type="Standard" />
<XslLink Default="TRUE">main.xsl</XslLink>
<RowLimit Paged="TRUE">30</RowLimit>
<ViewFields>
<FieldRef Name="ActionID"></FieldRef>
<FieldRef Name="LinkTitle"></FieldRef>
<FieldRef Name="AssignedTo"></FieldRef>
<FieldRef Name="InitiatedDate"></FieldRef>
<FieldRef Name="TargetDate"></FieldRef>
<FieldRef Name="ClosedDate"></FieldRef>
<FieldRef Name="Comments"></FieldRef>
<FieldRef Name="SubjectID"></FieldRef>
</ViewFields>
<Query>
<OrderBy>
<FieldRef Name="ID"></FieldRef>
</OrderBy>
</Query>
<ParameterBindings>
<ParameterBinding Name="NoAnnouncements" Location="Resource(wss,noXinviewofY_LIST)" />
<ParameterBinding Name="NoAnnouncementsHowTo" Location="Resource(wss,noXinviewofY_DEFAULT)" />
</ParameterBindings>
</View>
</Views>
<Forms>
<Form Type="DisplayForm" Url="DispForm.aspx" SetupPath="pages\form.aspx" WebPartZoneID="Main" />
<Form Type="EditForm" Url="EditForm.aspx" SetupPath="pages\form.aspx" WebPartZoneID="Main" />
<Form Type="NewForm" Url="NewForm.aspx" SetupPath="pages\form.aspx" WebPartZoneID="Main" />
</Forms>
</MetaData>
</List>


ListInstance's Element.xml


<?xml version="1.0" encoding="utf-8"?>
<Elements xmlns="http://schemas.microsoft.com/sharepoint/">
<ListInstance Title="ActionList"
OnQuickLaunch="TRUE"
TemplateType="10001"
Url="Lists/ActionList"
Description="My List Instance">
<Data>
<Rows>
</Rows>
</Data>
</ListInstance>
</Elements>