28 July 2012

SharePoint 2010 -MS LYNC Integration.

SharePoint - a collaborative platform to have mash up functional is always fun. Recently I found can across well drafted article published by J.D. Wade on Sharepoint and Microsoft Lync.

Lync and SharePoint Integration

Special thanks : J.D Wade.

21 July 2012

ORACLE : WITH Block statement

Query writing is fun but can be complex when we are referring multiple tables/views which has inlet/Joins /sub-query referred. on the best solution & organized way of writing such query in Oracle is using WITH Blocks.
Below I'm using simple example to help you get started with WITH-blocks
Tutorial : First block starts with "WITH" keyword  
WITH block_name AS ( ), Final statement includes Select statement with in query or join as needed treating each block as table. Below are 2 example showing with block usage.

Example : Consider 4 tables/views having needed information blinded with a connecting factor and say ID. Normal Query States :

        SELECT T1.Col1, T1.col2, T2.col3, T2.col4,
T2.col5 FROM Table1 T1 JOIN Table2 T2 ON Col6 = col7 
WHERE col6 IN ( SELECT TA.COLA FROM TableA TA JOIN TableB TB ON TA.COLA1 = tb.ColB1 ) 
Now to have more organized way to get this query executed using WITH Block  

CONDITION 01: Using blocks in WHERE clause
        WITH BLOCK1 AS (SELECT TA.COLA FROM
  TableA TA JOIN TableB TB ON TA.COLA1 = tb.ColB1), 
SELECT T1.Col1, T1.col2, T2.col3, T2.col4, T2.col5 FROM Table1 T1 JOIN Table2 T2 ON Col6 = col7 WHERE col6 IN 
( --Note:with block added as select statement & can be used at multiple places. 
SELECT block1.cola FROM BLOCK1 
) 

CONDITION 02: JOINING WITH blocks all together.
--Note : block starts from "WITH" statement
        WITH BLOCK1
AS
(SELECT TA.COLA FROM TableA TA JOIN
TableB TB ON TA.COLA1 = tb.ColB1 
), 
--Note: Except last with block all with block end with , 
BLOCK2 AS ( 
SELECT T1.Col1, T1.col2, T2.col3, T2.col4, T2.col5 FROM Table1
T1 JOIN Table2 T2 ON Col6 = col7 
) 
--final statement only includes Black name. 
SELECT * FROM Block2 B2, Block1 B1 WHERE B2.col6 = b1.COLA
  
Hope this help's you ----

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.


04 March 2012

Central Administration returns blank page after installation on Windows 7

Installation of SharePoint 2010 on Windows Server seems to be much easier than installing on Windows-7 machine to be loaded with SharePoint 2010 as a developer machine.

Now when i click on central admin blank page is returned.
No Error logs in IIS.
However I checked IIS Web-site & Application Pool everything seems to be running fine & was registried with proper service account.
Also check all SQL & Sharepoint Service which were also properly started.

Overall there was really no way anything was missed.
However after long search and troubleshooting i found windows features are required to be executed Click here to check steps by MSDN

Following command needs to be executed on Command Prompt as administrator:

start /w pkgmgr /iu:IIS-WebServerRole;IIS-WebServer;IIS-CommonHttpFeatures;IIS-StaticContent;IIS-DefaultDocument;IIS-DirectoryBrowsing;IIS-HttpErrors;IIS-ApplicationDevelopment;IIS-ASPNET;IIS-NetFxExtensibility;IIS-ISAPIExtensions;IIS-ISAPIFilter;IIS-HealthAndDiagnostics;IIS-HttpLogging;IIS-LoggingLibraries;IIS-RequestMonitor;IIS-HttpTracing;IIS-CustomLogging;IIS-ManagementScriptingTools;IIS-Security;IIS-BasicAuthentication;IIS-WindowsAuthentication;IIS-DigestAuthentication;IIS-RequestFiltering;IIS-Performance;IIS-HttpCompressionStatic;IIS-HttpCompressionDynamic;IIS-WebServerManagementTools;IIS-ManagementConsole;IIS-IIS6ManagementCompatibility;IIS-Metabase;IIS-WMICompatibility;WAS-WindowsActivationService;WAS-ProcessModel;WAS-NetFxEnvironment;WAS-ConfigurationAPI;WCF-HTTP-Activation;WCF-NonHTTP-Activation


Hope this help you too.
-------------------------------------------

05 January 2012

Custom entry for Hyperlink Or Picture column in SharePoint using webpart

SharePoint provides many columns as input one of which is Hyperlink or picture column which has two fields as entry and is a concern how to have the entry to be made possible from custom web part or via custom coding.

Normal out of box form looks like this.


I have created a webpart which has needed input holder to accept values from user.
Currently I’m using 2 columns Title & Hyperlink column : MyURL for URL
Please find the code for the same.

using (SPSite osite = new SPSite(SPContext.Current.Web.Url))
{
using (SPWeb oweb = osite.OpenWeb())
{
//listName
SPList Samplelist = oweb.Lists["ListName"];
SPListItem ListItem= Samplelist.AddItem();
oweb.AllowUnsafeUpdates = true;
ListItem["Title"] = "Akshaya Blog Title";
SPFieldUrlValue HyperlinkURLVal = new SPFieldUrlValue();
HyperlinkURLVal.Url ="http://akshaya-m.blogspot.com";
HyperlinkURLVal.Description = "Akshaya Blog Click Here";
ListItem["MyURL"] = HyperlinkURLVal;
//Update List item
ListItem.Update();
}
}


Outcome as needed--


Thanks please revert your queries/comments

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.


10 December 2011

Hide the extension .aspx in the url of page ...

Now a days customers are more concerned with site URL and its relative path displayed on the browser address.
Many Suggest having interceptor/handler or use the existing global.asax (Application_Begin Request handler) for modifying the URL shown in the browser window, Web Routing is the concept (4.0 framework)

However you can get solution for .Net /sharepoint application there are following ways:
  1. MVC
  2. HttpModule rewrite URL
  3. ISAPIRewrite to enable Extension-less URL Rewriting for IIS5 and IIS6
  4. IIS level extension parsing
Step by step approaches refer below links:
URL Rewriting in ASP.NET
URL Rewriting in Asp.net
URL rewrite/Routing (4.0 framework concept) *
IIS Forum for Extension parsing

 Let me know your comments /feedback for the same

16 August 2011

ASP .Net Page Life cycle


There are many post related to page life cycle. but the mentioned is really the best provided
Graphical View for Page Life Cycle








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




17 February 2011

Sandbox Solution: Overview

What is sandbox solution

Sandbox is a restricted environment where programs are deployed with restrictions. It plays valuable role for developers to test their application by using sandbox solution. Once this is tested it can be later deployed to full use in the farm.

Solution that are deployed into sandbox are called sandbox solutions.
 
Advantages

If farm is load balanced.
Release code which is fully not tested for production release.
Less bottleneck for farm administrator as this can be managed at site collection by administrator to it.

Disadvantages
First decide whether you want this solution? as using this solution does has impact on performance of the servers. As the farm using sandbox does have more process load than a farm without this.
Code Access Security (CAS) limits the operations that the code can perform

How to use

Activate SharePoint 2010 User Code Host service(SPUCHostService.exe,)  on server you want this solution. Should be done by farm administrator

Sandbox Code Services

Sandbox can be applied at the root of site collection level.
Members of the site collection administrators group can deploy sandboxed solutions

Governance for sandbox

Before deploying think of below

When should the solution be blocked or unblocked?
When to release the solution to production?
Who should be given access, deployment rights etc?

Adding / Blocking /Load Balancing for Sandbox

This can be done via CA – System settings


Special Thanks :Amarprit Jaspal


26 January 2011

List of Content Managment Systems.

In today's world Content Management System is core requirement for a business oriented system more and more companies developing their business standard directly influencing the need for CMS to hand their operation.

For all CMS lovers here is consolidated list fro all the management systems present till dated.
Click Here  By Wiki

25 November 2010

WSP Process stuck in "Deploying"

Recently, I deployed my Webpart solution packages created in sharepoint Farm.
After a long waiting i still figured the solution getting "Deploying" as its status..
Initially i Tried

stsadm -o execadmsvcjobs on the server running Central Admin.  No change. 
Since it was a farm deployment i Thought improper deployment was performed.

so I reset the IIS to get a refreshed processes running but still no effect.

Solution: Not Sure if its correct but worked for me.I opened list of timer jobs (Operations > Timer Job Definitions) search the job which point to the WSP solution we are deploying..Killing the Process will do the Trick.

However this does not actually deploy but only status is populated as "Deployed".
To Overcome this solution since you are on Farm Servers you need to Execute stsadm -o execadmsvcjobs on all the servers



23 November 2010

SharePoint 2010 Database Naming Standards

Hello,

Database Naming conventions for SharePoint 2010 well defined by John W Powell -Click Here to view!

--------

15 November 2010

FBA : Change Password

From my Earlier blog stating Form Based Authentication in SharePoint (MOSS 2007).
 ( Click Here )

Many were interested in password management for the users. A complete package ready to use is uploaded on codeplex.
However here I’m attaching a custom strip down to users change Password code snippet for the same.




There are two options while password management
1. Just to change Password
2. to provide Question & Answer along with Password change
Note : for Option (2) please add/updated web.Config file within Membership provider
------------------------------------------------------------------

///save button functionlity
void btnChangePassword_Click(object sender, EventArgs e)
{
if (Validate(true))
{
try
{
string AppName = Membership.ApplicationName;
if (.Text.Trim().ToString() != .Text.Trim().ToString())
{ .Text = " New and Confirm password Mismatch ! " ; }
else
{
if (Membership.Provider.ChangePassword(.Text, .Text, .Text))
{ //membership provider has Change Password checked in Web.Config
if (Membership.Provider.ChangePasswordQuestionAndAnswer(.Text, .Text, .Text, .Text))
{
//Message: " Your Password Has Been Sucessfully Changed.."
return;
}
}
catch (MembershipPasswordException ee)
{//Exception Message}
}
}

---------------------------------------------------------------------

Let me know your comments/ exceptions etc.
Will be glad to get back to you.

Active Directory: Password Management using SharePoint Webpart.

For Active Directory member the password management is one of the vital functionality which developer needs to add in his efforts to provide a appropriate solution.
Here below is the code snipplet to achieve this functionality.




I have implemented using SharePoint Webpart.

please specify you validation accordingly.
-:Core Code:-
------------------------------------------------------------------

SPSecurity.RunWithElevatedPrivileges(
delegate()
{
try
{
WindowsImpersonationContext aspContext = null;
WindowsIdentity identity = WindowsIdentity.GetCurrent();
aspContext = identity.Impersonate();
ContextOptions o = ContextOptions.Negotiate;
PrincipalContext ctx = new PrincipalContext(ContextType.Domain, this._DomainName, this._DomainName Path);


UserPrincipal UPrinci = new UserPrincipal(ctx);
UPrinci = UserPrincipal.FindByIdentity(ctx, SPContext.Current.Web.CurrentUser.LoginName);
UPrinci.ChangePassword(_oldpassword.Text, _newpassword.Text);
_labelmsg.Text = "Password changed successfully!" ;
} //Try
catch (PasswordException ex)
{ //ex.Message; Catch exception.}
} //Delegate



---------------------------------------------------------------------

Let me know your comments/ exceptions etc.
Will be glad to get back to you.

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();

29 October 2010

SharePoint Excel Error: Unable to Load WorkBook

When trying to open a excel file many come across this exception stating :

"The workbook that you selected cannot be loaded because it contains the following features are not supported by Excel Services"


Many blog suggested for Excel Services Trusted Site Entry for the excel file referring.

However the solution that worked for me:

Give "Read permissions" to the users and they will be able to open the file using excel client.

Steps :
For more info on how to see permissions you have for users and groups in your site go to: Site Actions > Site Settings > Advanced Permissions.
Edit User Permissions to Read

Also make sure the permission are inherited to the Document Library permissions.

Revert with your Comments on the same.

12 October 2010

Warning: Super user account!

When Working on a farm environment couple of time we come across some warning stating:
"The super user account utilized by the cache is not configured...."

Temporary Solution
:: execute- 'stsadm -o setproperty -propertyname portalsuperuseraccount -propertyvalue account -url webappurl'.

Furthermore, there is the caveat:
The account should be any account that has Full Control access to the SharePoint databases but is not an application pool account. What have people done - create a special account?

After doing an extensive research i found solution as stated by Mirjam van Olst

http://sharepointchick.com/archive/2010/10/06/resolving-the-super-user-account-utilized-by-the-cache-is.aspx



07 October 2010

SharePoint Installation steps

For installing Sharepoint on your local system please refer this blog

Over view on Installing Sharepoint 2007by dataSprings

Over view on Installing Sharepoint 2010by SharePoint Knowledge



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.





20 July 2010

Create WebPart Properties with Drop Down Items.

 
Dealare field

protected WeekDays _daysWeek = WeekDays.Sun;

/// Days of the Week to be appended in the Dropdown List

public enum WeekDays
{
Mon,
Tue, Web, Thur, Fri, Sat, Sun
};
/// Properties
[Personalizable(PersonalizationScope.Shared)]

[WebBrowsable(true)] [System.ComponentModel.Category("My Zone")]
[WebDisplayName("My DropDown Property")] [WebDescription("Get webpart properties
with DropDown")]
public WeekDays SelectedDay
{
get 
{ return _daysWeek; }
set 
{ _daysWeek = value; }
}






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)

12 May 2010

PARENT-CHILD RELATION USING J-SCRIPT

1. List Creation:
Create two list in the web application which needs this functionality to be implemented.
  1. Category: create list named “CATEGORY “ with default Title field in it.
  2. Sub-Category: Create list named “SUB-CATEGORY” with Title & a lookup from the Category List (Title Column).
Script for Content Editor WP.
Note: For adding script get the List GUID and Default View GUID of the Sub Category List

<script type="text/javascript"> _spBodyOnLoadFunctionNames.push("PageOnLoad");
function PageOnLoad()
{ // This function will add onchange event to the Country DropDown field and call
OnChanged function. var lookupElement = GetElementByTypeAndTitle('SELECT','Category');
if ( lookupElement != null)
{
lookupElement.onchange = function()
{
OnChanged(lookupElement.options[lookupElement.selectedIndex].text)
};
} }
function OnChanged(FilterValue)
{ // siteName - the root / and possibly sub site you are working on
// lookupListName - the guid for the list you want to use as lookup
// lookupViewName - the guid for the view filtering the content of the list
// NOTE: TO DERIVE THE GUID FOR THE LIST NAME AND VIEW NAME
// Open the List -> Settings -> List Settings -> Click on "All Items" view,
// From the URL you can get the ListName GUID and ListView GUID.
// textField - the field you want to show to the user
// valueField - this is most of the time the internal ID field
// FilterField - the field you want to be a filter
// FilterValue - the filter's value var
siteName="";
var lookupListName="{90533341-04F8-4353-BBEB-D6D9A0BAAC1F}";
var lookupViewName="{C6C467A6-C04D-448D-8015-D4A622784745}";
var FilterField ="Category";
var textField ="ows_LinkTitle";
var valueField ="ows_ID";
var filterElement = GetElementByTypeAndTitle('SELECT','Sub-Category');


filterElement.innerHTML = ""; var reqstring = siteName + "/_vti_bin/owssvr.dll?CS=109&XMLDATA=1&RowLimit=0&List=" + lookupListName +"&View=" + lookupViewName;


if (FilterValue != "") reqstring= reqstring +
"&FilterField1=" + escape(FilterField) + "&FilterValue1=" + escape(FilterValue);


var req = new ActiveXObject("MSXML2.XMLHTTP"); req.open("GET",reqstring,false);
req.send();
// -- loading response in XML Document
var doc = new ActiveXObject("MSXML2.DOMDocument"); doc.loadXML(req.responseText); var data = doc.documentElement.childNodes(1);
for (i=0;i<data.childNodes.length;i++)
{
var optionText = data.childNodes(i).attributes.getNamedItem(textField).value;
var optionValue = data.childNodes(i).attributes.getNamedItem(valueField).value;
var opt = document.createElement("OPTION");


filterElement.options.add(opt);
opt.innerText = optionText;
opt.value = optionValue;
} }
function GetElementByTypeAndTitle(elementType, elementTitle)
{
//get the Element by tag name.
var allElements = document.getElementsByTagName(elementType);
for (var i = 0; i < allElements.length; i++)
{
//compare the Title.
if (allElements[i].title == elementTitle) return allElements[i];
}
return null;
}
</script>


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



--------

23 October 2009

Simple SharePoint Code Snippets

Here are few code snippets that are handy to use while creating a WebParts.

Added / Updating SharePoint List
osite =SPContext.Current.Site;
oweb = osite.OpenWeb();

oweb.AllowUnsafeUpdates = true;

SPList olist = oweb.Lists["LIST NAME"];

SPListItem newTask = olist.Items.Add();

newTask["Title"] = TextBox1.Text.ToString();

newTask["Comments"] = txtComments.Text.ToString();
newTask.Update();
lbstatus.Text = "Comments Added successfully";
txtComments.Text = "";

lbstatus.Visible = true;

oweb.AllowUnsafeUpdates = false;
oweb.Close();






24 September 2009

KPI : custom Code WebPart



Here i'v developed a webpart for showing KPI indicators which are binded as desired
i have used a literal control and binded a my display structure in this literal control.

Code
//inialization
private LiteralControl Literal1;
SPSiteoCurrentSite = null;
SPWeb oweb =null;
int count;
DataTable dt =new DataTable();
string strStruct;

In CreateChildControls()
Literal1 = new LiteralControl();
Literal1.Load += new EventHandler(Literal1_Load);
Controls.Add(Literal1);
-------
on load event of Literal Control i'll be calling my Core functionlity which will be binded with this literal control.

MyFunction()
{
try {
count = 0;
//oCurrentSite = new
SPSite("http://syngdcds0138:1111");

oCurrentSite = SPContext.Current.Site;
oweb = oCurrentSite.OpenWeb();
oweb.AllowUnsafeUpdates = true;
SPList oProjectName = oweb.Lists["Tasks"];
SPQuery Query1;
DataTable Dtable;
DataView Dview;
SPListItemCollection items1;
SPUser currentUser = oweb.CurrentUser;
string UNAme = currentUser.Name;
Query1 = new SPQuery();
Dtable = new DataTable();
Dview = new DataView();
Query1.Query = "<Where><Eq><FieldRef Name='AssignedTo' /><Value Type='User'>" +
currentUser.Name + "</Value></Eq></Where>";
items1 = oProjectName.GetItems(Query1);
strStruct = "<div>" + "<table>";
foreach (SPListItem objItem in items1)
{//Pending Completed Overdue
string picture = string.Empty;
if (objItem["Status"].ToString() == "Overdue")
{ picture = @"~/_LAYOUTS/Images/ico-task-overdue.jpg";
}
else if (objItem["Status"].ToString() == "Completed")
{ picture = @"~/_LAYOUTS/Images/ico-task-Completed.jpg";
}
else
{picture = @"~/_LAYOUTS/Images/ico-task-Pending.jpg";
}
string[] CreatedBy = objItem["Created By"].ToString().Split('#');
string AssignedBY = CreatedBy[1];
string DDt = Convert.ToDateTime(objItem["DueDate"].ToString()).ToShortDateString();
strStruct += "<tr>" + "<td colspan=2 align='left'>" + "<img src='" + ResolveUrl(picture) +
"'
/>&nbsp;&nbsp;&nbsp;"
+ "<a style='text-align:right; font-size:12px;' href='" + oweb.Url +
"/Lists/" + oProjectName.Title + "/DispForm.aspx?ID=" + objItem["ID"].ToString() + "&Source=" + oweb.Url + "'>" + objItem["Title"].ToString() + "</a>" + "</td></tr>" + "<tr><td colspan=2 style= 'font-family:Arial; font-size:xx-small;'>Due Date:" + DDt + "&nbsp;&nbsp;Assigned By:"
+ AssignedBY + " </td></tr>";
}
strStruct += "<tr><td></td><td> <a href='" + oweb.Url + "/Lists/" + oProjectName.Title + "/Allitems.aspx'>More&gt;&gt</a>" + "</td></tr>" + "<tr>" +
"<td><img
src='~/_LAYOUTS/images/ico-task-Completed.jpg'> Completed "
+
"<img
src='~/_LAYOUTS/images/ico-task-Pending.jpg'> Pending "
+
"<img
src='~/_LAYOUTS/images/ico-task-overdue.jpg'> Overdue </td>"

+ "</tr>" + "</table></div>";
Literal1.Text = strStruct;
}
catch (Exception ee) { //Error}
}

Revert your comments for this article

22 September 2009

Meeting WorkSpace Webpart :- Gets All Meeting Task

This WebPart is developed get all the Task which are added in a Decision Meeting Workspace template selected. since SharePoint does not provide any out-Of-Box functionality to segregate this vital information.
hence a custom WebPart was developed by my associate.
Initially all the related reference /namespaces are added , despite of Microsoft.sharepoint;
We also be needing :
using Microsoft.SharePoint.Administration;
using Microsoft.SharePoint.WebControls;
using Microsoft.SharePoint.WebPartPages;
using Microsoft.SharePoint.Meetings;
//Core Code for WebPart.
public class MeetingWorkspace : System.Web.UI.WebControls.WebParts.WebPart
{

//Initilization
SPGridView m_grid;
SPWeb web1 = SPContext.Current.Web;
ObjectDataSource objDataSource = new ObjectDataSource();
//Override Methods
protected override void CreateChildControls()
{
try
{
Type type = this.GetType();
objDataSource.ID =
"mTaskDS";
objDataSource.TypeName = type.AssemblyQualifiedName;
objDataSource.SelectMethod =
"GetListItems";
objDataSource.ObjectCreating +=
new ObjectDataSourceObjectEventHandler(objDataSource_ObjectCreating);
this.Controls.Add(objDataSource);
#region SPGridView Details
m_grid =
new SPGridView();
m_grid.AutoGenerateColumns =
false;
m_grid.Columns.Clear();
HyperLinkField meetingName = new HyperLinkField();
meetingName.HeaderText =
"Meeting Name";
meetingName.DataTextField =
"MeetingName";
string[] strmeetingName = { "MeetingSiteUrl" };
meetingName.DataNavigateUrlFields = strmeetingName;
meetingName.DataNavigateUrlFormatString =
"{0}";
m_grid.Columns.Add(meetingName);

BoundField t = new BoundField();
t.DataField =
"Title";
t.HeaderText =
"Task Title";
m_grid.Columns.Add(t);
BoundField b = new BoundField();
b.DataField =
"Status";
b.HeaderText =
"Status";
b.HtmlEncode =
false;
b.SortExpression =
"Status";
m_grid.Columns.Add(b);
BoundField colStartDate = new
BoundField();
colStartDate.DataField =
"StartDate";
colStartDate.HeaderText =
"Start Date";
colStartDate.HtmlEncode =
false;
m_grid.Columns.Add(colStartDate);
BoundField colDueDate = new
BoundField();
colDueDate.DataField =
"DueDate";
colDueDate.HeaderText =
"Due Date";
colDueDate.HtmlEncode =
false;
m_grid.Columns.Add(colDueDate);
m_grid.DataSourceID =
"mTaskDS";
m_grid.AllowGrouping =
true;
m_grid.AllowGroupCollapse =
true;
m_grid.GroupField =
"MeetingName";
m_grid.GroupFieldDisplayName =
"MeetingName";
m_grid.AllowSorting =
true;
m_grid.AllowPaging =
true;
Controls.Add(m_grid);
m_grid.DataBind();
m_grid.PageSize = 3;
m_grid.PageIndexChanging +=
new GridViewPageEventHandler(m_grid_PageIndexChanging);
m_grid.PagerTemplate =
null;
#endregion

base.CreateChildControls();
}
catch(Exception ex) { //Error }
}

//Data View Method
public DataView GetListItems()
{
DataView dv = new DataView();
DataTable dt = new DataTable();
try
{
string rowFilter = "AssignedTo = '" + SPContext.Current.Web.CurrentUser.Name + "'";
foreach (SPWeb web in web1.Webs)
{
if (SPMeeting.IsMeetingWorkspaceWeb(web))
{
SPMeeting meeting = SPMeeting.GetMeetingInformation(web);
// A Meeting Workspace has a Meeting Series list with information about all meetings in the workspace.
SPList meetings = web.Lists["Meeting Series"];
// Get the meeting items that fit the criteria.
SPListItemCollection items = meetings.Items;
// Now extract useful information about each meeting.
foreach (SPListItem item in items)
{
int instanceID = (int)item["InstanceID"];
SPQuery query =new SPQuery();
query.MeetingInstanceId = instanceID;
query.Query = @"<Query> <Where><IsNotNull> <FieldRefName='ID' /> </IsNotNull></Where></Query>" ;
SPList list = web.Lists["Tasks"];
DataTable dtMItems = list.GetItems(query).GetDataTable();
if (dtMItems.Columns["MeetingName"] == null)
{
dtMItems.Columns.Add("MeetingName");
dtMItems.AcceptChanges();
}
if (dtMItems.Columns["MeetingSiteUrl"] == null)
{
dtMItems.Columns.Add("MeetingSiteUrl");
dtMItems.AcceptChanges();
}
foreach (DataRow dr in dtMItems.Rows)
{
dr["MeetingName"] = item.Title;
dr["MeetingSiteUrl"] = web.Url + "/default.aspx?InstanceID=" + instanceID.ToString();
dtMItems.AcceptChanges();
}
dt.Merge(dtMItems);
} } }
dv = new DataView(dt, rowFilter, null, DataViewRowState.CurrentRows);
}
catch (Exception ex) {//Error}

return dv;
}

//Handler
pri
vate void objDataSource_ObjectCreating(object sender, ObjectDataSourceEventArgs e)
{
e.ObjectInstance = this;
}
private void m_grid_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
try
{
m_grid.PageIndex = e.NewPageIndex;
m_grid.AllowGrouping = true;
m_grid.AllowGroupCollapse = true;
m_grid.GroupField = "MeetingName";
m_grid.GroupFieldDisplayName = "MeetingName";
m_grid.DataBind();
}
catch (Exception ex) {//Error }
}
}

Addin Your Comments for the Same.

Special Thanks: Ganesh Bankar

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




Rate Now: