Sunday, November 4, 2012

Flyout Quick Launch Menu

Find:
 <SharePoint:AspMenu id=”V4QuickLaunchMenu”
 V4QuickLaunchMenu
Set StaticDisplayLevels and MaximumDynamicDisplayLevels to 1.
Open _styles\corev4.css
find the below section and add the background color so that it's not transparent.
.s4-ql ul.root ul > li > a{
/* ADD THIS */
background-color:white;

Wednesday, July 25, 2012

Set field to read only on EditForm


Solution: Open Sharepoint Designer, select “Lists and Libraries” then select the list, then select “EditForm.aspx” from “Forms” panel.

Select “Advanced Mode.”

Click “Preview in Browser” and set the value in the field to something distinctive (e.g. “Wokka Wokka”)

From the browser, select “View Source” and search for the distinctive text.

You will see something like this:

<input name="ctl00$TextField" type="text" value="wokka wokka" maxlength="255" id="ctl00_ctl00_ctl00_TextField" title="Title" class="ms-long ms-spellcheck-true" /><br />

Copy the value in “id” into the text below, then go back to Sharepoint Designer and append that text at the bottom of the EditForm.aspx file.

Click Preview In Browser again and the field should be read only.

<asp:Content ID="Script" ContentPlaceHolderID="PlaceHolderAdditionalPageHead" runat="server">
<script type="text/javascript">
function setControlReadOnly()
{
var elements=document.getElementById('ctl00_m_g_19d74208_fb82_4a74_a3b0_0c5d16ec6591_ctl00_ctl05_ctl00_ctl00_ctl00_ctl04_ctl00_ctl00_TextField');
if (elements == null)
{
alert("Could not set control to read only.");
}
elements.readOnly=true ;
}
_spBodyOnLoadFunctionNames.push("setControlReadOnly")
</script>
</asp:Content>

Tuesday, July 24, 2012

query.Query = "<Where><Gt><FieldRef Name='ID'/><Value Type='Counter'>0</Value></Gt></Where><OrderBy><FieldRef Name='Titl'/></OrderBy>";

Create a NetworkCredential from a SPManagedAccount

        private static NetworkCredential GetManagedAccountCredential(string managedAccount)
        {
            NetworkCredential result = null;
            try
            {
                SPSecurity.RunWithElevatedPrivileges(delegate()
                {
                    SPFarmManagedAccountCollection accounts = new SPFarmManagedAccountCollection(SPFarm.Local);
                    SPManagedAccount account = accounts.FindOrCreateAccount(managedAccount);
                    string[] usernameSplit = account.Username.Split('\\');
                    string username = usernameSplit[1];
                    string domain = usernameSplit[0];
                    var securePassword = (SPEncryptedString)account
                                                            .GetType()
                                                            .GetField("m_Password",
                                                              System.Reflection.BindingFlags.GetField |
                                                              System.Reflection.BindingFlags.Instance |
                                                              System.Reflection.BindingFlags.NonPublic)
                                                            .GetValue(account);
                   // TODO - remove these 3 lines when .Net 4.0 is available and we can create NetworkCredential with SecureString
                    var intptr = System.IntPtr.Zero;
                    var unmanagedString = Marshal.SecureStringToGlobalAllocUnicode(securePassword.SecureStringValue);
                    var password = Marshal.PtrToStringUni(unmanagedString);
                    Marshal.ZeroFreeGlobalAllocUnicode(unmanagedString);
                    result = new NetworkCredential(username, password, domain);
                    password = null;
                });
            }
            catch (Exception ex)
            {
                Logging.LogException("GetManagedAccountCredential", ex);
            }
            return result;
        }

Wednesday, July 18, 2012

Get Sharepoint data from remote sharepoint site

        private static ListItemCollection GetSharepointData(string siteUrl, string sharepointList, string sharepointView)
        {
            ListItemCollection listItems = null;
            try
            {
                Console.WriteLine("Connection to Sharepoint: '{0}'", siteUrl);
                ClientContext clientContext = new ClientContext(siteUrl);
                Console.WriteLine("Opening Sharepoint list: '{0}'", sharepointList);
                List list = clientContext.Web.Lists.GetByTitle(sharepointList);
                FieldCollection fields = list.Fields;
                clientContext.Load(list);
                clientContext.Load(fields, items => items.Include
                                            (item => item.FieldTypeKind,
                                             item => item.Title,
                                             item => item.InternalName));
                clientContext.ExecuteQuery();
                CamlQuery camlQuery = new CamlQuery();
                listItems = list.GetItems(camlQuery);
                clientContext.Load(listItems);
                clientContext.ExecuteQuery();
            }
            catch (Exception ex)
            {
                Console.WriteLine("EXCEPTION: GetSharepointData Failed to load list {0}", ex.Message);
            }
            return listItems;
        }

Thursday, July 12, 2012

View/Edit item in popup window link

string viewUrl = list.DefaultViewUrl;
// If current user can edit the list, then we set viewUrl to the edit form
if ((list.EffectiveBasePermissions & SPBasePermissions.EditListItems) == SPBasePermissions.EditListItems)
{
    viewUrl = list.DefaultEditFormUrl;
}
string editLink = @"<a href=""javascript:void(0)"" onclick=""javascript:SP.UI.ModalDialog.showModalDialog({{ url: '{0}?ID={1}', title: '{2}' }}); return false;"">{2}</A>";
string linkUrl = string.Format(editLink, viewUrl, item.ID, item.title);

Tuesday, April 10, 2012

Delete all items from Sharepoint QuickLaunch menu

public static void CleanQuickLaunch(SPWeb web)
{
try
{
SPNavigationNodeCollection nodes = web.Navigation.QuickLaunch;
int nodeCount = nodes.Count;
int iNode = 0;
for (iNode = nodeCount -1; iNode >=0 ; iNode--)
{
try
{
SPNavigationNode node = web.Navigation.QuickLaunch[iNode];
if (node.Children.Count > 0)
{
int nodeChildCount = node.Children.Count;
int iNodeChild = 0;
for (iNodeChild = nodeChildCount - 1; iNodeChild >= 0; iNodeChild--)
{
try
{
Debug.WriteLine(node.Children[iNodeChild].Title);
node.Children[iNodeChild].Delete();
}
catch (Exception ex)
{
Logging.LogException("CleanQuickLaunch Delete Child Node", ex);
}
}
}
node.Delete();
}
catch (Exception ex)
{
Logging.LogException("CleanQuickLaunch Delete Node", ex);
}
}
}
catch (Exception ex)
{
Logging.LogException("CleanQuickLaunch", ex);
}
}

Tuesday, April 3, 2012

private static void AddCQWP(SPLimitedWebPartManager webPartManager, string zone, string Url, SPList list)
{
ContentByQueryWebPart CQWP = new ContentByQueryWebPart();CQWP.WebUrl = Url;
CQWP.ListName = list.Title;CQWP.ListGuid = list.ID.ToString();
CQWP.FilterType1 = "Boolean";CQWP.FilterField1 = "Field1";
CQWP.FilterValue1 = "1";CQWP.FilterDisplayValue1 = "1";
CQWP.FilterOperator1 = ContentByQueryWebPart.FilterFieldQueryOperator.Eq;CQWP.FilterType2 = "Boolean";
CQWP.FilterField2 = "Field2";CQWP.FilterValue2 = "1";
CQWP.FilterDisplayValue2 = "1";CQWP.FilterOperator2 = ContentByQueryWebPart.FilterFieldQueryOperator.Eq;
CQWP.Filter1ChainingOperator = ContentByQueryWebPart.FilterChainingOperator.And;
CQWP.Title = "Title of the CQWP";
CQWP.ItemStyle = "TitleOnly";
CQWP.ItemLimit = -1;
CQWP.SortBy = "FieldName";
CQWP.DataMappingViewFields = "FieldName;";
CQWP.WebUrl = "~sitecollection";
CQWP.UseCopyUtil = true;string dataMapping = "LinkUrl:Description:ImageUrl:Title:{" + list.Fields["FieldName"].Id.ToString() + "},FieldName,Text;";
CQWP.DataMappings = dataMapping;
CQWP.DataMappingViewFields = "{" + list.Fields["FieldName"].Id.ToString() + @"},Text;";
webPartManager.AddWebPart(CQWP, zone, 20);}

Thursday, March 22, 2012

C# Add Content Editor Web Part

using (SPLimitedWebPartManager webPartManager = web.GetLimitedWebPartManager(file.Url, PersonalizationScope.Shared))
{
ContentEditorWebPart wp = new ContentEditorWebPart();
XmlDocument xmlDoc = new XmlDocument();
XmlElement xmlElement = xmlDoc.CreateElement("Root");
xmlElement.InnerText = "Test CEWP Contents";
wp.Content = xmlElement;
wp.Content.InnerText = xmlElement.InnerText;
wp.Title = "Test";
webPartManager.AddWebPart(wp, "Zone 1", 10);
}

Wednesday, March 21, 2012

Programmatically create Sharepoint Pages

Props to Laura: http://www.sharepoint911.com/blogs/laura/Lists/Posts/Post.aspx?List=daba3a3b%2Dc338%2D41d8%2Dbf52%2Dcd897d000cf3&ID=67&Web=dbb90e85%2Db54c%2D49f4%2D8e97%2D6d8258116ca0

Open your site in SharePoint Designer, and click File –> New
–> ASPX
Click the Format menu, choose Master Page,
and click Attach Master Page
Click OK for the Default Master Page.
Click the PlaceHolderMain section in the middle of the page, click the
little chevron (the little gray button with an arrow on it), and click
Create Custom Content.
Put your cursor inside of the PlaceHolderMain section. On the
Insert Menu, choose SharePoint Controls, and
click Web Part Zone

View Source, copy/paste into the Resource.


string siteUrl = "http://localhost";
using (SPSite site = new SPSite(siteUrl))
{
using (SPWeb web = site.OpenWeb("/"))
{
SPDocumentLibrary lib = (SPDocumentLibrary)web.Lists.TryGetList("Site Pages");
string filename = string.Format("test{0}.aspx", DateTime.Now.ToString("yyyymmddhhmmss"));
System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding();
byte[] page = encoding.GetBytes(Resource1.ASPXTemplate);
SPFile file = lib.RootFolder.Files.Add(filename, page, true);
}
}

CreateField with Default Value

public static void CreateFieldWithDefault(SPList list, string fieldName, string defaultValue, SPFieldType spFieldType)
{
try
{
string fieldNameNoSpaces = TrimSpaces(fieldName);
string displayName = list.Fields.Add(fieldNameNoSpaces, spFieldType, false);
SPField field = list.Fields[fieldNameNoSpaces];
field.Title = fieldName;
if (spFieldType != SPFieldType.Boolean)
{
field.DefaultValue = defaultValue;
}
field.Update();
if (spFieldType == SPFieldType.DateTime)
{
SPFieldDateTime dt = (SPFieldDateTime)field;
dt.DisplayFormat = SPDateTimeFieldFormatType.DateOnly;
dt.Update();
}
SPView view = list.DefaultView;
view.ViewFields.Add(fieldName);
view.Update();
}
catch (Exception ex)
{
Logging.LogException("CreateFieldWithDefault", ex);
}
}

private static string TrimSpaces(string fieldName)
{
string[] names = fieldName.Split(' ');
string fieldNameNoSpaces = string.Empty;
foreach (string name in names)
{
fieldNameNoSpaces += name;
}
return fieldNameNoSpaces;
}

SPItemEventReceiver - SPItem SPField updated

public override void ItemAdded(SPItemEventProperties properties)
{
// Check that ths is the list we care about
if (false == string.Equals(properties.ListTitle, "ListName", StringComparison.InvariantCultureIgnoreCase))
{
return;
}

// Check if this is the Field name that we care about
if (null == properties.AfterProperties["FieldName"])
{
return;
}

// If you get here, field was added/updated.

}

private static void SnapshotToXLS(SPList list, SPList docLib)
{
try
{
SPListItemCollection listItems = list.GetItems(list.Views["View"]);
DataTable items = listItems.GetDataTable();
string filename = string.Format("{0}.xml", DateTime.Now.ToString("yyyymmddhhmmss"));
MemoryStream contents = new MemoryStream();
items.WriteXml(contents);
SPFile file = docLib.RootFolder.Files.Add(filename, contents);
}

Monday, March 19, 2012

Sharepoint Menu Manipulation Headers versus Links

Everything gets created as a link, if you want just a header, use the following code:

SPNavigationNode header = new SPNavigationNode("Header", "");
header = nodes.AddAsLast(header);
header.Properties["NodeType"] = "Heading";
header.Properties["BlankUrl"] = "true";
header.Update();

Monday, March 5, 2012

Delete all items from a Sharepoint list

private static void EmptyList(SPSite site, SPList list)
{
StringBuilder sbDelete = new StringBuilder();
sbDelete.Append("");
string command = "" + list.ID + "{0}Delete";
foreach (SPListItem item in list.Items)
{
sbDelete.Append(string.Format(command, item.ID.ToString()));
}
sbDelete.Append("
");
site.RootWeb.ProcessBatchData(sbDelete.ToString());
}

Friday, February 24, 2012

Create Grid View

private static string CreateGridView(SPWeb web, string listName, string viewName, string fields)
{
SPList list = web.Lists.TryGetList(listName);
if (null == list)
{
// LogError
return string.Empty;
}
System.Collections.Specialized.StringCollection viewFields = new System.Collections.Specialized.StringCollection();
string[] names = fields.Split(';');
foreach (string name in names)
{
viewFields.Add(name);
}
SPView view = list.Views.Add(viewName, viewFields, "", 100, false, false, SPViewCollection.SPViewType.Grid, false);
return view.Url;
}

Add to Quick Launch

private static void AddToQuickLaunch(SPWeb web, string viewUrl, string viewTitle)
{
if ((string.IsNullOrEmpty(viewTitle))
(string.IsNullOrEmpty(viewUrl)))
{
return;
}
SPNavigationNodeCollection nodes;
SPNavigationNode node;
nodes = web.Navigation.QuickLaunch;
node = new SPNavigationNode(viewTitle, viewUrl);
nodes.AddAsFirst(node);
}