Showing posts with label SharePoint. Show all posts
Showing posts with label SharePoint. Show all posts

December 3, 2019

Project Management SharePoint Template

Hello All,

I was looking for a free template for Project Management in SharePoint on-prem. or online, After searching a lot found one good template 'BrightWork'..

It provides
  1. PLAN AND MANAGE WITH STANDARDIZED TEMPLATE.
  2. SHARE PROGRESS WITH AUTOMATED REPORTS
  3. COLLABORATE WITH A TEAM-FOCUSED PROJECT SITE

Its very easy to use and can be installed in SharePoint On-Prem. or online environment.

Thanks BrightWork..

May 3, 2016

How to do with SharePoint Library using Powershell

Hi,
 
I am working on PowerShell scripts to automate deployment for one of client,
 
Here is post :: How to do with SharePoint Library using Powershell,


# Create Document Library

# Add SharePoint Snapin to PowerShell          
if((Get-PSSnapin | Where {$_.Name -eq "Microsoft.SharePoint.PowerShell"}) -eq $null) {          
  Add-PSSnapin "Microsoft.SharePoint.PowerShell"
}

function CreateLibrary
{
    param ($LibName)
    try
    {
        $spListCollection  = $OpenWeb.Lists 
        $spLibrary  = $spListCollection.TryGetList($LibName)

        if($spLibrary -ne $null) {
            Write-Host  -f Yellow "Library $LibraryName already exists in the site"
        }
        else
        {      
            $spListCollection.Add($LibName, "", $listTemplate)
            $spLibrary  = $OpenWeb.GetList($OpenWeb.ServerRelativeUrl+"/"+$LibName)
            Write-Host -f Green "Created Document Library $LibName"
        }
    }
    catch [System.Exception]
    {
 write-host -f red "Not set Likes Setting on " $_.Exception.ToString()
    }
}

$SiteURL = Read-Host -Prompt 'Enter Root Site URL and / @ end'
$OpenWeb = Get-SPWeb $SiteURL
$listTemplate = [Microsoft.SharePoint.SPListTemplateType]::DocumentLibrary
CreateLibrary -LibName "Department"

#enable Content Types

$spLibrary.ContentTypesEnabled = $true
$spLibrary.Update()

#Add Content Type

$ctype = "Report Data Source"
$ctToAdd = $rootSite.ContentTypes[$ctype]
$ct = $spLibrary.ContentTypes.Add($ctToAdd)

#Enable Versioning

$spLibrary.EnableVersioning = $true
$spLibrary.EnableMinorVersions = $false
$spLibrary.Update();

# Enable Versioning with Limit

$spLibrary.EnableVersioning = $true
$spLibrary.EnableMinorVersions = $false
$spLibrary.MajorVersionLimit = 3
$spLibrary.Update();

#Order Columns

$FieldOrder = New-Object System.Collections.Specialized.StringCollection
$FieldOrder.Add("ContentType")
$FieldOrder.Add("FileLeafRef")
$FieldOrder.Add("Title")
$FieldOrder.Add("CategoryDescription")
foreach ($ctype in $spLibrary.ContentTypes)
{
      if($ctype.Name -ne "Folder")
      {
           $ctype.FieldLinks.Reorder($FieldOrder);
           $ctype.Update($false);
     }
}

#Enable Moderation and Draft Version

$spLibrary.EnableModeration = $true
$spLibrary.DraftVersionVisibility = 2
$spLibrary.Update();

# Enable Rating Settings

$assembly=[System.Reflection.Assembly]::Load("Microsoft.SharePoint.Portal, Version=15.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c")
$reputationHelper =$assembly.GetType("Microsoft.SharePoint.Portal.ReputationHelper");
$bindings = @("EnableReputation", "NonPublic", "Static");
[System.Reflection.BindingFlags]$flags = [System.Reflection.BindingFlags]::Static -bor [System.Reflection.BindingFlags]::NonPublic;
$methodInfo = $reputationHelper.GetMethod("EnableReputation", $flags);
$values = @($spLibrary, "Likes", $false);
$methodInfo.Invoke($null, @($values));

# Create View

$viewTitle = "Dashboard_User" #Title property
$viewFields = New-Object System.Collections.Specialized.StringCollection
$viewFields.Add("DocIcon") > $null
$viewFields.Add("LinkFilename") > $null
$viewFields.Add("CategoryDescription") > $null
$viewFields.Add("BIKeywords") > $null
$viewFields.Add("LikesCount") > $null
$viewQuery = ""
$viewRowLimit = 5
$viewPaged = $true
$viewDefaultView = $false

$newview = $spLibrary.Views.Add($viewTitle, $viewFields, $viewQuery, $viewRowLimit, $viewPaged, $viewDefaultView)
 

March 29, 2016

Create SharePoint Web Part Page using PowerShell

Hi,
 
I am working on PowerShell scripts to automate deployment for one of client,
 
Here is post :: Create SharePoint Web Part Page using PowerShell,


# Add SharePoint Snapin to PowerShell          
if((Get-PSSnapin | Where {$_.Name -eq "Microsoft.SharePoint.PowerShell"}) -eq $null) {          
  Add-PSSnapin "Microsoft.SharePoint.PowerShell"
}


#function to create web part page in Site Pages
function CreateBlankWebpartPage          
 
{
    Param($WebPartPageName)               
    try
    {    
        $pageLayout = 1  
        $spListCollection  = $OpenWeb.Lists 
        $spLibrary  = $spListCollection.TryGetList("Site Pages")       
        $xml = "" + $spLibrary.ID + "NewWebPageNewWebPartPage" + $pageLayout + "true" + $WebPartPageName + ""
        $OpenWeb.ProcessBatchData($xml)
        foreach($listItem in $spLibrary.Items)
        {
            if($($listitem.URL).Contains("$WebPartPageName" + ".aspx"))
            {
                $myListItem = $listItem
                break;
            }
        }
        $pageUrl =  $($myListItem.URL)
        Write-Host -f Green "New page is Created with Url - $pageUrl"
    }
    catch [System.Exception]
    {
        write-host -f red $_.Exception.ToString()
    }
}
 
 
$SiteURL = Read-Host -Prompt 'Enter Root Site URL and / @ end'
 
$OpenWeb = Get-SPWeb $SiteURL
 
CreateBlankWebpartPage -WebPartPageName "My Favorites"
CreateBlankWebpartPage -WebPartPageName "Pending Approval"
CreateBlankWebpartPage -WebPartPageName "My Tasks"
CreateBlankWebpartPage -WebPartPageName "My Reports"

SharePoint Left Navigation Using PowerShell

Hi,
 
I am working on PowerShell scripts to automate deployment for one of client,
 
Here is post :: Creating SharePoint Left Navigation using PowerShell,

 
First step will be creating XML File as below,
 
<?xml version="1.0" encoding="utf-8"?>
<Navigation>
  <Headings>
    <Heading Title="Heading1" Url="" Description=""  Permission="domain\UserGroup">
      <NavLink Title="HeadNav1" Url"/>
      <NavLink Title="HeadNav2" Url=""/> 
    </Heading>
    <Heading Title="Heading2" Url="" Description="" Permission="domain\UserGroup" >
      <NavLink Title="HeadNav3" Url=""/>
      <NavLink Title="HeadNav4" Url=""/>
    </Heading>
    <Heading Title="Heading3" Url="" Description="" Permission="domain\UserGroup" >
    </Heading>
  </Headings>
</Navigation>
 

Save the xml file, now time for PowerShell script to read the xml and build the left navigation.
 
PowerShell script will first clear the existing Left Navigation and then Create New left Navigation with
 
  1. Heading
  2. NavLink Under Heading
  3. Description for Heading
  4. URL link for Heading and NavLink
  5. Permission (Target Audience) for Heading

# Add SharePoint Snapin to PowerShell          
if((Get-PSSnapin | Where {$_.Name -eq "Microsoft.SharePoint.PowerShell"}) -eq $null) {          
  Add-PSSnapin "Microsoft.SharePoint.PowerShell"
}

function LeftNavBar{
 
    $qlNav = $OpenWeb.Navigation.QuickLaunch
 
    #Get XML File
    $xmlFilePath = "$PSScriptRoot\.xml"
    $xmlFile = [xml](Get-Content($xmlFilePath))
    $oldWebUrl = $OpenWeb.Url
    $currentLinks = @()
 
    #Clear Quick Launch links
    $qlNav | ForEach-Object {
        $currentLinks = $currentLinks + $_.Id
    }
    $currentLinks | ForEach-Object {
        $currentNode = $OpenWeb.Navigation.GetNodeById($_)
        write-host -f Yellow "Deleting" $currentNode.Title "and all child navigation links..."
        $qlNav.Delete($currentNode)
    }
 
    #Create Quick Launch Links
    $xmlFile.Navigation.Headings.Heading | ForEach-Object {
        $headingNode = New-Object Microsoft.SharePoint.Navigation.SPNavigationNode($_.Title, $_.Url)
        #$headingNode.Properties["Description"] = $_.Description
        #$headingNode.Update();
        write-host -f Green "Creating Heading:" $_.Title
        $heading = $qlNav.AddAsLast($headingNode)
        $heading.Properties["Audience"] = $_.Permission
        $heading.Update();
      
        $_.NavLink | ForEach-Object {
            if($_.Title -ne $null) {
            $linkNode = New-Object Microsoft.SharePoint.Navigation.SPNavigationNode($_.Title, $_.Url)
            write-host -f Green "Creating Navigation Link:" $_.Title
            $link = $heading.Children.AddAsLast($linkNode)
            }
        }
    }
  
 
    $OpenWeb.Dispose()
}


$SiteURL = Read-Host -Prompt 'Enter Root Site URL and / @ end'
 
$OpenWeb = Get-SPWeb $SiteURL

LeftNavBar

SharePoint Site Column Using Powershell

Hi,
 
I am working on PowerShell scripts to automate deployment for one of client,
 
Here is first post :: Create Site Columns using PowerShell,
 

# Add SharePoint Snapin to PowerShell          
if((Get-PSSnapin | Where {$_.Name -eq "Microsoft.SharePoint.PowerShell"}) -eq $null) {          
  Add-PSSnapin "Microsoft.SharePoint.PowerShell"
}
 
#Create Multi Select Lookup Column
function CreateCategory
{
    param ($sSiteCollectionUrl)  
    try
    {
        $web = Get-SPWeb $SiteURL
      
        #Configuration
        $lookupFieldWebGuid=$web.ID
        $lookupList = $web.Lists.TryGetList("CategoryMaster")
        $lookupListGuid = $lookupList.ID
        $fieldDisplayName="Category"
        $fieldInternalName="BICategory"
        $sitecolGroup = "OwnColumns"
        $showField = "Title"
        $fieldDescription = "'Defines content for users' search functionality. Select multiple options, if necessary.'"
        $fieldHidden="FALSE"
        $fieldReadonly = "FALSE"
        $fieldMulti = "TRUE"
        $fieldRequired = "TRUE"
        $unlimitedLength = "FALSE"
        #End of configuration
 
        $lookupXMLString = '
        Required="' + $fieldRequired + '" EnforceUniqueValues="FALSE" WebId="' + $lookupFieldWebGuid + '" ShowField="' + $showField + '" UnlimitedLengthInDocumentLibrary="' + $unlimitedLength + '"
        Group="' + $sitecolGroup + '" Mult="' + $fieldMulti + '" Sortable="FALSE" StaticName="' + $fieldInternalName + '" List="' + $lookupListGuid + '"
        Name="' + $fieldInternalName + '" Hidden="' + $fieldHidden + '" ReadOnly="' + $fieldReadonly + '">
' 
        #Create site column from XML string
        $web.Fields.AddFieldAsXml($lookupXMLString)
        Write-Host "The Category site column has been added." -foregroundcolor green
    }
    catch [System.Exception]
    {
        write-host -f red $_.Exception.ToString()
    }
}
 
#Create Date Column
function CreateDate
{
    param ($sSiteCollectionUrl)  
    try
    {
        $web = Get-SPWeb $SiteURL 
    
        $fieldXML = '
        Name="Report_x0020_Date"
        Description="Report Publish Date"
        DisplayName="Report Date"
        StaticName="Report Date"
        Format="DateOnly"
        Group="OwnColumns"
        Hidden="FALSE"
        Required="FALSE" 
        Sealed="FALSE"
        ShowInDisplayForm="TRUE"
        ShowInEditForm="TRUE"
        ShowInListSettings="TRUE"
        ShowInNewForm="TRUE">
'  
        #Create site column from XML string
        $web.Fields.AddFieldAsXml($fieldXML)  
       
        write-Host "Added the field Report Date to the Site" -foregroundcolor green           
           
        #Disposing SPSite and SPWeb objects
        $web.Dispose()  
        
    }
    catch [System.Exception]
    {
        write-host -f red $_.Exception.ToString()
    }
}
 
#Create Choice Column
function CreateFrequency
{
    param ($sSiteCollectionUrl,$sFieldDisplayName, $sFieldInternalName, $sFieldType)  
    try
    {
        $spSite = Get-SPSite -Identity $sSiteCollectionUrl
         $spWeb = $spSite.OpenWeb()   
 
    
        #We check the field type is not null
        if($sFieldType -ne '')
        {
            $spWeb.Fields.Add($sFieldInternalName,$sFieldType,$false)
            $spChoiceField=$spWeb.Fields.GetField($sFieldInternalName)
            write-Host "Added the field Frequency to the Site" -foregroundcolor green
            $spChoiceField.Group="OwnColumns"
            $spChoiceField.Choices.Add("Weekly")
            $spChoiceField.Choices.Add("Months")
            $spChoiceField.Choices.Add("Annually")
            $spChoiceField.Choices.Add("Adhoc")
            $spChoiceField.Title=$sFieldDisplayName
            $spChoiceField.DefaultValue=""
            $spChoiceField.Required = "TRUE"
            $spChoiceField.FillInChoice=$false
            $spChoiceField.Update()
        }
                     
        #Disposing SPSite and SPWeb objects
        $spWeb.Dispose()
    }
    catch [System.Exception]
    {
        write-host -f red $_.Exception.ToString()
    }
}

#Create User Column
function CreateOwner
{
    param ($sSiteCollectionUrl)  
    try
    {
        $web = Get-SPWeb $SiteURL 
    
        $fieldXML = '
        Name="BIOwner"
        Description="Main business owner of published content."
        DisplayName="Owner"
        List="UserInfo"
        ShowField="ImnName"
        UserSelectionMode="PeopleOnly"
        UserSelectionScope="0"
        StaticName="BIOwner"
        Group="OwnColumns"
        Hidden="FALSE"
        Required="TRUE"
        Sealed="FALSE"
        ShowInDisplayForm="TRUE"
        ShowInEditForm="TRUE"
        ShowInListSettings="TRUE"
        ShowInNewForm="TRUE">
' 
        #Create site column from XML string
        $web.Fields.AddFieldAsXml($fieldXML)  
       
        write-Host "Added the field Owner to the Site" -foregroundcolor green           
           
        #Disposing SPSite and SPWeb objects
        $web.Dispose()  
        
    }
    catch [System.Exception]
    {
        write-host -f red $_.Exception.ToString()
    }
}

# get Site URL

$SiteURL = Read-Host -Prompt 'Enter Root Site URL and / @ end'
$rootWeb = Get-SPWeb $SiteURL
CreateCategory -sSiteCollectionUrl $SiteURL
CreateDate -sSiteCollectionUrl $SiteURL
CreateOwner -sSiteCollectionUrl $SiteURL
CreateFrequency -sSiteCollectionUrl $SiteURL -sFieldDisplayName "Frequency"  -sFieldInternalName "Frequency" -sFieldType "Choice"

Highlighted in blue color can be change as per your requirement.

Thanks

October 5, 2011

Enhanced SharePoint Reporting with the SharePoint Solutions Gallery

OfficeWriter previously integrated with SharePoint, getting solutions up and running used to require quite a bit of coding and configuration on your end. Not so now: they've created two free downloadable plug-and-play solutions: Excel Export Plus and Word Export Plus.

Both consist of custom solutions you install in your SharePoint site that allow you to export list data to Excel and Word.

Excel Export Pro lets you pull the contents of any SharePoint list into a pre-formatted Excel template.

Word Export Pro lets you pull the contents of any item on a SharePoint list into a pre-formatted Word template.
 
For More : Click Here

June 28, 2011

Google Chart Tools - Display Live Data on your site.

Hi, I am trying to give one POC (Proof of Concept) to my client, requirment is to show the attractive reports, without any deployment, with only ADMIN rights to one of the SharePoint 2007 site.

I searched a lot and finally decide to go with Google Chart Tools. We can fetch the data from sharepoint list view webpart and can create the chart in SharePoint page using javascript.

Here is the simple example...


and the code to get the above result is..

<div id="chart_div1"></div>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load("visualization", "1", {packages:["corechart"]});
if(typeof jQuery=="undefined"){
var jQPath="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/";
document.write("<script src='",jQPath,"jquery.js' type='text/javascript'><\/script>");
}
</script>


<script type="text/javascript">
$("document").ready(function(){
google.setOnLoadCallback(drawChart1);
});

function drawChart1() {
var arrayList=$("td.ms-gb:contains('Implemented Solution')");
var coord= new Array();
var labels= new Array();
var titles= new Array();
total=0

$.each(arrayList, function(i,e)
{
var MyIf= $(e).text();
var txt= MyIf.substring(MyIf.indexOf('(')+1,MyIf.length-1); // Extract the ‘Y' coordinates
coord[i]=txt;
total=total+(txt*1)
var txt1= MyIf.substring(MyIf.indexOf(':')+2,MyIf.indexOf("(")-1); // Extract the labels
titles[i]=txt1;
});


for(i=0;i<coord.length;i++)
{
//coord[i]=Math.round((coord[i]/total*100)*10)/10
labels[i]=titles[i]+ coord[i] //"("+coord[i]+"%)"; //update the total
}

var data = new google.visualization.DataTable();
data.addColumn('string', 'Technology Env');
data.addColumn('number', 'Application');
data.addRows(coord.length);

for(i=0;i<coord.length;i++)
{
data.setValue(i, 0, titles[i]);
data.setValue(i, 1, parseInt(coord[i]));
}

var chart1 = new google.visualization.PieChart(document.getElementById('chart_div1'));
chart1.draw(data, {width: 600, height: 440, title: 'Implemented Solution', is3D:true, vAxis: {title: '', titleTextStyle: {color: 'red'}}});
}

</script>

For more Information .... Google Chart Tools

April 29, 2011

Find Web visitor’s Location Automatically with Google APIs

This works great in the United States and has mixed results elsewhere. I’m working to see if I can change that. If your primary customer base is in the US, use this confidently. If your primary customer base is elsewhere, use in development stage only.

Google provides IP address to location translation for FREE! Whenever you use Google’s jsapi script to dynamically load a Google AJAX API, Google automatically populates google.loader.ClientLocation, which has all the juicy details about the web visitor’s location.

We can also add this to SharePoint Portal in Content Editor web part.

Script :

<DIV id='info'> </div>

<script type="text/javascript" src="http://www.google.com/jsapi?key=ABQIAAAAp04yNttlQq-7b4aZI_jL5hQYPm-xtd00hTQOC0OXpAMO40FHAxQMnH50uBbWoKVHwgpklyirDEregg"></script>
<script type="text/javascript">
if(google.loader.ClientLocation)
{
     visitor_lat = google.loader.ClientLocation.latitude;
     visitor_lon = google.loader.ClientLocation.longitude;
     visitor_city = google.loader.ClientLocation.address.city;
     visitor_region = google.loader.ClientLocation.address.region;
     visitor_country = google.loader.ClientLocation.address.country;
     visitor_countrycode = google.loader.ClientLocation.address.country_code;

     document.getElementById('info').innerHTML = '<p>Lat/Lon: ' + visitor_lat + ' / ' + visitor_lon +   '</p><p>Location: ' + visitor_city + ', ' + visitor_region + ', ' + visitor_country + ' (' + visitor_countrycode + ')</p>';
}
else
{
      document.getElementById('info').innerHTML = '<p>Whoops!</p>';
}

</script>


February 12, 2010

Include value of SharePoint’s Version Column in a word document.

Hi All,

I'm trying to work out a way to display the contents of the version column from SharePoint (i.e. the value that changes every time a file is checked in) as a field (or something similar) inside of a word document.


Finally I got solution to get the version in your document, it's a bit painful to get it working...


1) Enable versioning and content types on your document library.

2) Go into Document Library settings and select the content types you want the version to appear in.

3) After that Select Information management policies settings from the content type menu.



4) Select define a policy and click.



5) Click on the 'Enable Label' Check box

6) Do not Check the other two boxes in the Labels section.

7) In the Label Format field, enter the metadata fields in the following format:


Version : {Version} \n



8) Set the label appearance and click on preview.



9) Click at the bottom of the page.

10) Go back to the library and create a new document using the content type you have modified.

11) Save the file as a Word 2007 format.

12) Select the insert tab.

13) Select Quick Parts from the Ribbon menu and hover over document property

14) Select Label from the properties list

15) This should display the metadata defined in your label as a field in your word document. The field will update automatically when you next open the document.

16) Save the Document

October 12, 2009

Open Microsoft Application from SharePoint using Javascript

Hi All,

I have some requirments that to open MS-Word, MS- Excel , MS-PowerPoint and MS- Outllook applications from SharePoint enviornment.

This is possible by using "Process" Class in System.Diagonostics as

Process wordApp = new Process();
wordApp.StartInfo.FileName= "WinWord.exe";
wordApp.Start();


But the problem in SharePoint is the Process is started but with the Credentials of "Network Services" so the word application is not visible.
The above solution is working in any normal ASP.Net web application but not in SharePoint. So we try a work around as use javascript and create ActiveX objects and Pass the Application Name as arguments.


TheCode is as ...
For MS-Word Application.

var WordApplication=new ActiveXObject("Word.Application");
WordApplication.Visible=true; // "Visible" is in the Word Object Model
WordApplication.Documents.Add();


For MS-Excel Application.


var ExcelApplication=new ActiveXObject("Excel.Application");
ExcelApplication.Visible=true; // "Visible" is in the Excel Object Model
ExcelApplication.Workbooks.Add();


For MS-PowerPoint Application.

var PPTApplication=new ActiveXObject("Powerpoint.Application");
PPTApplication.Visible=true; // "Visible" is in the PowerPoint Object Model
PPTApplication.Presentations.Add();


For MS-OutLook Application.

var objO = new ActiveXObject('Outlook.Application');
var objNS = objO.GetNameSpace('MAPI');
var olInbox = objNS.GetDefaultFolder(6);
olInbox.Display();


Try this code in Script.


Prerequsite :


There some prerequsites for this application,
  1. The application is installed at client machine, because it will open client local application but not on servers application.
  2. There is settings for running this scripts as,
Tools > Internet Options… > choose tab Security > click button Custom level > scroll > to 'Run ActiveX controls and plug-ins' > select ‘prompt’ or ‘enable’.

October 8, 2009

Programmatically Adding, Deleting, Copying and Downloading Attachments in SPList

I developed a new functionality in our application where I worked with attachments in SharePoint Lists programmatically… It was a nice learning… Let me share my experiences with that too………… And now I seem to have found an informative stuff for my readers and an apt title too

ADDING AN ATTACHMENT TO AN ITEM IN SPLIST :

private void AddNewAttachment(int NodeID)
{
try
{
SPList myList = SPContext.Current.Web.Lists["Item List"];SPListItem myNewItem = myList.GetItemById(NodeID);
if (fileUpload.PostedFile != null && fileUpload.HasFile)
{
Stream fStream = fileUpload.PostedFile.InputStream;
byte[] contents = new byte[fStream.Length];fStream.Read(contents, 0, (int)fStream.Length);fStream.Close();fStream.Dispose();
SPAttachmentCollection attachments = myNewItem.Attachments;string fileName = Path.GetFileName(fileUpload.PostedFile.FileName);attachments.Add(fileName, contents);
myNewItem["Attached FileName"] = fileName; // store the name of the file in a column for future requirements
myNewItem.Update();
}
}
catch (Exception eAdd)
{
string errAdd = eAdd.Message;
}
}


DELETING AN ATTACHMENT FROM SPLIST :


private void DeleteAttachment(int NodeID)
{
try
{
SPList myList = SPContext.Current.Web.Lists["Item List"];
SPListItem delItem = myList.GetItemById(NodeID);
SPAttachmentCollection atCol = delItem.Attachments;
if (delItem["Attached FileName"] != null)
{
string strFileName = delItem["Attached FileName"].ToString();
delItem["Attached FileName"] = string.Empty;
atCol.Delete(strFileName);
delItem.Update();
}
}
catch (Exception eDel)
{
string errDel = eDel.Message;
}
}



DOWNLOADING THE ATTACHMENT :
Find the download link first then reedirect to another aspx page so that the response ending on the current page does not affect the functionalities on this :-

private void DownloadAttachment(int NodeID)
{
try
{
string AttachmentURL = string.Empty;
SPList myList = SPContext.Current.Web.Lists["Item List"];
SPListItem attItem = myList.GetItemById(NodeID);
if (attItem["Attached FileName"] != null)
{
AttachmentURL = “/Lists/Item%20List1/Attachments/” + NodeID.ToString() + “/” + attItem["Attached FileName"].ToString();

System.Web.HttpContext.Current.Session["FileName"] = attItem["Attached FileName"].ToString();
System.Web.HttpContext.Current.Session["Attachment"] = AttachmentURL.Trim();
}
else
{
lblReport.Text = GetMessage(110);
}
if (AttachmentURL != string.Empty)
Page.Response.Write(”");
}
catch (Exception eDwn)
{
string errDwn = eDwn.Message;
}
}
At the aspx page you need to run the code as :

if(System.Web.HttpContext.Current.Session["Attachment"] != null)
{
string strName = System.Web.HttpContext.Current.Session["FileName"].ToString();
string sbURL = System.Web.HttpContext.Current.Session["Attachment"].ToString();
System.Web.HttpResponse response;
response = System.Web.HttpContext.Current.Response;
System.Web.HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.Default;
response.AppendHeader(”Content-disposition”, “attachment; filename=” + strName);
response.AppendHeader(”Pragma”, “cache”);
response.AppendHeader(”Cache-control”, “private”);
response.Redirect(sbURL);
response.End();
}

Now set these sessions to null.


COPYING AN ATTACHMENT FROM ONE ITEM TO ANOTHER IN SPLIST :
private void CopyAttachment(int FromID, int NodeID, string AttachedFile)
{
try
{
SPList myList = SPContext.Current.Web.ParentWeb.Lists["Item List"];
SPListItem myItem = myList.GetItemById(NodeID);
SPListItem myPrevItem = myList.GetItemById(FromID);

SPAttachmentCollection attColl = myPrevItem.Attachments;

SPFile attFile = myPrevItem.ParentList.ParentWeb.GetFile(myPrevItem.Attachments.UrlPrefix + AttachedFile);
string fileRead = myPrevItem.Attachments.UrlPrefix.ToString() + AttachedFile;

StreamReader fsReader = new StreamReader(attFile.OpenBinaryStream());
Stream fStream = fsReader.BaseStream;

byte[] contents = new byte[fStream.Length];
fStream.Read(contents, 0, (int)fStream.Length);
fStream.Close();
fStream.Dispose();

myItem.Attachments.Add(AttachedFile, contents);
myItem.Update();
}
catch (Exception eCopy)
{
string errCopy = eCopy.Message;
}
}


No exact match found when adding using from different domains in SharePoint

Problem:

Either when you’re trying to add a user account from a different domain to a SharePoint site collection or using People Picker you get a “no exact match found”.

Issue:

The service account attached to the Sharepoint Web Application is used for user account verification. In the case where there is only a one-way trust between the domains, a login for the requested domain is required. For example, when you add a user from a different domain to the security list for a file, where the current login does not have permissions to the queried domain a login popup appears. Since a login dialog doesn’t appear for Sharepoint, an additional login is required.

Solution:

In a multi forest network, separate logins will have to be registered against each domain. Assuming you have a login with permissions to the domains that are found in different forests you can run the following command on the Sharepoint server to register the login password (domain:, login, password; domain, login, password):

stsadm.exe -o setproperty -url “<https://SharepointPortal>” -pn “peoplepicker-searchadforests” -pv “domain:na.aecomnet.com,na\mosssp,Password; domain:as.aecomnet.com,nas\mossspas,Password; domain:corp.aecomnet.com,aecom/mossspcorp,Password; domain:au.aecomnet.com,au\mosstest,mos5test”

September 17, 2009

How to get Image path of Type column in document library

Hi All,

Today i found one very interesting thing. I thought it may help you a lot in many cases.

I was developing webpart which functions like this.

I have document library and in that Document Library i have one column which specially identified a ContactID from other List. When i add that contact i also take the attachment and put it in that document library, so first when i get that ContactID (ID of the contact listItem), i insert a row in that document library with Contact ID in the ContactID column in that document library.

This post is not regarding this, but would be one of the scenario to explain what i am now about to tell you.

I also needed the icon with each respective documents. If the document is Docx, i needed to show the docx icon which sharepoint puts in Type column in Document Library. same goes for any files. Doc,Docx,XML,Xls,Xlsx,ppt etc.

so i wonder how sharepoint manages this, i tried to take the ListItem of the document library and tried to see that any of the Field gives the icon path or not. But no, none of the fields returns me the Icon of the path, or even none of the Field tells us that it uses which icon. I search a bit, then i found that everything is in one Field which is called "DocIcon".

So assume that you have document library called "Shared Documents".

---------------------------------------------------------------------------------------------
SPDocumentLibrary objDocLib =(SPDocumentLibrary)SPContext.Current.Web.Lists["Shared Documents"];
---------------------------------------------------------------------------------------------

Now, Lets say i am taking the First Document,SPListItem objItem = objDocLib.GetItemById(1); // Make sure you have at least one doc, otherwise this will give ErrorNow,

Check for this condition,

---------------------------------------------------------------------------------------------
if (objItem["DocIcon"] == null)
---------------------------------------------------------------------------------------------

Because if sharepoint images does not have supporting type icon for that document type, lets say any file without any extesnion, this field will return you null. so first check this. now proceed.

---------------------------------------------------------------------------------------------
string strFileType= Convert.ToString(objItem["DocIcon"]);
---------------------------------------------------------------------------------------------

This returns you the type (it returns doc,docx,ppt,xls,xlsx,xml etc). So from here you can come to know what is the type of the document.

Now, interesting part comes. you must be wondering that OK, that is fine, but where is the icon path?

Here is a trick that i found,

Check the Images Folder inside C:\Program Files\Common Files\Microsoft Shared\web server extensions\12\TEMPLATE\IMAGES.

Now Check you will find all the icons which sharepoint uses have .gif extension and all these icons have IC prefix with the extension and plus .gif at last. So have you got any hint? No??? no, problem, here we go. Check this out.

---------------------------------------------------------------------------------------------
Image picture = new Image();
if (objItem["DocIcon"] == null)
{
picture.ImageUrl = @"_layouts\Images\" + "ICgen.gif";
}
else
{
picture.ImageUrl = @"_layouts\Images\" + "IC" + objItem["DocIcon"].ToString() + ".gif";
}
---------------------------------------------------------------------------------------------

Consider picture as asp Image control, If you have noticed that if sharepoint does not have icon matching with the document type then it puts one white paper kind of icon and the name of that icon is ICgen.gif. so we have done same thing, if sharepoint does not have any supported icon for that document type, it will give objItem["DocIcon"] null. so we have also checked that and places the proper URL, and if we found that then we make combination of "IC" + objItem["DocIcon"].ToString() which is extension + ".gif" which is default extension of any images of sharepoint.That's it. your job is done.