Thursday, December 15, 2011

Set/Update Content Type of new upload file in document library

using (SPSite site = new SPSite(SiteSubSite))
{
using (SPWeb web = site.OpenWeb())
{
web.AllowUnsafeUpdates = true;
//Create file Stream object using save local file
FileStream fstream = File.OpenRead(sourceFilePath);
byte[] content = new byte[fstream.Length];
fstream.Read(content, 0, (int)fstream.Length);
fstream.Close();

SPFile file = web.Files.Add(targetDocumentLibraryPath, content, true);

SPContentType spPdf = file.Item.ParentList.ContentTypes[ContentType.Name.ToString()];

file.Item["ContentTypeId"] = spPdf.Id;
file.Item["Content Type"] = spPdf.Name;
file.Item.SystemUpdate();
file.Update();

}
}

Error: "Cannot open database "WSS_Content_...." requested by the login. The login failed. Login failed for user ... "

Today I am converting word to PDF file using Word Automation Service, its throw error like "Cannot open database "WSS_Content_...." requested by the login. The login failed. Login failed for user ... "

Solution :

I have open IIS manager and click on the Application pool. Selected respected site's pool and apply valid user authentication over there. After reset IIS and checked my feature.

Its Working...

Enjoy...

Sunday, December 11, 2011

Enable Riboon Button for specific list and single item selection


<CommandUIHandlers>
<CommandUIHandler Command="ListDocumentMerge_Test_Button" CommandAction="~site/_layouts/ListDocumentMerge/DocumentMerge.aspx?List={ListId}&ID={SelectedItemId}"
EnabledScript="javascript:function singleEnable() {
var items = SP.ListOperation.Selection.getSelectedItems();
var ci = CountDictionary(items);
var listId = SP.ListOperation.Selection.getSelectedList();
if (ci == 1 && listId == '{B8701B6B-8CB7-4105-852F-4C685F580A63}')
{ return true; }
return false; }
singleEnable();" />
</CommandUIHandlers>

Programmatically add Custom action in SharePoint 2010

If you need to create a ribbon button that applies to a specific list in a farm deployment scenario you must write some code in a feature event receiver to create an SPUserCustomAction class as so:
SPList list = web.Lists["SomeList"];SPUserCustomAction action = list.UserCustomActions.Add();action.Title = "Do Something";action.Description = "Sample ribbon button";action.ImageUrl = "/_layouts/images/centraladmin_backupandrestore_granularbackup_32x32.png";action.Location = "CommandUI.Ribbon.ListView";action.Sequence = 0;action.Url = "javascript:DoAction();";action.CommandUIExtension =@"<CommandUIExtension xmlns='http://schemas.microsoft.com/sharepoint/'> <CommandUIDefinitions> <CommandUIDefinition Location='Ribbon.Documents.Manage.Controls._children'> <Button Id='Sample.DoSomething.Button' Command='Sample.DoSomething' Image32by32='/_layouts/images/centraladmin_backupandrestore_granularbackup_32x32.png' Image16by16='/_layouts/images/centraladmin_backupandrestore_granularbackup_32x32.png' Sequence='0' LabelText='Do Something' Description='Sample ribbon button' TemplateAlias='o1' /> </CommandUIDefinition> </CommandUIDefinitions> <CommandUIHandlers> <CommandUIHandler Command='Sample.DoSomething' CommandAction='javascript:DoAction();' EnabledScript='javascript:EnableDoAction();'/> </CommandUIHandlers></CommandUIExtension>";
action.Update();

Hide Ribbon in SharePoint 2010

f you have a to disable / hide the SharePoint 2010 ribbon in list forms (such as New / Edit / Display forms), one of the easiest ways is to do it through CSS.

As SharePoint 2010 provides great flexibility with list forms, we can easily modify whatever is required in a particular form for a particular list.

Click "Edit List" icon in the ribbon and it will fire up SharePoint Designer. Open the form where the ribbon needs to be hidden, right click it and choose "Edit File in Avdanced Mode".

The below is div in which the ribbon resides.
<div id=”s4-ribbonrow” class=”s4-pr s4-ribbonrowhidetitle”>
...
</div>
Now to hide the ribbon, add this to the page.
<style type="text/css">
#s4-ribbonrow{ display:none; }
</style>

Custom Ribbon Menu in SharePoint 2010

Feature.xml

<Feature xmlns="http://schemas.microsoft.com/sharepoint/"
Id="031FE880-77CF-4A84-8C5C-7324229EDC6D"
Title="List Document Merge Custom Ribbon Button"
Scope="Web"
Description="List Document Merge Custom Ribbon Button"
ImageUrl="DOC32.GIF">

<ElementManifests>

<ElementManifest Location="RibbonButton.xml"/>

</ElementManifests>

</Feature>

RibbonButton.xml

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

<CustomAction
Id="ListDocumentMergeCustomRibbonButton"
RegistrationId="101"
RegistrationType="List"
Location="CommandUI.Ribbon"
Sequence="5"
Title="Merge Documents"
Rights="ViewListItems" xmlns="http://schemas.microsoft.com/sharepoint/"
>
<CommandUIExtension>
<CommandUIDefinitions>
<CommandUIDefinition Location="Ribbon.Documents.Manage.Controls._children">
<Button
Id="Ribbon.Documents.New.ListDocumentButton"
Alt="Merge Documents"
Sequence="5"
Command="ListDocumentMerge_Test_Button"
Image32by32="/_layouts/images/DOC32.GIF"
Image16by16="/_layouts/images/DOC32.GIF"
LabelText="Merge Documents"
TemplateAlias="o1" />
</CommandUIDefinition>
</CommandUIDefinitions>

<CommandUIHandlers>
<CommandUIHandler
Command="ListDocumentMerge_Test_Button"
CommandAction="~site/_layouts/ListDocumentMerge/DocumentMerge.aspx?List={ListId}&ID={SelectedItemId}" />
</CommandUIHandlers>

</CommandUIExtension>
</CustomAction>

</Elements>

Wednesday, December 7, 2011

The type ‘System.IO.Packaging.Package’ is defined in an assembly that is not referenced. You must add a reference to assembly ‘WindowsBase’

While I was working with the Open Office XML SDK 2.0, after I added the reference to the DocumentFormat.OpenXml assembly and tried to build the application I ran into this error message.

The type ‘System.IO.Packaging.Package’ is defined in an assembly that is not referenced. You must add a reference to assembly ‘WindowsBase, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35′

Turns out, all you need to do to fix it is to just add another reference to WindowsBase assembly that is found in the .NET Tab.

Monday, October 17, 2011

Get User Login Name from SP User/Group Column in Sharepoint

SPFieldUser field = item.Fields["Approver"] as SPFieldUser;

if (field != null)
{
SPFieldUserValue fieldValue = field.GetFieldValue(item["Approver"].ToString()) as SPFieldUserValue;
if (fieldValue != null)
{
string str= fieldValue.User.LoginName;
}

}

Saturday, October 1, 2011

How to display all versions in a SharePoint list view page

http://stefan-stanev-sharepoint-blog.blogspot.com/2009/08/how-to-display-all-versions-in.html

Programmatically get custom list and document library Version History

private void GetVersionHistory()
{
try
{
using (SPSite site = new SPSite(SPContext.Current.Site.Url.ToString()))
{
using (Microsoft.SharePoint.SPWeb web = site.OpenWeb())
{
Guid id = new Guid(this.Request.QueryString["ListId"].ToString());
SPList objList = web.Lists[id];
DataTable dtPhoto = new DataTable("dtPhoto");
site.AllowUnsafeUpdates = true;
web.AllowUnsafeUpdates = true;

if (objList.BaseType == SPBaseType.DocumentLibrary)
{
char[] sep = { '' };
char[] sepHash = { '#' };
SPListItem item = objList.GetItemById(Convert.ToInt32( this.Request.QueryString["ItemId"].ToString()));
string strname = item["Name"].ToString();
foreach (SPFile file in objList.RootFolder.Files)
{
if (file.Name == strname)
{
dtPhoto.Columns.Add("Version");
dtPhoto.Columns.Add("Modified");

dtPhoto.Columns.Add("Modified By");
dtPhoto.Columns.Add("Comments");
DataRow dtrow;

dtrow = dtPhoto.NewRow();
dtrow["Version"] = file.UIVersionLabel;
dtrow["Modified"] = item["Modified"].ToString();

string[] str1 = item["Modified By"].ToString().ToString().Split(sepHash);

dtrow["Modified By"] = ( str1[1].ToString());
dtrow["Comments"] = file.CheckInComment;

dtPhoto.Rows.Add(dtrow);

SPFileVersionCollection filecollection = file.Versions;
if (filecollection.Count > 0)
{



foreach (SPFileVersion v in filecollection)
{

dtrow = dtPhoto.NewRow();
dtrow["Version"] = v.VersionLabel;
dtrow["Modified"] = v.Created;
string[] str = v.CreatedBy.ToString().Split(sep);

dtrow["Modified By"] =GetUserName( str[1].ToString());
dtrow["Comments"] = v.CheckInComment;

dtPhoto.Rows.Add(dtrow);

}
if (dtPhoto != null && dtPhoto.Rows.Count > 0)
{
gvVersion.DataSource = dtPhoto;
gvVersion.DataBind();


}
else
{
trversion.Visible = false;
gvVersion.Visible = false;

}
return;
}
}
}
}
else
{

#region


SPQuery objQuery = new SPQuery();
objQuery.Query = "<Where><Eq><FieldRef Name=\"ID\"/><Value Type=\"Counter\">" + this.Request.QueryString["ItemId"].ToString() + "</Value></Eq></Where>";
SPListItemCollection objItemColl = objList.GetItems(objQuery);


foreach (SPListItem objItem in objItemColl)
{
SPListItemVersionCollection objVerisionColl = objItem.Versions;
if (objVerisionColl.Count > 0)
{
dtPhoto.Columns.Add("Version");
dtPhoto.Columns.Add("Modified");
dtPhoto.Columns.Add("Modified By");
dtPhoto.Columns.Add("Comments");

DataRow dtrow;


//Navigate to each version of the ListItem
foreach (SPListItemVersion objVersion in objVerisionColl)
{
SPListItem objLstItm = objVersion.ListItem;
char[] sep = { ',' };
char[] sep1 = { ';' };
dtrow = dtPhoto.NewRow();
dtrow["Version"] = objVersion.VersionLabel;
dtrow["Modified"] = objLstItm.Versions.GetVersionFromLabel(objVersion.VersionLabel)["Modified"].ToString();
string[] strtest = objLstItm.Versions.GetVersionFromLabel(objVersion.VersionLabel)["Modified By"].ToString().Split(sep);
string[] str11 = strtest[0].Split(sep1);
string s = str11[1].ToString().Replace("#", "");
dtrow["Modified By"] = s;
dtrow["Comments"] = "";

dtPhoto.Rows.Add(dtrow);
}
}
}
#endregion

}


if (dtPhoto != null && dtPhoto.Rows.Count > 0)
{
gvVersion.DataSource = dtPhoto;
gvVersion.DataBind();


}
else
{
trversion.Visible = false;
gvVersion.Visible = false;

}



}
}
}
catch (Exception)
{


}
}

Thursday, July 14, 2011

Show username instead of "System Account" in SharePoint

Many times when you login to a SharePoint site you will see at the right hand side top corner "Welcome System Account" instead of your username. Sometimes we need to really get rid of this system account and display proper username.
Here are the two ways which could help you accomplish this task:
Solution one :
· Go to Central Administration / Application Management.
· Click Policy for Web Application.
· Select your web app and click your account in the list.
· In the Edit Users page, clear the Account operates as System checkbox.
· That should fix this particular problem.
Solution two:
· Go to Central Administration / Operations.
· Select Service Accounts
. Select your web application
· Change the application pool identity for your Web application

Sunday, June 12, 2011

SharePoint 2010 - i:0#.w|domain\username issue in User

Hi Friend,

Yesterday When I fetched user name through object model, I am getting user name like i:0#.w|domain\username. Because It is possible in claim based authentication in sharepoint.

To Solve this problem, decode the account name.

using Microsoft.SharePoint.Administration.Claims;
SPClaimProviderManager mgr = SPClaimProviderManager.Local;
string strDecodedLoginName = "";


strDecodedLoginName = mgr.DecodeClaim(strLoginName).Value;

Wednesday, June 8, 2011

The underlying connection was closed: Could not establish trust relationship for the SSL/TLS secure channel.System.Web.Services in sharepoint 2010

Hi Guys,

Today I am connect to SharePoint web service from external machine but I am getting error "The underlying connection was closed: Could not establish trust relationship for the SSL/TLS secure channel.System.Web.Services ".

I searched on Google and found below solution.

//Trust all certificates
System.Net.ServicePointManager.ServerCertificateValidationCallback =
((sender, certificate, chain, sslPolicyErrors) => true);



Tuesday, May 31, 2011

SMTP Detail From Central Administration

Hi Friends,

You will get SMTP configuration detail from central admin which is useful in webpart or workflow for email trigger.

using Microsoft.SharePoint.Administration;

string smtpServer = SPAdministrationWebApplication.Local.OutboundMailServiceInstance.Server.Address;

string smtpFrom = SPAdministrationWebApplication.Local.OutboundMailSenderAddress;

Friday, March 25, 2011

Custom workflow action appearing in action list but not showing Workflow UI

I created for SharePoint Designer 2010 in Visual Studio 2010. My custom action appears in Designer in the action list just like it's supposed to, but when I click on it it does not appear in the workflow. I don't get any error messages throughout the development process, and Designer seems to have no trouble with knowing the action is there and there is an assembly associated with it.

Solution :
I have checked application web.config file and found that <authorizedType Assembly="DocToPDFActivity, Version=1.0.0.0, Culture=neutral, PublicKeyToken=2478de059b6051f4" Namespace="DocToPDFActivity" TypeName="*" Authorized="True" /> is configure in it.

So Just i have added it and reset IIS.

After I have checked Workflow action UI and it appears.

Cheers.

Friday, March 4, 2011

Word To PDF - Sharepoint 2010

http://msdn.microsoft.com/en-us/library/ff181518.aspx

http://www.microsoft.com/resources/msdn/en-us/office/media/video/office.html?cid=office-video&VideoID=e784efe4-bf2a-4777-b15f-b5a59cecfe64&from=mscomoffice

Error occurred in deployment step 'Recycle IIS Application Pool': Cannot connect to the SharePoint site. Error occurs while deploying SharePoint solut

In Visual Studio 2010 while deploying SharePoint solutions, sometime we see this error
“Error occurred in deployment step 'Recycle IIS Application Pool': Cannot connect to the SharePoint site. If you moved this project to a new computer or if the URL of the SharePoint site has changed since you created the project, update the Site URL property of the project.”

This is because we forgot to mention the Site URL where we are going to deploy this solution. After specifying site URL, deployment went well.



Site URL will be your SharePoint site i.e. http://MOSS:2000.

Sunday, February 13, 2011

How To Write Exception error In Sharepoint Log File

Add Microsoft.Office.Server dll in your project, you can find this dll under “\Common Files\Microsoft Shared\Web Server Extensions\12\ISAPI\”.

The log files are found under \Common Files\Microsoft Shared\Web Server Extensions\12\Log\. Following line of code is used to write exception in sharepoint default log file.

Microsoft.Office.Server.Diagnostic.PortalLog.LogString(“Exception – {0} – {1} – {2}”,”Log Message”,ex.Message,ex.StackTrace);

Wednesday, February 9, 2011

Disable SharePoint DataTime Control Event

((TextBox)(dtduedate.Controls[0])).Attributes.Add("onKeyPress", "DisbleEnterKey();");

Saturday, February 5, 2011

SharePoint DateTime control returning current date when no date is selected

In WSS 3.0/4.0, I am using sharePoint DateTime control. I retrieve the date selected by the user using SelectedDate property of the sharePoint DateTime control.

The issue is that even when the user has not selected any date in the sharePoint DateTime control, the SelectedDate property of the sharePoint DateTime control returns current date.

Solution :

if (dt.IsDateEmpty)
{
objdt = DBNull.Value;
}
else
{
objdt = dt.SelectedDate.ToString();
}