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