Showing posts with label sharepoint Scripts. Show all posts
Showing posts with label sharepoint Scripts. Show all posts

18 July 2013

SharePoint-GridView & PeopleEditor control.

Developer usually invest much time when the control are sharepoint and binding data is not made straight forward.

Below is simple example to get SharePoint:PeopleEditor control in SPGridView Control on application page.

Step 01:  Add SPGridView control on Application /Webpart page.
Step 02:  Add needed columns in the Sp GridView
Step 03 : Add Sharepoint PeopleEditor column
Step 04:  Add Title Property in PeopleEditor with binded column from data source
 Ex: -   Title='<%# Bind("AUTHOR") %>'
Step 05: Add OnRowDataBound property in SPGridView
Ex : - OnRowDataBound="spGridViewRowEventHandler"
Step 06: Add your picker validate code to resolve the user/Author on databound.

protected void spGridViewRowEventHandler(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {              
                PeopleEditor ppAuthor = (PeopleEditor)e.Row.FindControl("Control");
                string userid= ppAuthor.Title.ToString();
                 ppAuthor.CommaSeparatedAccounts =userid
                 ppAuthor.Validate();
            }

        }


That's it your control is done

21 March 2013

SharePoint People-picker Slowness

Recently my SharePoint portal seems to slowing from end user information entering. The User entry box people-picker was really taking forever to resolve name. The slowness was recorded across whole site collection and there was no customization involved which might have affected this issue.

In order to resolve this slowness following steps needs to be performed.
1. Execute following command on the WFE server.

 Stsadm–o setapppassword –password 

Please note - the password here is not the server.

2. Now execute following command on APP server.

Stsadm –o setproperty –pn peoplepicker -searchadforests –pv "forests:i.domain.com, Domain:i.domain.com" -url "http://Sharepointsite/"


This will do the trick. repeat same for Sub-site as well.


05 March 2013

SharePoint User Profile Synchronization.


SharePoint portals are tightly integrated with Active Directory and since SharePoint has a additional Database to maintain user profiling, However many times user alias names are shown inconsistent on welcome.ascx section For some it's show :
         first name , last name
         last name, first name 
         domain\userID 
 This means AD-Profile Synchronization is not enabled or not happening for some reasons.
SOLUTION:

Manually run following SharePoint PowerShell Command which synchronizes AD Accounts.

Get-SPUser –Web http://SharePointServer | Set-SPUser –SyncFromAD

Execute command for each Site collection to reflect these changes.  

14 March 2012

Power Shell Command finder links

Couple of helpful links for Powershell links to refer

SilverLight Command Builder

Index of SharePoint Server 2010 Windows PowerShell cmdlets

Codeplex PS tool (directions on the site)

Finally for Remote Server Execution of powershell commands best mentioned steps:
SharePoint 2010 with Windows PowerShell Remoting Step by Step

Hope this helps you as well.


16 December 2011

Validate Login User with AD/LDAP authentication(Login Page)

Validating users against Active Directory/ LDAP. Also many organisation have multiple domains and same application needs to validate accross all domain.

This code can be used in SharePoint custom Login form for user Validation for Claim based authentication or Form Based Authentication.




Reference Added :

using System.Runtime.InteropServices;

COMException : The exception that is thrown when an unrecognized HRESULT is returned from a COM method call for more simplified error response from LDAP Error: Unknown error (0x80005000).


using System.DirectoryServices;


Below is the code sniplet

using (DirectoryEntry entry = new DirectoryEntry())
{
entry.Username = "DOMAIN\\LOGINNAME";
entry.Password = "PASSWORD";
DirectorySearcher searcher = new DirectorySearcher(entry);
searcher.Filter = "(objectclass=user)";
try
{
searcher.FindOne();
{
//Add Your Code if user Found..
}
}
catch (COMException ex)
{
if (ex.ErrorCode == -2147023570)
{
ex.Message.ToString();
// Login or password is incorrect
}
}
}


ErrorCode : -2147023570 suggest the Username or password is not correctly entered.

post your questions, comments or suggestion.


24 June 2011

Grid with Content Query Webpart

Here I'm sharing link to get Display Content Query Web Part Results in a Grid / Table well explained by Paul.
.Click here to view




02 November 2010

SharePoint WebPart & ASP.Net Coding workarounds

As a SharePoint Developer there are couple of the changes in coding as compared to ASP.net application.
Few important note I would like add for my developer Friends

For Output : http://akshaya-m.blogspot.com?k=akshaya

Asp .Net Code
Response.Redirect("http://akshaya-m.blogspot.com?k=akshaya");
SharePoint Webpart Code Needs:
HttpContext.Current.Response.Redirect("http://akshaya-m.blogspot.com?k=akshaya");


Get akshaya from the browser URL (http://akshaya-m.blogspot.com?k=akshaya)

Asp .Net Code
Request.SubString["k"]
SharePoint Webpart Code Needs:
Context.Request["k"].ToString();

07 October 2010

Custom Welcome Control

For providing enriched contents on the masterpage sharepoint has UserControls placed.

Here I'm providing couple of best link for the same.





26 June 2010

Print WebPart Content Area :Sharepoint

After developing a business specific front end there is always a request for Print functionality for specific WebParts /content.

Here is a script added at SharePoint Forum (Click Here)

23 March 2010

Webpart :File Upload with Folder Drill Down

Development Steps:
Custom webPart is created for specific document library which populates folders and sub-folder ina dropdown control showing the folder name and file control to upload file to the selected folder/sub-folder.

1. Control initialization is carried in the CreateChildControls()
Note: since the control needs to pertain existing values in on page I referred I have enabled drop Down values true for
-----Code-----
<DropDown_Control>.AutoPostBack = true;
<DropDown_Control>.EnableViewState = true;
-----------

2. Loading the Parent drop-down with all the parent Folders

-----Code-----
using(SPWeb myWeb = mysite.OpenWeb())
{
//before selecting the Folder
ListItem listItem = new ListItem();
listItem.Text = "Select Folder";
listItem.Value = "";
<DropDown_Control1>.Items.Add(listItem);
myWeb.AllowUnsafeUpdates =true;
SPFolder mylibrary = myWeb.Folders[<Document Library Name>.ToString()];
SPFolderCollection AllFolders = mylibrary.SubFolders;
foreach (SPFolder folderin AllFolders)
{
listItem = new ListItem();
listItem.Text = folder.Name.ToString();
listItem.Value = folder.Name.ToString();
<DropDown Control_1>.Items.Add(listItem);
}
}

-----------

3. Loading the Child DropDown with-in the selected parent folders

-----Code-----
void<DropDown Control_1>_SelectedIndexChanged(object
sender, EventArgs e)
{
//The code is much similar the mentioned above except few minor variations
using(myWeb = mysite.OpenWeb())
{
ListItem listItem = newListItem();
listItem.Text = "Select Sub-Folder";
listItem.Value = "";
<DropDown Control_2>.Items.Add(listItem);
myWeb.AllowUnsafeUpdates = true;
string_MainFolder = [<Document Library Name>.ToString();
SPFolder Mainlibrary = myWeb.Folders[_MainFolder];
SPFolder mylibrary = Mainlibrary.SubFolders[<DropDown Control_1>.SelectedValue.ToString()];
SPFolderCollection AllFolders = mylibrary.SubFolders;
foreach (SPFolder folder in AllFolders)
{
listItem = newListItem();
listItem.Text = folder.Name.ToString();
listItem.Value = folder.Name.ToString();
<DropDown Control_2>.Items.Add(listItem);
}
}
}
-----------

4. I have used a file upload control to get the local file to be uploaded

5. To upload my local file in the specified folder location selected on my Button control <Button_Control_Click Event>

-----Code-----

void < Button_Control>_Click(object sender,
EventArgs
e)
{
if(<FileUpload_Control>.PostedFile !=null)
{
if(<FileUpload_Control>.PostedFile.ContentLength > 0)
{
System.IO.Stream strm = <FileUpload_Control>.PostedFile.InputStream;

byte[] FileContent = new byte[ Convert.ToInt32(<FileUpload_Control>.PostedFile.ContentLength)];

strm.Read(FileContent, 0, Convert.ToInt32(<FileUpload_Control>.PostedFile.ContentLength));

strm.Close();
// Open site where document library is created.
SPWeb myWeb = mysite.OpenWeb();

// Get the folder that should store the document In this case, there's a document library called "<Document Library Name>" within the Root Web of the Site Collection
SPFolder MainDocLib = myWeb.Folders[<Document Library Name>.ToString()];

// Within the "<Document Library Name>" library, add the document into its Parent Folder
SPFolder parent = MainDocLib.SubFolders[<DropDown Control_1>.SelectedValue.ToString()];

// Within the "<Document Library Name>" library, add the document into a Parent folder's Sub-Folder
SPFolder child =parent.SubFolders[<DropDown Control_2>.SelectedValue.ToString()];

// Upload document

myWeb.AllowUnsafeUpdates = true;

SPFile spfile = child.Files.Add(System.IO.Path.GetFileName(<FileUpload_Control >.PostedFile.FileName), FileContent,true);

child.Update();
myWeb.Dispose();

<Status_Control>.Text = "File Successfully Uploaded! @"+ child.Url.ToString();
}
}
else
{
<Status_Control>.Text = "Sorry! File Not Found!";
}
}
-----------

Bingo!



Special Thanks: Dhawal Mehta

18 February 2010

Domain Specific Master Page/CSS Loading...

Having different Branding for alternate user is one of the most demanding requirement from a business prospective. However I have been incisive with the HTTP handler to load my masterpages for various domain based users..
Here is the simplest solution suggested & implemented by my friends which is really effective and fast to incorporate..
All my efforts were utilized in created CSS (style Sheet) and its adjacent master file..
These .CSS & .master file are uploaded on the portal’s style library.
For effective implementation I have added the following entries in the master page it self.
CSS initialization has been done in the head tag while domain checking and loading on masterpage is carried on the body.

If you want you can perform the same by using a content Editor Webpart Also.
/*.MASTER File/*

/* HEAD SECTION Tags*/

<link href="../../Shared Resources/custom.css" rel ="stylesheet" type ="text/css"
/>
< link rel ="stylesheet" type ="text/css" title = "MasterStyle01" href =
"/Style
Library/MasterStyle01.css"
/>

< link rel ="stylesheet"type ="text/css" title = "MasterStyle02" href = "/Style Library/MasterStyle02.css" />

</HEAD>



Body must include the conditions to check the User Domain and to load its corresponding master file.

/*BODY SECTION Tags*/

<BODY scroll="yes" onload="javascript:if (typeof(_spBodyOnLoadWrapper) !=
'undefined') _spBodyOnLoadWrapper();">
<WebPartPages: contenteditorwebpart id="ContentEditorWebPart1" runat="server"
__webpartid="{453BF7D0-85B6-40F5-AB3F-7255E09E41D5}">
<WebPart xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="http://schemas.microsoft.com/WebPart/v2>
<Content xmlns ="http://schemas.microsoft.com/WebPart/v2/ContentEditor"> <! [CDATA[<script>
var myLoginUser = '_LogonUser_'.toLowerCase();
if (myLoginUser.indexOf('Domain01') != "-1")
{
if(document.styleSheets)
{
for(var StyleSheetIterator = 0; StyleSheetIterator<document.styleSheets.length; StyleSheetIterator++)
{
if(document.styleSheets[StyleSheetIterator].title =="MasterStyle02")
{ document.styleSheets[StyleSheetIterator].disabled = false; }
if(document.styleSheets[StyleSheetIterator].title == "MasterStyle01") { document.styleSheets[StyleSheetIterator].disabled = true; }
</script>]]> </Content></WebPart> </WebPartPages:ContentEditorWebPart>
........


Note: check the tags existence in the master file itself before adding.
--
Special Thanks : Anshul Gagneja & Dhawal Mehta

17 February 2010

Sharepoint Session State

hi focks,
Here is a link I'm session state configuration in sharepoint.
Click Here blogged by Erick Kraus


Special Thanks : Erick

22 December 2009

Implementing Color Events in SharePoint Calendar

Hi,

I have color coded event implemented in SharePoint calendar using simple steps and without coding.
All I have done is created a calculated field with input color segment column and a script to include this selected color.

1. Create a Choice type Field named Color .




2. Add the needed colors
3. Create a calculated field name Calendar text Insert formula :

=Color&"|||"&Title

4. Add a CEWP(Content Editor WebPart)

<script language="JavaScript">


var SEPARATOR = "|||";
var nodes, category;
nodes = document.getElementsByTagName("a");

for(var i = 0; i < nodes.length; i++)
{
if(nodes[i].innerText.indexOf(SEPARATOR) != -1)
{
UpdateCalendarEntryText(nodes[i]);
var foundNode = nodes[i];
var trap = 0;
while(foundNode.nodeName.toLowerCase() != "td") {
foundNode = foundNode.parentNode;
trap++;
if(trap > 10)
{
break; // don't want to end up in a loop

}
}

var colour = GetCalendarColour(category);

if(colour ! "")
foundNode.style.background = colour;
}
}

function UpdateCalendarEntryText(anchorNode)
{
var children = anchorNode.childNodes;
for(var i = 0; i < children.length; i++)

{

if(children[i].nodeType == 3 && children[i].nodeValue.indexOf(SEPARATOR)
!= -1)
{
var parts = children[i].nodeValue.split(SEPARATOR);
category = parts[0];
children[i].nodeValue = parts[1];
}
else
UpdateCalendarEntryText(children[i]);
}
}

function GetCalendarColour(desc)
{
var colour;

switch(desc.toLowerCase())
{

case "red":
colour = "#ff0000";
break;


case "blue":
colour = "#0000ff";
break;


case "yellow":
colour = "#ffff00";
break;


case "green":
colour = "#008000";
break;

case "orange":
colour = "#ff8040";
break;

default:
colour = "";

}
nbsp;
return colour;
}

</script>


Bingo



--------

18 September 2009

KPI in WSS

I’m adding this article to produce KPI indicators for a simple task list which will show symbolic representation for each item added.

Here I have selected a task list in which I have added a calculated field named “Indicator” and these indicators are calculated from the priority field which is categorized (high, Medium & Low).
Here is the code snippet for calculated field.
="<DIV><IMG
src='/_layouts/images/kpipeppers-"&(3-RIGHT(LEFT(Priority,2),1))&".gif'
/></DIV>"
Now added the following script in content editor webpart

<script type="text/javascript">
var theTDs = document.getElementsByTagName("TD");
var i=0;
var TDContent = " ";

while (i < theTDs.length)

{
try
{
TDContent = theTDs[i].innerText theTDs[i].textContent;
if ((TDContent.indexOf("<DIV") == 0) && (TDContent.indexOf("</DIV>") >= 0))

{
theTDs[i].innerHTML = TDContent;
}

}
catch(err){}
i=i+1;
}////
ExpGroupRenderData overwrites the default SharePoint function
// This part is needed for collapsed groupings
//
function ExpGroupRenderData(htmlToRender, groupName, isLoaded)

{

var tbody=document.getElementById("tbod"+groupName+"_");
var wrapDiv=document.createElement("DIV");
wrapDiv.innerHTML="<TABLE><TBODY id=\"tbod"+ groupName+"_\"
isLoaded=\""+isLoaded+ "\">"+htmlToRender+"</TBODY></TABLE>";
var theTBODYTDs = wrapDiv.getElementsByTagName("TD"); var j=0; var TDContent = " ";
while (j < theTBODYTDs.length) {
try {
TDContent = theTBODYTDs[j].innerText theTBODYTDs[j].textContent;
if ((TDContent.indexOf("<DIV") == 0) && (TDContent.indexOf("</DIV>") >= 0))

{
theTBODYTDs[j].innerHTML = TDContent;

} }
catch(err){}
}
tbody.parentNode.replaceChild(wrapDiv.firstChild.firstChild,tbody);
}
</script>



Special thanks: Christophe




07 July 2009

Replacing Time field

SharePoint provides date time field in a fixed format, However we can further organized to have a hourly/minute counter to view its last updates/modification.
This can be achieved by using a simple Content Editor Web part[CEWP] and Script for converting "DD/MM/YYYY hh:mm" to minutely incremental field.

Add the following sniplet in the source script section fo the CEWP.

<--Code-->

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(function() {
var str = "Last Updated"; //change
this based on col header

var today = new Date();
today = Date.parse(today)/1000;
var a=0;
var headers = $("table.ms-listviewtable:first>
tbody> tr:first th"
).get();
$.each(headers, function(i,e){
x = $(e).contents().find("a[title*='"+str+"']").length;
a = x > 0 && i > a ? i : a;
});
var dArray = $("table.ms-listviewtable:first>
tbody> tr:gt(0)"
).find(">td:eq("+a+")").get()
$.each(dArray, function(i,e){
var d1 = Date.parse($(e).text())/1000;
var dd = (today-d1)/86400;
var dh = (dd-Math.floor(dd))*24;
var dm = (dh-Math.floor(dh))*60;
var time = ((Math.floor(dd) > 0 ? Math.floor(dd) +" days, " : "")+
(Math.floor(dh) > 0 ? Math.floor(dh)+" hrs, " : "")+
(Math.floor(dm)+" min"));
$(e).text(time);
});
});
</script>
Special Thanks: Paul Grenier


25 June 2009

Script for Edit Page & Site Setting.

Hi,
Many folks face problem once the SharePoint portal is authorized; many eliminate the option of removing the site action menu from master page. Many occasions accrue when one is suppose the edit the web parts or the page contents, everything using designer is also not fissile. Here is a simple script which can be added in the required page as a Content Editor WebPart which can help you in further alterations in future.


<!--Code-->
<style>
#ContentTypeToolbar table
{
background-color: #BFDBFF !important;width: 100%;
}
td button
{
padding: 3px 7px 4px 7px !important; border: 1px solid
#A0BECE; font-family: Verdana; background-color: transparent; height:auto; width:auto;
xoverflow:visible; margin: 0px 1px 0px 1px !important;
}
</style>
<div id="ContentTypeToolbar" style="background-color:#93BCF;"></div>
<script>
window.attachEvent("onload", new Function("NewButtons_OnLoad();"));
function NewButtons_OnLoad()
{
try
{
var aTags = document.getElementsByTagName("IE:MENUITEM");
var sToolbar='<table
class="ms-menutoolbar" cellSpacing="0" cellPadding="2" width="100%" border="0" ><tr><td>';
// For Each Menu Item
for(var j=0;j< aTags.length;j++)
{
var aTag = aTags[j];
// Only Process the items from the _New And _settings Menu (ignore Actions)
if(aTag.getAttribute("id").toLowerCase().indexOf("_siteaction")>=0)
{
var BtnText=aTag.getAttributeNode("text").value;
var OnMenuClick=aTag.getAttributeNode("onMenuClick").value;
var IconSrc=aTag.getAttributeNode("iconSrc").value;
var Description=aTag.getAttributeNode("description").value;
// Add the Button with an Image.
sToolbar=sToolbar+'<button class="ms-menubuttoninactivehover"
onmouseover="MMU_EcbTableMouseOverOut(this, true)" onClick="'+OnMenuClick+'" title="'+Description+'"
hoverInactive="ms-menubuttoninactivehover" hoverActive="ms-menubuttonactivehover"><img
style="height:22px;width:22px;" align="absmiddle" src="'+IconSrc+'">'+BtnText+'</button>';
}//end of if
if(aTag.getAttribute("id").toLowerCase().indexOf("_settings")>=0)
{
var BtnText=aTag.getAttributeNode("text").value;
var OnMenuClick=aTag.getAttributeNode("onMenuClick").value;
var IconSrc=aTag.getAttributeNode("iconSrc").value;
var Description=aTag.getAttributeNode("description").value;
// Add the Button with an Image.
sToolbar=sToolbar+'<button class="ms-menubuttoninactivehover"
onmouseover="MMU_EcbTableMouseOverOut(this, true)" onClick="'+OnMenuClick+'" title="'+Description+'"
hoverInactive="ms-menubuttoninactivehover"
hoverActive="ms-menubuttonactivehover"><img
style="height:22px;width:22px;" align="absmiddle" src="'+IconSrc+'">'+BtnText+'</button>';
}//end of if

} // End For
sToolbar=sToolbar+'<td class="ms-toolbar" noWrap width="1%" ><img class="icon"
height="18" alt="" src="../../_layouts/images/blank.gif" width="1"></td><td
class="ms-toolbar" noWrap align="right"><
button onclick="CTWPAbout()" style="background-color:transparent;border:0;cursor:hand;"><img
src="/_layouts/images/helpicon.gif"></button></td></tr></table>';
if (document.location.href.indexOf('codeexport') >0)
{
sToolbar='<textarea rows="5">'+sToolbar+'</textarea>';
}
document.getElementById("ContentTypeToolbar").innerHTML=sToolbar;
} // try
catch (e)
{
window.status=e.description;
} // catch }
function CTWPAbout()
{
var sAbout='by Akshaya\n\nCopyright 2009\n ';
alert(sAbout);
}
Special Thanks: Vinay Patil
--

22 April 2009

Accordion-Style Left Navigation using JQuery

Accordion-Style Left Navigation:
Before
All the Quick link menu provided by sharepoint out of Box has a fixed format and altering its CSS alters is branding.
However we can achieve collapsing and expanding functionality using jQuery provided by Google’s API.

if you want the accordion-style menu for all pages, you should work it into the default.master. For now, i have carried by adding a Content Editor Web Part (CEWP) to the page. Add the code below to the web part’s Content Editor (source). Now your menu should look like this.
Here when you click on the menu header box with the down arrow image, it exposes the submenu below it and swaps the image with an ‘x’. Likewise, clicking the header with the ‘x’ will hide the associated submenu.

<--script-->
<script type="text/javascript" src="http://www.google.com/jsapi"></script>
<script type="text/javascript">
// Load jQuery
google.load("jquery", "1.2.6");
</script>
<script type="text/javascript">
$(function(){
//initialize menus
var menuRows = $("[id$='QuickLaunchMenu'] > tbody > tr");
var menuHd = menuRows.filter("[id!='']:has(+tr[id=''])");
//set img path for when submenu is hidden
var closedImg = "/_layouts/images/Menu1.gif";
//set img path for when submenu is visible
var openedImg = "/_layouts/images/ptclose.gif";
var cssInit = {
"background-image": "url('"+closedImg+"')",
"background-repeat": "no-repeat",
"background-position": "100% 50%"
}
var cssClosed = {"background-image": "url('"+closedImg+"')"}
var cssOpen = {"background-image": "url('"+openedImg+"')"}
//hide submenus
menuRows.filter("[id='']").hide();
//apply initial inline style to menu headers
menuHd.find("td:last").css(cssInit);
menuHd.click(function () 

{
var styleElm = $(this).find("td:last")
var nextTR = $(this).next("tr[id='']");
if (nextTR.is(':visible')) 

{
nextTR.hide();
styleElm.css(cssClosed);

else 
{
nextTR.show();
styleElm.css(cssOpen);
}
});
});



Rate Now: