December 29, 2010

CSS-MasterPage-Interview-Questions

CSS and Master Page Explained
http://social.msdn.microsoft.com/Forums/en/sharepoint2010general/thread/dc1d2942-5117-47e3-8255-bd1f0db3d1c0

Interview Questions:
http://www.megasolutions.net/qs/Sharepoint_Portal_Interview_Questions.aspx

December 23, 2010

Flash Object Example in CodeEditor Webpart - SharePoint

<object id="solutions" width="425" height="350" align="" classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,0,0"> <param name=movie VALUE="/SiteCollectionImages/SolutionsPageAnimation5.swf">
<param name="allowScriptAccess" value="sameDomain" />
<param name="quality" value="high" />
<param name="wmode" value="transparent">
<embed src="/SiteCollectionImages/SolutionsPageAnimation5.swf" wmode="transparent" quality="high" width="425" height="350" name="solutions" align="" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer"></embed> </object>

November 16, 2010

SharePoint 2010 Taxonomy / Managed Metadata Explained

Go to Central Administration
--> Manage Service Applications
--> Managed Metadata Service
--> Under Managed Metadata Service --> New Group
--> Under Group --> New Term Set
--> Under Term Set --> Create Term
--> Remember the Terminology

1. Create a Site Column with "Managed Metadata" Data Type.
2. Add this Site Column to any content type u desire.
3. Add this content type to any list or document library u desire.

Requirement: Update Metadata field in list through Code.

1. VS 2010
2. SharePoint 2010 --> Blank SharePoint Project
3. Features --> Add Feature
4. Add Elements with CustomActionGroup and CustomAction Tags
Note: Id an be any string, don't spend time to give guid.
5. Map to Layout Folders.
6. Add Application Page.

--> In ASPX page add the register tag.

<%@ Register TagPrefix="Taxonomy" Namespace="Microsoft.SharePoint.Taxonomy" Assembly="Microsoft.SharePoint.Taxonomy, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>

--> Under Content Main

<Taxonomy:TaxonomyWebTaggingControl ID="myTaxonomyCntrl" runat="server">
</Taxonomy:TaxonomyWebTaggingControl>

--> In ASPX.CS Page Load Method

SPSite site = SPContext.Current.Site;
TaxonomySession session = new TaxonomySession(site);
TermStore termStore = session.TermStores["Managed Metadata Service"];
Group group = termStore.Groups["Group Name"];
TermSet products = group.TermSets["Term Set Name"];
TermCollection termCollection = products.GetAllTerms();
myTaxonomyCntrl.SspId.Add(termStore.Id);
myTaxonomyCntrl.TermSetId.Add(products.Id);
myTaxonomyCntrl.AllowFillIn = true;
myTaxonomyCntrl.IsMulti = false;

Alright, I know..References? Get the Utilities and Taxonomy from 14 Folder.

--> Button clicked Event

SPWeb spweb = SPContext.Current.Web;
SPGroup myVistors = spweb.ParentWeb.Groups["My Visitors"];
SPList SecuredDocs = spweb.Lists["Secured Documents"];
SetPermissions(SecuredDocs,myVistors);
SPField SecuredDocsField = SecuredDocs.Fields["Managed Metadata Column Name"];
SetDefaultValue(SecuredDocsField);

--> SetPermissions

private void SetPermissions(SPList lst, SPGroup grp)
{
try
{
lst.BreakRoleInheritance(true);
lst.RoleAssignments.Remove((SPPrincipal)grp);
lst.Update();
SPRoleDefinitionCollection collection = lst.ParentWeb.RoleDefinitions;
SPRoleDefinition roleDefinition = collection["Custom Permission Level"];
SPRoleAssignment roleAssignment = new SPRoleAssignment((SPPrincipal)grp);
roleAssignment.RoleDefinitionBindings.Add(roleDefinition);
lst.RoleAssignments.Add(roleAssignment);
lst.Update();
}
catch (SPException ex)
{
lblStatus.Text = ex.Message.ToString();
}
}

--> Set DefaultValue of the Manged Metadata Column
private void SetDefaultValue(SPField field)
{
try
{
TaxonomyField TF = (TaxonomyField)field;
TaxonomyFieldValue TFV = new TaxonomyFieldValue(field);
string txt = myTaxonomyCntrl.Text;
string[] ary = txt.Split('|');
TFV.Label = ary[0].ToString();
TFV.TermGuid = ary[1].ToString(); ;
TF.DefaultValue = TFV.ValidatedString;
TF.Update();
}
catch (SPException ex)
{
lblStatus.Text = ex.Message.ToString();
}
}
---> Redirect?
SPUtility.Redirect("settings.aspx", SPRedirectFlags.RelativeToLayoutsPage, this.Context);
--> Build and Deploy ;-)

November 09, 2010

Custom Layout Page in SharePoint Designer

http://blog.henryong.com/2010/06/08/how-to-create-custom-sharepoint-2010-page-layouts-using-sharepoint-designer-2010/

November 05, 2010

November 04, 2010

InfoPath and Content Organizer

1. Infopath or any workflows in sharepoint 2010 wont run automatically after an item created when logged in as System Account, For any user other than Configured in Application Pool, it will run with no problems.
2. Content Organizer is set to Content Types derived form Document only.
It means when you create a new document, rules are applied.
If infopath form is created, we need to attache a workflow to send the document to repository.
Repository location is given at the bottom of content organizer settings.
Once it sent to that, rules are applied with no issues.
3. Fields in Infopath form when published from Infopath designer, are created as Optional.
These wont be showing up as properties in Content Organizer Rules.
To make them show up, first create a site column from the site.
Use this site column when publishing the infopath form.
After published, go the content type published and make the field as required.
Things will show up and folders can be created with those properties.

October 29, 2010

JQUERY

$ - jquery

$("#id") - element whose id is "id"
$("id") - all elements whose id = "id"
$(".id") - all elements with class name "id"
.html() - gets the elements innerHTML
.html(string) - sets the elements inner html
.val() - gets the elements value
.val(value) - sets the elements value
\\ - escape character in jquery

Validate Decimal onKeyup in JS

//OnKeyup
function VD(txt)
{
if (txt.value.split('.').length > 2)
{
txt.value = txt.value.substr(0, txt.value.length-1);
}
}

Note: http://asquare.net/javascript/tests/KeyCode.html
// OnKeyPress
function ValidateDecimal(event) {
var keynum;
if(window.event) // IE
{
keynum = event.keyCode;
if (!((keynum >= 48 && keynum <= 57) || keynum == 46 || keynum == 37 || keynum == 39 || keynum == 8 || keynum == 9)) {
return false; }
}
else if(event.which) // Netscape/Firefox/Opera
{
keynum = event.which;
if (!((keynum >= 48 && keynum <= 57) || keynum == 0 || keynum == 9)) {
return false; }
}

}

October 19, 2010

How to Find out when moss trial expires

http://msmvps.com/blogs/shane/archive/2007/04/21/how-do-i-find-out-when-my-moss-trial-expires.aspx

October 12, 2010

AD Admin Tools on Windows 7

http://www.symantec.com/connect/blogs/installing-admin-tools-ad-users-computers-etc-windows-7

October 08, 2010

I love the looks of you - Porter,Cole

I love the looks of you and the lure of you
The sweet of you, and the pure of you
The eyes, the arms, and that mouth of you
The east, west, north and that south of you
I'd love to gain complete control of you
Handle even the heart and soul of you
'Casue I love all of you

October 07, 2010

Grid with Lots of Data

http://docs.dhtmlx.com/doku.php?id=dhtmlxgrid:toc_dhtmlxgrid_step_by_step

Sharepoint 2010 User Profile and My Sites Synchronization

Error: An error Occured in the claim providers
http://www.mstechblogs.com/sharepoint/an-error-has-occurred-in-the-claim-providers-sharepoint2010/

Problems with AD Synchronization:
Configure Alternate Access Mappings

Manage Service Applications --> User Profile Service Applications --> Configure Synchornization Connections --> Create Connection -->Auto Discover Controller name --> ForestName: DOMAIN.COm

MySiteSettings --> Setup my Sites -->
Take out /my

Start Profile Synchronization
http://social.technet.microsoft.com/Forums/en-US/sharepoint2010setup/thread/062ccf35-13ce-489b-8a8b-fd8a280bb9a1

Program Files\Microsoft Office Servers\14.0\Synchronization Service\UIShell\miisclient

October 05, 2010

Infopath Form Services - SharePoint Custom Lists

http://blogs.msdn.com/b/infopath/archive/2007/03/26/submitting-to-a-sharepoint-list.aspx

http://msdn.microsoft.com/en-us/library/cc162745(office.12).aspx#ip2007SubmitDataSPList_CleaningUptheLayoutoftheForm

http://blog.completesharepoint.net/post/2009/08/16/Integrating-Custom-ASPNET-ASPX-form-into-Sharepoint-InfoPath-Form-Service-Programmatically.aspx

October 01, 2010

OnBase Document Management

http://www.indiana.edu/~onbase/
http://www.lbmctech.com/blog/?p=21
http://www.hyland.com/downloads/flashdemo/index.html

Expandable GridView

http://www.codeproject.com/KB/ajax/ExpandPanelGridView.aspx

September 28, 2010

Active Directory Rights Management Services (AD RMS)

http://technet.microsoft.com/en-us/library/cc725699(WS.10).aspx

http://sharepointsolutions.blogspot.com/2008/01/single-server-rms-and-moss-2007_06.html

September 24, 2010

ASP.NET MVC - Building Web Apps without Web Forms

http://msdn.microsoft.com/en-us/magazine/cc337884.aspx

GridView in MVC:
http://www.tsck.net/DasBlog/PermaLink,guid,98a3f09c-5783-4a16-9a3e-087d519108eb.aspx

Server Controls:
http://weblogs.asp.net/scottgu/archive/2007/12/06/asp-net-mvc-framework-part-3-passing-viewdata-from-controllers-to-views.aspx

September 22, 2010

Security Advisory in Asp.Net and Sharepoint

http://blogs.msdn.com/b/sharepoint/archive/2010/09/21/security-advisory-2416728-vulnerability-in-asp-net-and-sharepoint.aspx

September 10, 2010

Excel Contents to Sharepoint Properties

http://www.21apps.com/sharepoint/exposing-excel-contents-to-make-reporting-easy-in-sharepoint/

Creating a MVC Application

http://stephenwalther.com/blog/archive/2009/02/07/chapter-2-building-a-simple-asp.net-mvc-application.aspx

September 09, 2010

August 25, 2010

Sign in as Different User in ASP.NET Applications

"Sign in as Different User" is one of a cool feautures in SharePoint and we can implement that in ASP.NET Applications too.
Below are the steps:
0. Default.aspx
1. Forms/frmHome.aspx
2. Forms/frmAccessDenied.aspx

IIS requires Default.aspx to redirect to Forms/frmHome.aspx

---------------------------frmHome.aspx-----------------------------
Keep a Link Button with Sign in as Different User as text

-----------------------frmHome.aspx code------------------------------

----------------------page load----------------------------------

protected void Page_Load(object sender, EventArgs e)
{
Control cause = GetPostBackControl(Page);
string sUser = "";
if (Request.LogonUserIdentity.IsAuthenticated == true)
{
if (!IsPostBack == true)
{
sUser = Request.LogonUserIdentity.Name;
sUser = sUser.Remove(0, sUser.IndexOf("\\") + 1);
txtLoginID.Text = sUser.ToUpper();
GetUserId();
FillRoles();
txtLoginID.Focus();
this.DisablePageCaching();
}
else if (cause.ClientID == "LinkButton1")
{
sUser = Request.LogonUserIdentity.Name;
sUser = sUser.Remove(0, sUser.IndexOf("\\") + 1);
txtLoginID.Text = sUser.ToUpper();
GetUserId();
FillRoles();
txtLoginID.Focus();
this.DisablePageCaching();
}
else
{
sUser = Request.LogonUserIdentity.Name;
sUser = sUser.Remove(0, sUser.IndexOf("\\") + 1);
txtLoginID.Text = sUser.ToUpper();
}
}
}

-----------------------------On CLick----------------------------------

protected void LinkButton1_Click(object sender, EventArgs e)
{
Response.Redirect("~/Forms/AccessDenied.aspx");
}

------------------------------DisablePageCaching---------------------------

public void DisablePageCaching()
{
Response.Expires = 0;
Response.Cache.SetNoStore();
Response.AppendHeader("Pragma", "no-cache");
}

--------------------Get the control which does post back----------------

public static Control GetPostBackControl(Page page)
{
Control postbackControlInstance = null;
string postbackControlName =
page.Request.Params.Get("__EVENTTARGET");
if (postbackControlName !=
null && postbackControlName != string.Empty)
{
postbackControlInstance =
page.FindControl(postbackControlName);
}
else
{
// handle the Button control postbacks

for (int i = 0; i < page.Request.Form.Keys.Count; i++) { postbackControlInstance = page.FindControl(page.Request.Form.Keys[i]); if (postbackControlInstance is System.Web.UI.WebControls.Button) { return postbackControlInstance; } } } // handle the ImageButton postbacks if (postbackControlInstance == null) { for (int i = 0; i < page.Request.Form.Count; i++) { if ((page.Request.Form.Keys[i].EndsWith(".x")) || (page.Request.Form.Keys[i].EndsWith(".y"))) { postbackControlInstance = page.FindControl(page.Request.Form.Keys[i].Substring (0,page.Request.Form.Keys[i].Length - 2)); return postbackControlInstance; } } } return postbackControlInstance; } --------------frmAccessDenied.aspx.cs-------------- using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; public partial class Forms_AccessDenied : System.Web.UI.Page { private int _authenticationAttempts = 0; public int AuthenticationAttempts { get { if (!string.IsNullOrEmpty(string.Format("{0}", Session["AuthenticationAttempts"]))) { int.TryParse(Session["AuthenticationAttempts"].ToString(), out _authenticationAttempts); } return _authenticationAttempts; } set { _authenticationAttempts = value; Session["AuthenticationAttempts"] = _authenticationAttempts; } } private string _currentUser = string.Empty; public string CurrentUser { get { _currentUser = Request.LogonUserIdentity.Name; Session["CurrentUser"] = _currentUser; return _currentUser; } set { _currentUser = value; Session["CurrentUser"] = _currentUser; } } private string _previousUser = string.Empty; public string PreviousUser { get { _previousUser = string.Format("{0}", Session["PreviousUser"]); return _previousUser; } set { _previousUser = value; Session["PreviousUser"] = _previousUser; } } ///
/// This event fires on every page load
///

/// /// protected void Page_Load(object sender, EventArgs e)
{
// Make sure the browser does not cache this page
this.DisablePageCaching();

// Increase authentication attempts
this.AuthenticationAttempts = this.AuthenticationAttempts + 1;

if (this.AuthenticationAttempts == 1)
{
// Change previous user to current user
this.PreviousUser = this.CurrentUser;

// Send the first 401 response
this.Send401();
}
else
{
// When a browser is set to "automaticaly sign in with current credentials", we have to send two 401 responses to let the browser re-authenticate itself.
// I don't know how to determine if a browser is set to "automaticaly sign in with current credentials", so two 401 responses are always send when the user
// does not switch accounts. In Micrososft Office sharepoint the user has to supply the credentials 3 times, when the user does not switch accounts,
// so it think this is not a problem.
if (this.AuthenticationAttempts == 2 && this.CurrentUser.Equals(this.PreviousUser))
{
// Send the second 401 response
this.Send401();
}
else
{
// Clear the session of the current user. This will clear all sessions objects including the "AuthenticationAttempts"
Session.Abandon();
Session.Clear();

// Redirect back to the main page
Response.Redirect("~/Forms/frmHome.aspx");
}
}
}

///
/// Make sure the browser does not cache this page
///

public void DisablePageCaching()
{
Response.Expires = 0;
Response.Cache.SetNoStore();
Response.AppendHeader("Pragma", "no-cache");
}
///
/// Send a 401 response
///

public void Send401()
{
// Create a 401 response, the browser will show the log-in dialogbox, asking the user to supply new credentials, // if browser is not set to "automaticaly sign in with current credentials"
Response.Buffer = true;
Response.StatusCode = 401;
Response.StatusDescription = "Unauthorized";

// A authentication header must be supplied. This header can be changed to Negotiate when using keberos authentication
Response.AddHeader("WWW-Authenticate", "NTLM");

// Send the 401 response
Response.End();
}
}

-----------------------IIS 7 Settings -- IMPT --------------------------

1. Once you publish the website to wwwroot
2. Under Default Site in IIS, right click the folder and convert it to application
3. Disable Anaonymous authentication and enable only windows authentication
4. Check Permissions under Secuirty Tab of Virtual Directory if users have access or not.

----------------------------Web.Config---------------------------------

<authentication mode="Windows"/>
<identity impersonate="false" />
<authorization>
<allow users="?"/>
</authorization>

--------------------------Happy Coding ----------------------------------

August 19, 2010

Upload Request Timed Out and Sign in as Different User in asp.net

1. Error message when you try to upload a large file to a document library on a Windows SharePoint Services 3.0 site: "Request timed out"

Refer: http://support.microsoft.com/kb/925083

2. ASP .NET – C# – How to “Sign in as Different User” like in Microsoft SharePoint with Windows Authentication

Refer: http://www.roelvanlisdonk.nl/?p=825

July 30, 2010

SharePoint and TFS Integration

http://blogs.msdn.com/b/teams_wit_tools/archive/2009/06/01/sharepoint-integration-in-tfs-2010-beta1.aspx

July 16, 2010

Create Table Script in Sql Server

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[TableName](
[ID] [bigint] IDENTITY(1,1) NOT NULL,
[ColumnName] [nvarchar](50) NOT NULL
) ON [PRIMARY]
GO

....Creates a table with ID as Primary Key with an increment 1 starting with 1

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[TableName](
[ID] [bigint] IDENTITY(0,1) NOT NULL,
[ColumnName] [nvarchar](50) NOT NULL
) ON [PRIMARY]
GO

....Create a table with ID as Primary Key with an increment 1 starting with 0

Alter Table Sql Server 2008

The Alter Column statement can modify the data type and the Nullable attribute of a column. The syntax is the same for SQL Server 2005 and SQL Server 2008 except 2008 allows the sparse attribute to be changed.

For the example below, we will begin by creating a sample table, then we will modify the columns.

CREATE TABLE dbo.Employee

(

EmployeeID INT IDENTITY (1,1) NOT NULL

,FirstName VARCHAR(50) NULL

,MiddleName VARCHAR(50) NULL

,LastName VARCHAR(50) NULL

,DateHired datetime NOT NULL

)



-- Change the datatype to support 100 characters and make NOT NULL

ALTER TABLE dbo.Employee

ALTER COLUMN FirstName VARCHAR(100) NOT NULL



-- Change datatype and allow NULLs for DateHired

ALTER TABLE dbo.Employee

ALTER COLUMN DateHired SMALLDATETIME NULL



-- Set SPARSE columns for Middle Name (sql server 2008 only)

ALTER TABLE dbo.Employee

ALTER COLUMN MiddleName VARCHAR(100) SPARSE NULL
Columns can be altered in place using alter column statement.

•Only the datatype, sparse attribute (2008) and the Nullable attribute of a column can be changed.
•You cannot add a NOT NULL specification if NULL values exist.
•In order to change or add a default value of a column, you need to use Add/Drop Constraint.
•In order to rename a column, you must use sp_rename.

For Primary Key and Foreign Key Constraints:

Alter table dbo.TableName add primary key (ID);

Alter table dbo.Table Name Add constraint columnname_id_refs Foreign key ("columnname") References dbo.TableNamewithPrimaryKey ("PrimaryKeyColumnName");

Database backup File Location

\\Server\d$\Program Files\Microsoft SQL Server\MSSQL10.MSSQLSERVER\MSSQL\Backup

OfCourse you can change, but this is default one to go.

NOte: regarding the error when taking back up saying, media is supported with 2 families ..
The above path is teh culprit..take out that one and add new one ...it wont complain...if you keep this one and change the other one..it will complain like..access denied or media support...bla blah

July 09, 2010

Popup in SharePoint using LyteBox

1. Download the Lytebox files from http://www.dolem.com/lytebox/lytebox_v3.22.zip
2. Create a Document Library
3. Create images folder inside the Document Library
4. Upload files and Upload image files in Images folder respectively.
5. Go to any page you wanna use this feature.
6. Edit the page and add content editor web part.
7. In source view add
<script type="text/javascript" language="javascript" src="NameofLib/lytebox.js"></script>
<link rel="stylesheet" href="NameofLib/lytebox.css" type="text/css" media="screen" />
8. Add Another Content Editor Webpart
9. In Souce View Add
<A href="www.google.com" rel="lyteframe" title="My Page" rev="width: 600px; height: 700px; scrolling: no">Google</A>
10. Exit the Edit Mode

Note: Twaeking the Point 7 may require when stylesheet is not getting referenced.
Like using "../NameofLib/lytebox.js"

July 01, 2010

Version Build Numbers LookUp

http://www.sharepointgally.com/2010/03/moss-2007-windows-sharepoint-services.html

June 30, 2010

Single Sign on between Sharepoint and ASP.Net Applications

All Applications to be hosted in one IIS and shud be set to windows authentication in web.config files.
Otherwise..some Kerberos Delegation...Networking and stuff.

http://social.msdn.microsoft.com/Forums/en/sharepointdevelopment/thread/f38b4ea1-ab7e-4d55-b64f-01d6db8b02ab

June 29, 2010

Custom timer job in SharePoint

When we want to run a task (like sending emails or deleting the list items etc. . . ) in Daily basis or in Hourly basis then we can use a Timer job to this task .To see the timer job you can move to the Central Administrations then click on the operations tab, then in the Global Configuration section you can see the Timer job status and timer job definition. In timer job definition you can get the details of the timer job i.e. the title , the web application to which it is attached and the schedule type i.e. Daily, Weekly or hourly basis. To get the status of the timer job go to the timer job status, here you can view status.
Steps To create a custom timer job:

1. We need to create a class that inherits the SPJobDefinition Class. Then we need add the constructor s and the Execute () method.

namespace TestTimerJob {

public class CustomTimerJob : SPJobDefinition{

public CustomTimerJob (): base(){

}

/// <summary>

/// Initializes a new instance of the TaskJob class.

/// </summary>

/// <param name="jobName">
Name of the job.</param>

/// <param name="service">
The service.</param>

/// <param name="server">
The server.</param>

/// <param name="targetType">
Type of the target.</param>

public CustomTimerJob (string jobName, SPService service, SPServer server, SPJobLockType targetType)

: base (jobName, service, server, targetType) {

}

/// <summary>

/// Initializes a new instance of the TaskJob class.

/// </summary>

/// <param name="jobName">
Name of the job.</param>

/// <param name="webApplication">
The web application.</param>

public CustomTimerJob(string jobName, SPWebApplication webApplication)

: base (jobName, webApplication, null, SPJobLockType.ContentDatabase) {

this.Title = "Test Timer Job";

}

/// <summary>

/// Executes the specified content db id.

/// </summary>

/// <param name="contentDbId">
The content db id.</param>

public override void Execute (Guid contentDbId)

{

//Do the Operation which u want to perform

}

}

}




2. As we are going to deploy the timer job as a feature so we need to create another class which will implement the SPFeatureReceiver class. This class contains the event handlers. Here we can define the task which we are going to do when a feature will be installed, activated, deactivated and uninstalled.

namespace TestTimerJob {

class TaskJobInstaller:SPFeatureReceiver {

/// <summary>

/// Occurs after a Feature is installed.

/// </summary>

/// <param name="properties">
An <see cref="T:Microsoft.SharePoint.SPFeatureReceiverProperties"></see> object that represents the properties of the event.</param>

public override void FeatureInstalled (SPFeatureReceiverProperties properties) {

}

/// <summary>

/// Occurs when a Feature is uninstalled.

/// </summary>

/// <param name="properties">
An <see cref="T:Microsoft.SharePoint.SPFeatureReceiverProperties"></see> object that represents the properties of the event.</param>

public override void FeatureUninstalling (SPFeatureReceiverProperties properties) {

}

/// <summary>

/// Occurs after a Feature is activated.

/// </summary>

/// <param name="properties">
An <see cref="T:Microsoft.SharePoint.SPFeatureReceiverProperties"></see> object that represents the properties of the event.</param>

public override void FeatureActivated(SPFeatureReceiverProperties properties)

{

// register the the current web

SPSite site = properties.Feature.Parent as SPSite;

// make sure the job isn't already registered

foreach (SPJobDefinition job in site.WebApplication.JobDefinitions)

{

if (job.Name == "Test Timer Job")

job.Delete();

}

// install the job

TaskJob taskJob = new TaskJob("Test Timer Job", site.WebApplication);

//To perform the task on daily basis

SPDailySchedule schedule = new SPDailySchedule();

schedule.BeginHour = 2;

schedule.BeginMinute = 10;

schedule.BeginSecond = 0;

schedule.EndHour = 2;

schedule.EndMinute = 20;

schedule.EndSecond = 0;

taskJob.Schedule = schedule;

taskJob.Update();

}

/// <summary>

/// Occurs when a Feature is deactivated.

/// </summary>

/// <param name="properties">
An <see cref="T:Microsoft.SharePoint.SPFeatureReceiverProperties"></see> object that represents the properties of the event.</param>

public override void FeatureDeactivating (SPFeatureReceiverProperties properties) {

SPSite site = properties.Feature.Parent as SPSite;

// delete the job

foreach (SPJobDefinition job in site.WebApplication.JobDefinitions) {

if (job.Name == "Test Timer Job")

job.Delete();

}

}

}

}

3. Create a feature.xml file to deploy the feature.

<?xml version="1.0" encoding="utf-8" ?>

<feature xmlns="http://schemas.microsoft.com/sharepoint/"

Id="DA0DAC0D-B1C3-4832-91ED-A20DEDC16BD4"

Title="Test Timer job"

Description="Performs the scheduled SHP tasks"

Scope="Site"

Hidden="FALSE"

Version="1.0.0.0"

ReceiverAssembly="TestTimerJob, Version=1.0.0.0, Culture=neutral, PublicKeyToken=293e555b2fe2e92a"

ReceiverClass="TestTimerJob.TaskJobInstalle">

</Feature>

4, Create a folder inside. C:\Program Files\Common Files\Microsoft Shared\web server extensions\12\TEMPLATE\FEATURES\ and place this file inside the folder.

Now you can install the feature using the STSADM command .After installing the feature when you activate this feature on a SharePoint site then you will be able to see the Timer job in the Timer job definition inside the central administrator.

stsadm -o installfeature -filename folder\feature.xml -force
stsadm -o activatefeature -filename folder\feature.xml -url http://...
stsadm -o deactivatefeature -filename folder\feature.xml -url http://...

SharePoint Event Handlers

Event handling ?

The ability to catch certain user actions in code and respond programmmatically. These are the classes which we can inherit and write event handlers or receivers against them.

SPItemEventReceiver

SPListEventReceiver

SPWebEventReceiver

Which user actions you can catch?

ItemFileMove,IFMoving, ItemUpdated,ItemUpdating, ItemCheckedIn/Out, ItemCheckingIn/ItemChecingOut, ItemAdded,IAdding, ItemAttachementAdded/Adding, ItemDeleted/Deleting.

What is template id for customlist, document library, survey?

100 Custom List 101 Document Library 102 Survey 103 Links List 104 Announcements 105 Contacts

106 Events List 107 Tasks List 108 Discussion Board 109 Picture Library

Explain the steps for creating event handlers?

1) Create a class library project.

2) Add reference to Microsoft.Sharepoint.dll

3) Inherit the class SPItemEventReceiver

4) Override the method against which you want to attach the event handler.

e.g. for itemdeleting

namespace MyEventHandler{

public class ItemDeletingHandler : SPItemEventReceiver{

public override void ItemDeleting(SPItemEventProperties properties){

if(properties.ListTitle == “MyDocumentLibrary”){

// only the admin user has right to delete the uploaded document

if (!properties.UserLoginName.Contains(“domainnameadminUserName”)){

properties.ErrorMessage = “You don’t have sufficient privelege to delete on list “+properties.ListTitle;

properties.Cancel = true;}}}}}

5) Sign the assembly and put it in GAC i.e. c:windowsassembly

6) Create a new folder with the same name as your eventhandler at the following path

c:program filescommon filesmicrosoft sharedweb server extension12templateFeatures folder

7) Create two files feature.xml and elements.xml at the newly created folder.

Take feature.xml file of announcement and make the necessary changes to it.

<?xml version=“1.0“ encoding=“utf-8“?>

<Feature Id=“C50FF499-B52A-471f-A9FB-36A49E2FA49F“

Title=“MyEventHandler“

Description=“For restricting delete of a list“

Scope=“Web“

xmlns=“http://schemas.microsoft.com/sharepoint/“>

<ElementManifests>

<ElementManifest Location=“Elements.xml“/>

</ElementManifests>

</Feature>

9) Within elements.xml specify

<?xml version=“1.0“ encoding=“utf-8“?>

<Elements xmlns=“http://schemas.microsoft.com/sharepoint/“>

<Receivers ListTemplateId=“101“>

<Receiver>

<Name>MyEventHandler</Name>

<Type>ItemDeleting</Type>

<SequenceNumber>20000</SequenceNumber>

<Assembly>

MyEventHandler, Version=1.0.0.0,

culture=neutral, PublicKeyToken=e185cb2eba5d0774

</Assembly>

<Class>MyEventHandler.ItemDeletingHandler</Class>

<Data></Data>

<Filter></Filter>

</Receiver>

</Receivers>

</Elements>

Get the values for assembly tag by right clicking the assembly and selecting properties within the GAC.

If we have multiple eventhandler attached to a same event we can specify which handler should be executed first through SequenceNumber tag. It’s value should start from 20000

10) Now install the feature

stsadm.exe -o installfeature -filename MyEventHandlerfeature\Feature.xml

11) Activate the feature

stsadm -o activatefeature -filename MyEventHandlerfeature\Feature.xml -URL http://localhost.

June 28, 2010

Hide Port Numbers in Sharepoint Applications (or) create all applications on one port..i.e on Port 80

1. While Creating the application, give the same port number but different host header for each application.
2. Add entry in DNS for that Host Header with the IP Address.
3. If DNS is not available, add entry in C:\Windows\System32\drivers\etc\HOSTS file with the host header and the system ip address.
Restart the IIS and Recycle the Application Pool.
Note: Site opens only in the computer where u enter the entry in HOSTS File.
4. For already created applications with different ports, go to edit bindings property of the website in IIS and change the port back to 80 and add a Host header and do the same above steps for resolving.
5. Might need to add in Alternate access mappings also in case we need to find search results.

Note: Application might be asking the credentials in a loop trying to authenticate, Windows Error..Below is the fix.

Follow these steps: Disabling the LoopBackCheck
1. Click Start, click Run, type regedit, and then click OK.
2. In Registry Editor, locate and then click the following registry key:
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Lsa
3. Right-click Lsa, point to New, and then click DWORD Value.
4. Type DisableLoopbackCheck, and then press ENTER.
5. Right-click DisableLoopbackCheck, and then click Modify.
6. In the Value data box, type 1, and then click OK.
7. Quit Registry Editor, and then restart your computer

June 14, 2010

Central Administration - 403 Error - File Not Found - Access Denied - SharePoint 2010

Here is the **ucking Scenario,

1. Windows 2008 Server R2 [Front-End]
2. Windows 2008 Server R2 [Database server]
3. Installed Sharepoint Server 2010, Ran Sharepoint products and configuration wizard and everything is fine as it directs.
4. Insatlled all pre-rwq's on databse Server too.
5. Happies
6. Wanted to implement Search, cannot able to create a Search Service Application.
7. Online help - Ran Sharepoint products and Configuaration Wizard again.
8. All Sites Works, Central Admin gives 403 Error, file Not found..etc.

Resolution:

0. IISRESET, Rrefesh Application Pool, etc ....mostly doesn't work..then
1. Install the updates on Frond-End Server. There must be
Service Pack 1 for SQL Server Business Intelligence Development Studio 2008 (64-bit) (KB968369)......which was my Villian.
2. Install all updates on Database and FronEnd servers.
3. Restart the Servers.
4. Wait couple of minutes before opening Central Admin.
5. Aloha, mine was solved and if it is different from the above issue please post the resolution online...coz i searched for this like 2 days and no help online...So, help and get helped my friends.

Note: Sometimes it's nothing wrong technically, if you access the url like
http://FQDNofServer:Port/Default.aspx it works instead of just
http://FQDNofServer:Port

Help:
1. Stsadm -o deleteconfigurationobject -id Guid [removes a Service Application by id]
2. Psconfig.exe -cmd services -install [Installs Sharepoint products & Services]
3. stsadm -o spsearch -action stop|start

May 12, 2010

SharePoint Server 2010

Four Versions:
1. SharePoint Server 2010 Enterprise Client Access License features
For organizations looking to expand their business collaboration platform to enable advanced scenarios.
2. SharePoint Server 2010 for Internet Sites, Enterprise
For organizations looking to create customer-facing public internet sites and private extranets using the full enterprise capabilities of SharePoint.
3. SharePoint Server 2010 Standard Client Access License features
For organizations looking to deploy a business collaboration platform across all types of content
4. SharePoint Server 2010 for Internet Sites, Standard
For small and mid-sized organizations looking to create public Internet sites or basic extranets using the Standard features of SharePoint Server 2010.

Capability Areas:
1. Sites
• SharePoint Ribbon user interface
• Easy Web editing
• Cross-browser support and improved mobile experience
• SharePoint Workspace 2010
• Office Web Applications
• Personalization
• Standards and Accessibility
2. Communities
• My Sites
• Social feedback
• Wikis
• Blogs
3. Search
4. Content
• Document management
• Records management
• Rich media management
• Web content management
5. Insights
6. Composites

.....To Be Continued

References:

1. Migration
http://www.sharepointproconnections.com/article/sharepoint-server-2010/Migrating-to-SharePoint-2010-104619.aspx
2. http://sharepointgeorge.com/2009/upgrading-content-database-sharepoint-2010-database-attach-method/

Errors/Issues:
1. CabLib Compress ERROR: Could not flush cabinet: Could not create cabinet file [Happens after when u upgraded and deploying the web parts]
Solution: If you encounter this error when building a WSP it could mean that your files are read-only. Most source control tools mark files as read-only when a file is checked in. Either use the source controls tool to make the file writeable or right-click the file (or root folder) select Properties and uncheck Read-Only.
2. Content Database Attach Upgrade Fails
Solution: We cannot have same database content in two databases with different names.
Reason: Same Site It cannot be in two different places.
3. Creating a new web application fails and doesn't give confirmation message.
Solution: Happens when you are trying to create sites on the ports which u used earlier/deleted and application pools still exist for that port.
Delete unused application pools and if problem still persists restart the server (or) create on a new port.
4. Found 1 web(s) using missing web template 75816 (lcid: 1033) in ContentDatabase.
Solution: http://www.microsoft.com/downloads/details.aspx?FamilyId=C1039E13-94DA-4D7D-8CAE-3B96FA5A4045&displaylang=en
http://www.microsoft.com/downloads/details.aspx?FamilyId=CE90D6D7-7B96-47BF-A22F-A7E8C5D40647&displaylang=en
Install.
5. Twitter SharePoint web part
Solution: This can be downloaded from http://www.aidangarnish.net/blog/post/2009/02/Twitter-SharePoint-web-part.aspx
Install the webpart using following steps:
stsadm -o addsolution -filename \Nameofwsp.wsp
You can either use Central Administration > Manage Farm Solutions>Deploy Solution to deploy the solution or use following command:
stsadm -o deploysolution -name Nameofwsp.wsp -allowgacdeployment
(Additional attributes may be required based on your Windows SharePoint Services configuration. For example:
Single Server: [ -local | -time

April 30, 2010

Javascipt in Content Editor Webpart

<script language="JavaScript">
_spBodyOnLoadFunctionNames.push("HideLink");
function HideLink()
{
var currentUser = getCurrentUser();
if(currentUser == 'New Consultant')
{
var emp = document.getElementById("emp");
emp.style.display = "none";
}
if(currentUser == 'New Employee')
{
var con= document.getElementById("con");
con.style.display = "none";
}
}
function getCurrentUser()
{
var tags = document.getElementsByTagName('a');
for (var i=0; i < tags.length; i++)
{
if(tags[i].innerText.substr(0,7) == 'Welcome')
{
return tags[i].innerText.substr(8,tags[i].innerText.length);
}
}
}
</Script>

April 21, 2010

Mail to:

mailto:This is To?subject=This%20is%20Subject&cc=This is CC&bcc=This is BCC&body=CXI%20Welcomes%20You%0D%0A%0D%0AClick%20Below%20for%20the%20Documents%0D%0Ahttp%3A%2F%2Fmytestsite.net%2Fhr%2FLists%2FW5%2520AllLinks%2FAllItems.aspx

To test, just copy this and test in IE, it hsould open the Outlook email iwth desired content

April 20, 2010

April 13, 2010

For Sharepoint Controls Style Sheets reference

http://sharepoint.microsoft.com/blogs/zach/Master%20Page%20Cheat%20Sheet/Forms/ViewAll.aspx

April 05, 2010

Slokas

PRAYER: SLOKAS

OM………….OM……….. OM
SAHANA VAVATU, SAHANOV BHUNAKTU
SAHA VEERYAM KARAVAVAHAI
TEJASVINA AVAIHITAMASTU
MAHID VISHA VAHAI
OM SHANTHI…………. OM SHANTHI………….. OM SHANTHI

Let us be together, Let us eat together, Let us produce the energy together, Let there be no limit to our Energies, Let there be no ill feeling among us, OM………peace, peace, peace.

OM………..OM……….OM
ASATOMA SATGAMAYA
TAMSOMA JYOTIRGAMAYA
MRITYORMA AMRITAM GAMAYA
OM………….. SHANTHI……………..SHANTHI…………SHANTHI

Lead us from untruth to truth; From ignorance to enlightenment. From death to immortality.

OM……………SHANTHI………….SHANTHI………SHANTHI
OM PURNAMADAH PURNAMIDAM PURNAT PURNAMUDACYATE
PURNASYA PURNAMADAYA PURNAMEVAVASISYATE

Completeness is that, completeness is this
From completeness, completeness comes forth.
Completeness from completeness taken away
Completeness to completeness added,
Completeness alone remains.

March 31, 2010

SharePoint Master Page

<%-- Identifies this page as a .master page written in Microsoft Visual C# and registers tag prefixes, namespaces, assemblies, and controls. --%>
<%@ Master language="C#" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<%@ Import Namespace="Microsoft.SharePoint" %>
<%@ Register Tagprefix="SPSWC" Namespace="Microsoft.SharePoint.Portal.WebControls" Assembly="Microsoft.SharePoint.Portal, Version=12.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
<%@ Register Tagprefix="SharePoint" Namespace="Microsoft.SharePoint.WebControls" Assembly="Microsoft.SharePoint, Version=12.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
<%@ Register Tagprefix="WebPartPages" Namespace="Microsoft.SharePoint.WebPartPages" Assembly="Microsoft.SharePoint, Version=12.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
<%@ Register Tagprefix="PublishingWebControls" Namespace="Microsoft.SharePoint.Publishing.WebControls" Assembly="Microsoft.SharePoint.Publishing, Version=12.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
<%@ Register Tagprefix="PublishingNavigation" Namespace="Microsoft.SharePoint.Publishing.Navigation" Assembly="Microsoft.SharePoint.Publishing, Version=12.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
<%@ Register TagPrefix="wssuc" TagName="Welcome" src="~/_controltemplates/Welcome.ascx" %>
<%@ Register TagPrefix="wssuc" TagName="DesignModeConsole" src="~/_controltemplates/DesignModeConsole.ascx" %>
<%@ Register TagPrefix="PublishingVariations" TagName="VariationsLabelMenu" src="~/_controltemplates/VariationsLabelMenu.ascx" %>
<%@ Register Tagprefix="PublishingConsole" TagName="Console" src="~/_controltemplates/PublishingConsole.ascx" %>
<%@ Register TagPrefix="PublishingSiteAction" TagName="SiteActionMenu" src="~/_controltemplates/PublishingActionMenu.ascx" %>
<%-- Uses the Microsoft Office namespace and schema. --%>
<html>
<WebPartPages:SPWebPartManager runat="server"/>
<SharePoint:RobotsMetaTag runat="server"/>

<%-- The head section includes a content placeholder for the page title and links to CSS and ECMAScript (JScript, JavaScript) files that run on the server. --%>
<head runat="server">
<asp:ContentPlaceHolder runat="server" id="head">
<title>
<asp:ContentPlaceHolder id="PlaceHolderPageTitle" runat="server" />
</title>
</asp:ContentPlaceHolder>
<Sharepoint:CssLink runat="server"/>
<asp:ContentPlaceHolder id="PlaceHolderAdditionalPageHead" runat="server" />
</head>

<%-- When loading the body of the .master page, SharePoint Server 2007 also loads the SpBodyOnLoadWrapper class. This class handles .js calls for the master page. --%>
<body onload="javascript:_spBodyOnLoadWrapper();">
<%-- The SPWebPartManager manages all of the Web part controls, functionality, and events that occur on a Web page. --%>
<form runat="server" onsubmit="return _spFormOnSubmitWrapper();">
<wssuc:Welcome id="explitLogout" runat="server"/>
<PublishingSiteAction:SiteActionMenu runat="server"/>
<PublishingWebControls:AuthoringContainer id="authoringcontrols" runat="server">
<PublishingConsole:Console runat="server" />
</PublishingWebControls:AuthoringContainer>
<%-- The PlaceHolderMain content placeholder defines where to place the page content for all the content from the page layout. The page layout can overwrite any content placeholder from the master page. Example: The PlaceHolderLeftNavBar can overwrite the left navigation bar. --%>
<asp:ContentPlaceHolder id="PlaceHolderMain" runat="server" />
<asp:Panel visible="false" runat="server">
<%-- These ContentPlaceHolders ensure all default SharePoint Server pages render with this master page. If the system master page is set to any default master page, the only content placeholders required are those that are overridden by your page layouts. --%>
<asp:ContentPlaceHolder id="PlaceHolderSearchArea" runat="server"/>
<asp:ContentPlaceHolder id="PlaceHolderTitleBreadcrumb" runat="server"/>
<asp:ContentPlaceHolder id="PlaceHolderPageTitleInTitleArea" runat="server"/>
<asp:ContentPlaceHolder id="PlaceHolderLeftNavBar" runat="server"/>
<asp:ContentPlaceHolder ID="PlaceHolderPageImage" runat="server"/>
<asp:ContentPlaceHolder ID="PlaceHolderBodyLeftBorder" runat="server"/>
<asp:ContentPlaceHolder ID="PlaceHolderNavSpacer" runat="server"/>
<asp:ContentPlaceHolder ID="PlaceHolderTitleLeftBorder" runat="server"/>
<asp:ContentPlaceHolder ID="PlaceHolderTitleAreaSeparator" runat="server"/>
<asp:ContentPlaceHolder ID="PlaceHolderMiniConsole" runat="server"/>
<asp:ContentPlaceHolder id="PlaceHolderCalendarNavigator" runat ="server" />
<asp:ContentPlaceHolder id="PlaceHolderLeftActions" runat ="server"/>
<asp:ContentPlaceHolder id="PlaceHolderPageDescription" runat ="server"/>
<asp:ContentPlaceHolder id="PlaceHolderBodyAreaClass" runat ="server"/>
<asp:ContentPlaceHolder id="PlaceHolderTitleAreaClass" runat ="server"/>
<asp:ContentPlaceHolder id="PlaceHolderBodyRightMargin" runat="server" />
</asp:Panel>
</form>
</body>
</html>

March 29, 2010

IIS Redirect IIS 6 and IIS 7

ha ha...lots of hours and unexpectedly fixed the issue of IIS redirect.

Scenario:
1. Website URL is http://Server:Port/Sites/SiteName
2. User wants to type only http://Server:Port
Note: No Site Exists in Root, All Sites Exist under /Sites..

Resolution on IIS 6.0
1. Go to Properties of the IIS Virtual Directory of our Folder.
2. Home Directory
3. Select: A redirection to URL
4. Redirect to: /Sites/SiteName
5. Check: A directory below URL entered
6. Apply and Test.

Resolution on IIS 7.0
1. Go to Properties of the IIS Virtual Directory of our Folder.
2. In the Right Pane where all Propeties Listed, Double Click HTTP redirect
3. Check: Redirect requests to this destination
4. Redirect to: /Sites/SiteName
5. Check: Only redirect requests to content in this directory (not subdirectories)
6. Apply and Test.

March 25, 2010

Send Email Using Command Line - Telnet

1. Open Command Prompt
2. telnet EmalExchangeServer 25
3. HELO EmailExchangeServer
4. MAIL FROM:YourEmailAddress.........[May Get Reply "250 ok"]
5. RCPT TO:EmailAddress1,EmailAddress2 etc..[May Get Reply "250 ok"]
6. To Write Message, DATA
7. SUBJECT:YourSubject[Enter TWice]
8. Type the Message you Want
9. Put a single period (.) on a line by itself and press Enter to send your message. The server should say 'Message accepted for delivery'.
(Or it says 250 OK id=`a long id`)
8. QUIT to exit telnet

March 24, 2010

Windows and Forms Authentication

1. Create or Extend a Web Application.
2. Deployed CKS.FBA for Forms Based Authentication.
3. Modified Parser Paths in Web.Config if any of the master page has c# code in it.
<PageParserPaths>
<PageParserPath VirtualPath="/_catalogs/masterpage/Home.master" CompilationMode="Always" AllowServerSideScript="true">
</PageParserPath>
<PageParserPath VirtualPath="/_catalogs/masterpage/Home_Template.master" CompilationMode="Always" AllowServerSideScript="true">
</PageParserPath>
<PageParserPath VirtualPath="/_catalogs/masterpage/InnerPage.master" CompilationMode="Always" AllowServerSideScript="true">
</PageParserPath>
</PageParserPaths>
4. Added Safe Controls
5. Browse to C:\Windows\Microsoft.NET\Framework64\v2.0.50727
6. Run Aspnet_regsql.exe and create a database for Membership Provider.
7. Add Membership Provider information in web.config along with the Connection String
<connectionStrings>
<add name="FBAConnectionString" connectionString="Data Source=DBServerName ;Initial Catalog=DBName;Integrated Security=True" />
</connectionStrings>
<system.web>
<!--
Set compilation debug="true" to insert debugging
symbols into the compiled page. Because this
affects performance, set this value to true only
during development.
-->
<!-- membership provider -->
<membership defaultProvider="FBAMember">
<providers>
<add connectionStringName="FBAConnectionString" enablePasswordRetrieval="false" enablePasswordReset="true" requiresQuestionAndAnswer="false" applicationName="/" requiresUniqueEmail="false" passwordFormat="Hashed" maxInvalidPasswordAttempts="5" minRequiredPasswordLength="1" minRequiredNonalphanumericCharacters="0" passwordAttemptWindow="10" passwordStrengthRegularExpression="" name="FBAMember" type="System.Web.Security.SqlMembershipProvider,System.Web,Version=2.0.0.0,Culture=neutral,PublicKeyToken=b03f5f7f11d50a3a" />
</providers>
</membership>
<!-- role provider -->
<roleManager enabled="true" defaultProvider="FBARole">
<providers>
<add connectionStringName="FBAConnectionString" applicationName="/" name="FBARole" type="System.Web.Security.SqlRoleProvider,System.Web,Version=2.0.0.0,Culture=neutral,PublicKeyToken=b03f5f7f11d50a3a" />
</providers>
</roleManager>
<securityPolicy>
Note: All the web.config changes are needed to restore an already application, otherwise no touching on Web.Config needed other than Membership Provider.
8. Extend the Application
9. Authentication Provider, Set to Forms and Give the Name of the Provider which you mentioned in Web.config
10.All Membership additions in web.config should also be added in central admin Port also.
11. Add Users in Extended Application through IIS, .Net Users.
12. In Central Admin, Keep one FBA User as Collection Adminisatrtor (Important)
13. Now Have Fun with Windows and Forms
14. Error: Unknown Error mostly is because the secondary site collection adminsiatrtor is not set with fba user., add it in central admin and you will be fine.

Object reference not set to instance of an object .... while running stsadm.exe in adding the solution through wsp etc

The problem here is that the user you are logged in with does not have the required permissions for the database server.
Note: Remote Login -> Sql Server Management Studio --> Connect to Database --> Logins --> New Login --> Mappings, Server Roles etc.
Note: In User Mappings, Give db_owner role for all the databases needed.
If you run this with the same account as you installed your web applications with, there should be no problem.
You will need full control to the content database.
stsadm always uses credentials of the logged in user, unless offcourse you open your command prompt like this “runas /user:mydomain\myuser cmd.exe”.
Exchange mydomain and myuser with the values for the user you want to open a command prompt as.

March 18, 2010

Eye Excercises

The Cure: Eye exercise : The following exercises will loosen the strained and contracted muscles surrounding the eyes :

a. Keep your head still and relaxed. Gently move the eyes up and down six times. Repeat the same movement twice or thrice at 2-second intervals. The eyes should move slowly and regularly as far down as possible and then as far up as possible.

b. Move the eyes from side to side as far as possible, without any force or effort six times. Repeat two or three times.

c. Hold the index finger of your right hand about 8 inches in front of the eyes, then look from the finger to any other large object ten or more feet away - the door or window will do. Look from one to the other 10 times. Do this exercise fairly rapidly.

d. Move the eyes up gently and slowly in a circle, then move them low in the reverse direction. Do this four times in all. Rest for a second and repeat the movements two or three times, using minimum efforts. All eye muscle exercises should be performed while seated in a comfortable position.

Neck Exercises: Rotate the neck.

a. In circles and semi circles.

b. Move the shoulders clockwise and anti-clockwise brisky, drawing them up as far as possible several times.

c. Allow the head to draw forward and backward as far as possible.

d. Turn the head to the right and left as far as possible several times. These exercises help to loosen up contracted neck muscles which may restrict blood supply to the head.

Sun gazing: Sit on a bench facing the sun with your eyes closed and gently sway sideways several times for 18 minutes. Open the eyes and blink about ten times at the sun and look at some greenery. This helps short sight and is good for inflamed eyes.

Splashing: Splash plain, cold water several times on closed eyes. Rub the closed lids briskly for a minute with a clean towel. This cools the eyes and boosts blood supply.

Palming: Sit comfortably in an armchair or on a settee and relax with your eyes closed. Cover your eyes with your palm, right palm over the right eye and left over the left eye. Do not, however, press down on the eyes. With your eyes completely covered in this manner, allow your elbows to drop to your knees, which should be fairly close together. With your eyes closed thus, try to imagine blackness, which grows blacker and blacker. Palming reduces strain and relaxes the eyes and its surrounding tissues.

Swinging: Stand with your feet 12 inches apart, hands held loosely at the sides, the whole body and mind relaxed. Gently sway your body from side to side, slowly, steadily, with the heels rising alternatively but not the rest of the foot. Imagine you are the pendulum of the clock, and move just as slowly. Swinging should be done in front of a window or a picture. You will see the object moving in the opposite direction of your swing. This must be noted and encouraged. When you face one end of the window or object, blink once. This exercise has a very beneficial effect upon the eyes and nervous system.

Diet: Natural, uncooked foods are the best diet. These include fresh fruits, such as oranges, apples, grapes, peaches, plums, cherries; green vegetable like lettuce, cabbage, spinach, turnip tops; root vegetables like potatoes, turnips, carrot, onions and beetroots; nuts, dried fruits and dairy products.

Cereals are also necessary, but they should only be consumed sparingly. Genuine whole meal bread is the best and most suitable. Nans, cakes, pastries, white sugar, white bread, confectionary, tea, coffee, etc., together with meat, fish, or eggs, soon play havoc with digestion and the body.

The value of vitamin A for improving vision must be stressed. The intake of sufficient quantities of this vitamin is essential as a safeguard against or treatment of defective vision or eye disease of any kind. The best sources of this vitamin are cod liver oil, raw spinach, turnip tops, cream, cheese, butter, egg yolk, tomatoes, lettuce, carrot, cabbage, soya beans, green peas, wheat germ, fresh milk, oranges, and dates.

Yogic exercises: Trataka: In yoga, four exercises have been prescribed for strengthening weak eye muscles, relieving eyestrain and curing of eye disease. They are known as ‘ Trataka‘, which in sanskrit means "Winkles gaze at a particular point" or looking at an object with awareness. The four tratakas are: Dakshinay jatru trataka in which, with face forwards, the eyes are fixed on the tip of the right shoulder; Vamajatru trataka, in which the eyes are fixed on the tip of the left shoulder; Namikagra trataka, in which the eyes are focussed on the tip of the nose, and Bhrumadhya trataka, in which the eyes are focussed on the space between the eyebrows. These exercises should be practiced from a meditative position like padmasana or vajrasana. The gaze should be maintained for as long as you are comfortable, gradually increasing the period from 10-20 and then to 30 seconds. The eyes should be closed and rested after each exercise. Persons with acute myopia should perform the tratakas with their eyes closed.

March 17, 2010

Defaulting People Picker in aspx pages to Current User

<script type="text/javascript">
_spBodyOnLoadFunctionNames.push("fillDefaultValues");

function fillDefaultValues()
{
fillPeoplePickerWithCurrentUser('Submitted_x0020_By');
}

function fillPeoplePickerWithCurrentUser(pickerName)
{
//get the current user from the welcome menu
var currentUser = getCurrentUser();

//check to see that we've got it
if(currentUser != null)
{
//get the people pickers input div
var pp = getPickerInputElement(pickerName);
//set it to the current user if we've found it
if(pp != null)
pp.innerHTML = currentUser;
}
}

function getCurrentUser()
{
var tags = document.getElementsByTagName('a');
for (var i=0; i < tags.length; i++)
{
if(tags[i].innerText.substr(0,7) == 'Welcome')
{
return tags[i].innerText.substr(8,tags[i].innerText.length);
}
}
}

function getPickerInputElement(fieldsInternalName)
{
var result = "";
var divs = document.getElementsByTagName("DIV");
for(var i=0; i < divs.length ; i++)
{
if(divs[i].id=="WebPartWPQ2")
{
var tds = divs[i].getElementsByTagName("TD");
for(var j=0; j < tds.length; j++)
{
var cellHTML = tds[j].innerHTML;
if(cellHTML.indexOf('FieldInternalName="' + fieldsInternalName + '"') >= 0)
{
var innerDivs = tds[j].getElementsByTagName("DIV");
for(var k=0; k < innerDivs .length; k++)
{
if(innerDivs[k].id.indexOf("UserField_upLevelDiv") > 0)
{
result = innerDivs[k];
break;
}
}
}
}
}
}
return result;
}
</script>

Defaulting a SPFieldLink like All Day Event in Calender

Use a Console Applicationa and run this.

// Don’t forget this
using System.Reflection;
...
using(SPSite site =
new SPSite("http://yoursite"))
{
using(SPWeb web = site.OpenWeb())
{
SPList list = web.Lists["Calendar"];
SPContentType ct = list.ContentTypes["Event"];
SPFieldLink fieldLink = ct.FieldLinks["All Day Event"];
// Now comes the magic
Type type = typeof(SPFieldLink);
PropertyInfo pi = type.GetProperty("Default", BindingFlags.NonPublic | BindingFlags.Instance);
pi.SetValue(fieldLink, "1", null);
ct.Update();
}
}

March 12, 2010

SharePoint_Tips_Utility_Pack

http://www.codeplex.com/spstipsUtilityPack

For:

1. Look Up defalut Value
2. Show/Hide in forms
3. etc etc in managing Doc Library and Lists

March 05, 2010

Content Types in Sharepoint

1. One Content Type - One Metadata
2. A Document in a Doc Library can be associated to any number of the Content Types we desire.
3. Site Content Types are like Master Page/ Template which will be used in the Site.
4. Once a Doc Lib is associated to the Content Type, The Coulmns in that Content Type will now behave as Local version of that Doc Library.
5. You can Override the Values, Defaults, Req, Optional etc.
6. Limitation is if we want to attach two Content Types to One Doc Library and want the Column to behave differently in either Content Type, we cannot do that Coz it became a Local Version but in both Content Types.
7. If we want the Site Column to behave differently then a Separate Doc Library should be maintained.

March 03, 2010

Dynamic Redirect for a User

FormsAuthentication.RedirectFromLoginPage(txtUserName.Text.Trim(), false);
string strUserUrl = "";
SPSecurity.RunWithElevatedPrivileges(delegate
{
SPSite oSite = SPContext.Current.Site;
SPWebCollection collWebs = oSite.OpenWeb().GetSubwebsForCurrentUser();
foreach (SPWeb oWebsite in collWebs)
{
SPUserCollection collUsers = oWebsite.AllUsers;
foreach (SPUser oUser in collUsers)
{
if (oUser.LoginName.ToUpper() == txtUserName.Text.Trim().ToUpper())
{
strUserUrl = oWebsite.ServerRelativeUrl.ToString();
}
}

oWebsite.Dispose();
}
});

Response.Redirect("http://portal/"+strUserUrl,true);

March 02, 2010

Backup - Restore - STSADM - SharePoint Site

Backups are useful when moving from one Environment to another.
It will bring all the Data,Users,Permissions etc.

1. Run-->Cmd --> cd C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\12\BIN
2. stsadm -o backup -filename TestNameWithDate.dat -url http://WorkingURL
3. stsadm -o restore -filename TestNameWithDate.dat -url http://TargetURL -overwrite
4. Usually all Safe Controls will come in Web.Config but if something is breaking, check the Web.Config for safe controls.
5. If Content Types are not visible, Refresh/Restart the Application Pool and Site

Different Ways:

1. From Server : stsadm -o backup -filename TestNameWithDate.dat -url http://SiteURL
2. From SharePoint Designer 2007 (Recommended)
Steps:
1. Open the site in SharePoint Designer
2. Go to the site which you want to take BackUp
3. Site  Administartion  BackUp Website  ok  Save to your desktop location or anywhere
4. It will generate a .CMP file and that’s our backup which we can restore in the same way.
3. From the Site itself.
Steps:
1. Go to any site.
2. Make sure you are inside the site.
3. Now, Go to SiteActions  SiteSettings  Modify All Site Settings
4. Once you are here, In the browser URL, instead of settings.aspx access savetmpl.aspx
5. This will give you to save site as a Template(.stp file saved in site galleries of the root level site)

Custom Permission Levels - For a Normal restricted User

First Check the Site Permissions:
1. View Usage Data - View reports on Web site usage.
2. Browse Directories - Enumerate files and folders in a Web site using SharePoint Designer and Web DAV interfaces.
3. View Pages - View pages in a Web site.
4. Enumerate Permissions - Enumerate permissions on the Web site, list, folder, document, or list item.
5. Browse User Information - View information about users of the Web site.
6. Use Remote Interfaces - Use SOAP, Web DAV, or SharePoint Designer interfaces to access the Web site.
7. Use Client Integration Features - Use features which launch client applications. Without this permission, users will have to work on documents locally and upload their changes.
8. Open - Allows users to open a Web site, list, or folder in order to access items inside that container.
9. Edit Personal User Information - Allows a user to change his or her own user information, such as adding a picture.
List Permissions:
1. Add Items - Add items to lists, add documents to document libraries, and add Web discussion comments.
2. Delete Items - Delete items from a list, documents from a document library, and Web discussion comments in documents.
3. View Items - View items in lists, documents in document libraries, and view Web discussion comments.
4. Open Items - View the source of documents with server-side file handlers.
5. View Versions - View past versions of a list item or document.
6. Delete Versions - Delete past versions of a list item or document.
7. View Application Pages - View forms, views, and application pages. Enumerate lists.
Notes:
1. Modify Shared Web Part will come when user has edit access.
2. Access denied can come when he doesn't have View Application Pages Permission.
3. Delete will show up but when clicked acces denied will come, this is due to the user doesn't have delete versions, view versions permission when versioning has been enabled.

February 26, 2010

Sharepoint Scope Rule for Folder or Particlular List

First Grasp the URL in Content Source where you ran the Crawl.

From Central Admin:

1. Create the Scope and add folder rule.
2. In folder rule..The URL should be
CrawlURL/Documents/FolderName.
Instead of CrawlURL/Documents/AllItems.apsx
3. For List CrawlURL/Lists/ListName
4. You can see item count, but total will be reflected upon updating the scope.
5. Start Update now [No Need to Re-Crawl]
6. The Total will be now same as Item Count.
7. If wanted, In Search core Results..set this scope for limiting results and thats all.

From Site Level
1. Create the Scope and add folder rule.
2. In folder rule..The URL should be
CrawlURL/Documents/FolderName.
Instead of CrawlURL/Documents/AllItems.apsx
3. For List CrawlURL/Lists/ListName
4. You will see item count = 0, Total=0
5. Start Update now [No Need to Re-Crawl]
6. Still Item Count = 0, Total =0 but in Central Admin, You will see Item count = Count and Total = error
7. If wanted, In Search core Results..set this scope for limiting results and thats all.

Note: If searh results are not coming up correctly, Stop Start the Application Pool of Both Application and SSP

Sharepoint Designer Workflow LookUp Not Showing all the fields

When First Creating the Column, make it a single valued , not multiple values. It will show up in the Workflow Lokup. Deploy the Workflow to the list with Desired Logic. Then Change the Column to Multiple Values if needed and Test The Workflow.

February 22, 2010

Hide Site Actions for Normal Users

<SharePoint:SPSecurityTrimmedControl ID = "spstcSiteActions" runat = "server" PermissionsString = "ManageWeb" >
<span class="siteActionMenu">
<PublishingSiteAction:SiteActionMenu runat="server"/>
</span>
</SharePoint:SPSecurityTrimmedControl>

February 11, 2010

Open A Document in new Window from Document Library

If you want only documents in one document library to open to new windows, you can edit the document library in SharePoint Designer.

1. Open the site in SharePoint Designer and then open the document library allitems.aspx.

2. Right-click the document library web part and select “Convert to XSLT data view”.

3. Search for "Onlink" and you will see this tag “<xsl:otherwise ><A onfocus="OnLink(this)" HREF="{@FileRef}"….. </xsl:otherwise>”, .....add “target="_blank"” in <A> tag.

After this, the documents will be opened in a new window.

SonarQube with Jenkins Setup using Docker Images

https://funnelgarden.com/sonarqube-jenkins-docker/  https://medium.com/@hakdogan/an-end-to-end-tutorial-to-continuous-integration-and-con...