Wednesday, July 25, 2012

SharePoint 2010 : List "Order field" is hidden

just run the below script and "order" field will be visible in the list.

[void][System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint")
Add-PSSnapin Microsoft.SharePoint.Powershell -ErrorAction SilentlyContinue
$WebAppUrl = "http://site/"

$site=new-object Microsoft.SharePoint.SPSite($WebAppUrl
foreach ($web in $site.AllWebs) 
  Write-Host      $web.Url
 
  for ($i = 0; $i -lt $webLists.Count; $i++)
  {
 
     $spList = $weg.Lists[$i] #;   # ... }
      #foreach ($spList in $web.Lists) 
      # { 
            #if ($spList.BaseTemplate -eq "GenericList" -or $spList.BaseTemplate -eq  "DocumentLibrary" )
            if ($spList.BaseTemplate -eq "GenericList")
             {
                  # Write-Host  $spList.title
                 
                  if ($web.Url -eq "http://site")
                  {
                     #Write-Host  $spList.title
                   
                      $orderField = $spList.Fields["Order"]
                        $type = $orderField.GetType()
                        $mi = $type.GetMethod("SetFieldBoolValue", [reflection.bindingflags]"nonpublic, instance")
                        $parameters = "CanToggleHidden", $true
                        $mi.Invoke($orderField, $parameters)
                       
                        if($orderField.Hidden -eq $true)
                        {
                              Write-Host  "Surya" $spList.Title
                             
                              #if($spList.title -ne "Relationships List"  -or $spList.title -ne "Web Site Menu - First Level"   -or $spList.title -ne "Variation Labels" -or $spList.title -ne "TaxonomyHiddenList" -or $spList.title  -ne "Suggested Content Browser Locations" -or $spList.title -ne "Reusable Content" -or  $spList.title -ne "Reporting Metadata" -or $spList.title -ne "Notification List" -or  $spList.title -ne "Quick Deploy Items" -or $spList.title -ne "QuickLinksList")
                              #{
                                    $orderField.Hidden = $false
                                    $orderField.Update()
                              #}
                        }

                  }
                 
             }
           
            #SPListTemplateType.GenericList
      }
}


$web.Dispose()
$site.Dispose()


SharePoint: Master Page is not updating with feature after deployment


I noticed below points while working with master page


If master page is not customized, I mean if it is not modified by SharePoint designer or any other tool


  2nd time when I am done with modifications in my feature code, I am updating a master page feature    using below powershell script

update-spsolution -identity MasterPages.wsp  -literalpath C:\Pulipati\.MasterPages.wsp  -  gacdeployment
a.    My Master page is updating properly however it is not creating a version and it is not updating the modified date as well when I run above command.  But when I open a master page I see latest code.


If master page is customized, I mean if it is modified by SharePoint designer or any other tool


  If I run powershell command it is not updating my master page. So I followed this Post and successfully updated.


<Module Name="PGCMasterPageModule" List="116" Url="_catalogs/masterpage">
  <File Path="xxxMasterPageModule\CustomMaster.master" Url="CustomMaster.master"  IgnoreIfAlreadyExists="TRUE" Type="GhostableInLibrary" />
</Module>

IgnoreIfAlreadyExists="TRUE": always make this TRUE it will not throw any error when you deploy second time.

using System.IO;

  public override void FeatureActivated(SPFeatureReceiverProperties properties)
        {
            //if you want to debug just enable this code
            // System.Diagnostics.Debugger.Break();

            SPSite currentSite = (SPSite)properties.Feature.Parent;
            SPWeb oCurrentWeb = currentSite.RootWeb;


           oCurrentWeb.MasterUrl = oCurrentWeb.ServerRelativeUrl +    "/_catalogs/masterpage/CustomMaster.master";
            oCurrentWeb.CustomMasterUrl = oCurrentWeb.ServerRelativeUrl + "/_catalogs/masterpage/CustomMaster.master";
            oCurrentWeb.Update();

//below code executes only when the file is customized (for ex: if u modify with sharepoint designer) 


       if (oFile.CustomizedPageStatus == SPCustomizedPageStatus.Customized)
            {
                
            // Here we are trying to overwrite the default.master  
            SPFile oFile = oCurrentWeb.GetFile("_catalogs/masterpage/CustomMaster.master");
            SPFolder oFolder = oCurrentWeb.Lists["Master Page Gallery"].RootFolder;
            // Check In the file  
            if (oFile.CheckOutType != SPFile.SPCheckOutType.None)
                oFile.CheckIn("auto checkin");
            // Check Out the file for edit.  
            oFile.CheckOut();
            string directory = properties.Definition.RootDirectory; // it returns 14 hive feature path
            directory += @"\PGCMasterPageModule"// my feature module name as shown in picture

            // Get the master page name from the feature properties as defined in the elements.xml 
            //  SPFeatureProperty oPropertyName = properties.Feature.Properties["CustomMaster.master"];

            // Get the file names from the specified directory matching the feature property value. 
            string[] templates = Directory.GetFiles(directory, "CustomMaster.master", System.IO.SearchOption.TopDirectoryOnly);
            // templates should have all the matching file names. In this instance it whould be only one file name. 
            string MasterPageFile = templates[0];
            FileInfo fileInfo = new FileInfo(MasterPageFile);
            byte[] byteArr = System.IO.File.ReadAllBytes(MasterPageFile);
            oFolder.Files.Add(fileInfo.Name, byteArr, true);
            oFile.Update();
            oFile.CheckIn("Check in");
            oFile.Publish("Published");
            oFile.Approve("Approved");

        }


}


Tuesday, July 24, 2012

SharePoint 2010: Powershell commands



Powershell Commands


Add-SPSolution D:\Wsps\SampleSolution.wsp

Install-SPSolution –Identity SampleSolution.wsp -GACDeployment
Install-SPSolution –Identity SampleSolution.wsp -webapplication http://site -gacdeployment -force


Update-SPSolution –Identity SampleSolution.wsp –LiteralPath d:\test.wsp –GACDeployment

uninstall-spsolution -identity SampleSolution.wsp -webapplication http://site -confirm:$false

remove-spsolution -identity SampleSolution.wsp -confirm:$false

Backup-spsite –identity http://sitename  -path D:\backup\surya\9019.bak

Restore-SPSite –identity http://sitename  -path D:\backup\surya\9019.bak –force

Mount-SPContentDatabase "MyDatabase" -DatabaseServer "MyServer" -WebApplication http://sitename

Restore-SPSite -Identity "http://spdev5:8002/"  -Path "site_05312013.bak" -DatabaseName "sitedb"  -force -verbose

#Export SharePoint List
Export-SPWeb  "http://spdev5:8005" -path "D:\\Development\surya\ResourceLibrary.cmp" -ItemUrl Resource%20Library -IncludeVersions All

#Import SharePoint List
Import-SPWeb -Identity http://spdev5:8003 -path "D:\Development\surya\ResourceLibrary.cmp"


STSADM Commands


stsadm -o provisionservice -action start -servicetype spwebservice
stsadm -o backup -url  http://sitename  filename C:\Pulipati\testbackup.bak
stsadm.exe -o import -url http://sitename -filename C:\Export.cab -includeusersecurity

stsadm -o provisionservice -action start -servicetype Microsoft.SharePoint.Administration.SPWebService -servicename WSS_Administration


Not enough information to determine a list for module. Assuming no list for this module


Its throwing error when you forgot to mention Url.  that’s what I noticed.

IgnoreIfAlreadyExists : True : It will not throw any error if already exists.
IgnoreIfAlreadyExists : False : It throws an error if already exists.

<?xml version="1.0" encoding="utf-8"?>
<Elements xmlns="http://schemas.microsoft.com/sharepoint/">
  <Module Name="MyStyles" Url="Style Library" >
    <File Path="MyStyles\Sample.txt" Url="Sample.txt"  Type="GhostableInLibrary" IgnoreIfAlreadyExists="TRUE" />
    <File Path="MyStyles\NewFolder1\Style.css" Url="NewFolder1/Style.css"  Type="GhostableInLibrary"   IgnoreIfAlreadyExists="TRUE"/>
</Module>
</Elements>


Friday, July 20, 2012

SharePoint Feature Receiver : System.InvalidCastException: Unable to cast object of type 'Microsoft.SharePoint.SPSite' to type 'Microsoft.SharePoint.SPWeb


If you trying to activate masterpage in the site collection level and if you are using below code this will thrown error

this code is referring only website not site collection
  public override void FeatureActivated(SPFeatureReceiverProperties properties)
        {
           SPWeb currentWeb = (SPWeb)properties.Feature.Parent;
            currentWeb.MasterUrl = "/_catalogs/masterpage/CustomMaster.master";
            currentWeb.CustomMasterUrl = "/_catalogs/masterpage/CustomMaster.master";
            currentWeb.Update();
        }



Error: 
Feature receiver assembly 'TestMasterPages, Version=1.0.0.0, Culture=neutral, PublicKeyToken=9c3395ff06cc524a', class 'TestMasterPages.Features.CustomMaster.CustomMasterEventReceiver', method 'FeatureActivated' for feature '0ab67b2b-2360-45f2-b26e-e33a49ceea3c' threw an exception: System.InvalidCastException: Unable to cast object of type 'Microsoft.SharePoint.SPSite' to type 'Microsoft.SharePoint.SPWeb'.   
 at TestMasterPages.Features.CustomMaster.CustomMasterEventReceiver.FeatureActivated(SPFeatureReceiverProperties properties)   
 at Microsoft.SharePoint.SPFeature.DoActivationCallout(Boolean fActivate, Boolean fForce)


Solution:




  public override void FeatureActivated(SPFeatureReceiverProperties properties)
        {
          SPSite currentSite = (SPSite)properties.Feature.Parent;
            SPWeb currentWeb = currentSite.RootWeb;
            currentWeb.MasterUrl = "/_catalogs/masterpage/CustomMaster.master";
            currentWeb.CustomMasterUrl = "/_catalogs/masterpage/CustomMaster.master";
            currentWeb.Update();
        }



Cannot convert type 'Microsoft.SharePoint.WebControls.DelegateControl' to 'System.Web.UI.IAttributeAccessor'


When you are working with master page using SharePoint designer sometimes junk data will be added to the master page as shown below. 

in my scenario junk data added to <SharePoint:DeveloperDashboard control

  <div id="DeveloperDashboard" class="ms-developerdashboard">
                     <SharePoint:DeveloperDashboard runat="server" id="ddashboard" __designer:Preview="[ DeveloperDashboard &quot;ddashboard&quot; ]" __designer:Values="&lt;P N='ID' T='ddashboard' /&gt;&lt;P N='Page' ID='1' /&gt;&lt;P N='TemplateControl' ID='2' /&gt;&lt;P N='AppRelativeTemplateSourceDirectory' R='-1' /&gt;"/>
              </div>


Error:


http://server/sites/sitecol1/_catalogs/masterpage/CustomMaster.master(502): error CS0030: Cannot convert type 'Microsoft.SharePoint.WebControls.DeveloperDashboard' to 'System.Web.UI.IAttributeAccessor'
        
Solution : 

 To fix this issue, you can search the whole master page has value like " __designer:Preview " or " "__designer:Values ", remove them using notepad file or SharePoint designer which ever is possible.


Tuesday, July 17, 2012

Call JavaScript in SharePoint



<
asp:Content ContentPlaceHolderId="PlaceHolderMain" runat="server">

<script language="javascript" type="text/javascript">

  function CallJavascript()
    {
       alert("This is SharePoint");
    }

    _spBodyOnLoadFunctionNames.push(" CallJavascript ");

</script>

</ asp:Content>

Friday, July 6, 2012

SharePoint 2010 : Delete extended web application of any zone



You cannot see extended web application in the CA. you have to select default zone web application.

 you can delete extranet/intranet/internet extended web sites using below steps

Central Administration > Manage Web Applications > Select your  Web Application as shown in picture > select Delete from ribbon > Remove sharepoint from IIS website



Select IIS web site and zone to remove

Using Powershell

Remove-SPWebApplication -identity http://sitename -Zone {Default | Intranet | Internet | Internet | Custom | Extranet} -Confirm

his command removes the zone that you have specified for the Web application extension at http://sitename. This command does not remove the content databases or the IIS Web site.

 Note:
Be aware that this cmdlet can be used to delete the Web application, so be sure to use the appropriate parameters.

Thursday, July 5, 2012

Internet Explorer cannot display the webpage SharePoint 2010


Recently I came across a problem like
   Internet Explorer cannot display the webpage SharePoint 2010
When I create a web application in Sharepoint 2010. 

I checked with all scenarios
  1. ·         Application pool in running fine
  2. ·         Restarted iis server
  3. ·         Database server is fine
  4. ·         Checked Service account account

Everything is fine but not able access sharepoint site. At last I realized that with the port number that I was using. Actualy I am using  http://servername:110 port number. This one is reserved port no for pop3
Just make sure the port number which you are using before creating a web application.

 here are the list of port number.






Common port numbers

The Internet Assigned Numbers Authority (IANA) is responsible for the global coordination of the DNS Root, IP addressing, and other Internet protocol resources. This includes the registration of commonly used port numbers for well-known Internet services.
The port numbers are divided into three ranges: the well-known ports, the registered ports, and the dynamic or private ports. The well-known ports are those from 0 through 1023. Examples include:
The registered ports are those from 1024 through 49151. IANA maintains the official list.[2] The dynamic or private ports are those from 49152 through 65535. One common use is forephemeral ports.

List of TCP and UDP port numbers


Monday, July 2, 2012

SharePoint 2010 : Alternate Access Mappings Programmatically

here is the good post on this

http://www.directsharepoint.com/2012/01/get-current-web-application-alternate.html

or


            foreach (SPAlternateUrl altUrl in oWebApp.AlternateUrls)
            {
                if (altUrl.UrlZone == SPUrlZone.Default)
                {
                    incomingURL = SPUtility.AlternateServerUrlFromHttpRequestUrl(altUrl.Uri).AbsoluteUri;
                }
            }



SharePoint 2010 FBA : Add FBA users to SharePoint group programmatically


SharePoint stores FBA users to below format

i:0#.f|sqlmembershipprovider|Surya (please replace with your membership provider name)

 here i is identity provider
      f is membership provider name 



you may get below error when the format is wrong

The user does not exist or is not unique.


   void AddUserstoGroup()
        {
            string siteurl = “yoursiteurl”;

          
            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                using (SPSite site = new SPSite(siteurl))
                {
                    using (SPWeb web = site.OpenWeb())
                    {
                        web.AllowUnsafeUpdates = true;
                        //string userName = "i:0#.f|sqlmembershipprovider|kumar";
                        //userName = userName.Split('|')[2];

                        string userName = "i:0#.f|sqlmembershipprovider|" + txtEmail.Text;
                        web.SiteUsers.Add(userName, txtEmail.Text,txtLastName.Text + "," + txtFirstName.Text, "");

                        SPUser user = web.SiteUsers[userName];
                        if (user != null)
                        {
                            //TNI Visitors
                            web.Groups["Visitors"].AddUser(user);
                            web.Update();
                            web.AllowUnsafeUpdates = false;
                        }

                        web.Update();
                        web.AllowUnsafeUpdates = false;

                    }
                }
            });



        }

Followers