Thursday, February 27, 2014

PowerShell to check all the Farm Solutions Status different of “Deployed”

Initially, that solution was deployed with success on that farm, but for a weird reason that we couldn’t found out the why, that solution begun displaying an error on its status, as described on the screen shot below:

solutionerror

Based on this scenario, we decided to build a PowerShell to check all solutions status on our farms. If it find some solution with error status, it will create a log file pointing the name and the status of the solution and send by email this alert for the administrators.

Here is the PowerShell code:

####################

Add-PSSnapin Microsoft.SharePoint.PowerShell -EA 0

$ServerName = $env:computername

function sendMail($MailMSG) {
#Write-Host “Sending Email”
$attach = new-object Net.Mail.Attachment($MailMSG)

###First, the administrator must change the mail message values in this section
$FromAddress = “adm-web@sharepoint.com.br#change by your email address
$ToAddress = “adm-web@sharepoint.com.br”      #change by your email address

$MessageSubject = “$ServerName – Alert – Solution Undeployed on Farm”
#$MessageBody = $MailMSG
$MessageBody = “Please verify the attached”
$SendingServer = “smtp.yourcompany.com”         #change by your smt server
###Create the mail message
$SMTPMessage = New-Object System.Net.Mail.MailMessage $FromAddress, $ToAddress, $MessageSubject, $MessageBody
$SMTPMessage.Attachments.Add($attach)
###Send the message
$SMTPClient = New-Object System.Net.Mail.SMTPClient $SendingServer
$SMTPClient.Send($SMTPMessage)
$attach.dispose()
}

# Get current date and format it to avoid invalid characters such as “/” and “:”

$today=Get-Date -format “MM-dd-yyyy HH.mm.ss”

# Replace with your script location

$Location=”D:\Softwares\CheckFarmSolutionScript”

# Replace with your desired log file location + name

$logFile=”$Location\LogSOLUTIONS.log”

If (Test-Path $logFile){
Remove-Item $logFile -Confirm:$false
}

function List-Solutions()
{
$farm = Get-SPFarm
foreach ($solution in $farm.Solutions)
{

if($solution.Deployed -eq $false){
Write “Solution Verification started at $today” >>$logFile
Get-SPSolution -identity $solution.Name >>$logFile

}
}
}

#call the function List-Solutions

#test if the log file exists, If yes, send an email

If (Test-Path $logFile){

sendMail($logFile)

}
####################

Monday, February 17, 2014

Cannot start service SPAdminv4 on computer – SharePoint 2010 Administration

If you’ve experienced this error (System.InvalidOperationException, “Cannot start service SPAdminv4 on computer ‘.’) after installing/rebooting a SharePoint 2010 server and failing consistently at the SharePoint 2010 Products Configuration Wizard, then this is likely to help:

(1) Browse to C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\BIN

(2) In this directory Create a file called “WSSADMIN.EXE.CONFIG

(3) Populate it with the following:

<configuration>

      <runtime>

<generatePublisherEvidence enabled=“false”/>

      </runtime>

</configuration>

(4) Start the “SharePoint 2010 Administration” services again

Now everything should be working….

This disables checking for CAS (Code Access Security) publisher policy. MSDN article, http://msdn.microsoft.com/en-us/library/bb629393.aspx

More details, read http://blogs.msdn.com/johan/archive/2009/11/12/make-sure-you-have-an-internet-connection-when-using-signed-assemblies.aspx and http://blogs.msdn.com/dsvc/archive/2008/06/24/troubleshooting-startup-issues-with-managed-application-having-authenticode-signature.aspx

HOW TO: Como Habilitar o Developer Dashboard no SharePoint 2010

Developer Dashboard  é um novo recurso do SharePoint 2010 que vem para facilitar a vida do desenvolvedor e do responsável pelo bom desempenho e melhor experiência para o usuário final. Este recurso mostra quanto tempo uma página demorou para ser carregada e quais componentes foram carregados, sendo muito útil quando os usuários reclamam de lentidão, podendo assim, agora classificar o que seria e aonde esta “lentidão”, de forma mais fácil e rápida.

Solução:

Por default, este recurso vem desabilitado. Para habilitar, você pode utilizar o stsadm ou Windows PowerShell.

Para habilitar, usando STSADM, vá em Start > Microsoft SharePoint 2010 Products, clique em SharePoint 2010 Management Shell, e entre com o seguinte valor:

Stsadm –o setproperty –pn developer-dashboard –pv [modo]

Em [modo] , escolha a forma que você quer que ele funcione. Você pode escolher uma das três opções:

  • On – significa que o Developer Dashboard  será sempre exibido
  • Off – significa que estará desabilitado
  • Ondemand – significa que o Developer Dashboard  será exibido, mas não estará ativo, apenas quando precisar você deve ativá-lo clicando no seu ícone.

Ao habilitar este recurso, todas as páginas irão conter um ícone do Dashboard, como mostrado na imagem, porém, só os administradores do Site Collction poderão ver.

Caso tenha escolhido o modo ondemand, você pode habilitá-lo quando necessário apenas clicando sobre o ícone dele.

Figura 1: Representação do ícone

Quando habilitado, ele trará uma página com os resultados para análise.

Figura 2: Exibindo as informações

Agora basta você realizar suas análises.

Conclusão

Esta função é muito útil para os desenvolvedores para que eles possam entregar aplicações que funcionam corretamente sem ter problemas posteriores e também ajuda a detalhar o como a página e as web parts estão se comportando.

Mais referências:

http://larahvidotti.wordpress.com/2011/01/14/como-habilitar-o-developer-dashboard-no-sharepoint-2010/

Queue Service and Event Service will not start in Project Server 2007/2010

Open the registry editor

Start=>Run=>Regedit

Once the registry editor has been opened navigate to

HKLM\System\CurrentControlSet\Control

Here it will be necessary to create a new DWORD key with the following value:

ServicesPipeTimeout DWORD 60000 (decimal)

Note: 60000 = 60 Seconds.

Next, look for the WaitToKillServiceTimeout key – take note of its current value – and then change the value to 120000

Note: 120000=120 Seconds.

Reboot the Server.

Test by going to Start=>Run=>services.msc and examining the Microsoft Office ProjectServer Queue Service and Event Service. These services should now show as started, and assuming nothing else is wrong with the environment, the Queue Service should now be able to process jobs. The error messages in the event viewer should also have stopped.

Queue – ReportingProjectChangeMessageFailed (24006) – The INSERT statement conflicted with the FOREIGN KEY constraint FK_MSP_EpmAssignment_ResourceOwnerUID

Sintoma

            Ao publicar alguns projetos o job “Reporting (Project Publish)” relacionado ao projeto falha com a seguinte mensagem de erro:

“ReportingProjectChangeMessageFailed (24006) – The INSERT statement conflicted with the FOREIGN KEY constraint “FK_MSP_EpmAssignment_ResourceOwnerUID””

Causa

            Há várias causas distintas para a falha do job “Reporting (Project Publish)”. Neste caso em decorrência da mensagem de erro descrita acima a causa estava relacionada a falha de sincronização de um recurso membro do projeto com o base de dados de Reporting.

Solução

1. Executar a query abaixo na base de dados de Reporting (ProjectServer_Reporting – usar o nome conforme seu ambiente) com o intuito de identificar quais recursos tem problema de sincronização

select PubMR.Res_UID, PubMR.RES_Name, PubMR.WRES_Account, RepMER.ResourceName from ProjectServer_Reporting.dbo.MSP_Resources PubMR

left outer join ProjectServer_Reporting.dbo.MSP_EpmResource RepMER on PubMR.RES_UID = RepMER.ResourceUID where ResourceName is NULL

2. Da lista acima para o usuário que é membro do projeto forçar seu sincronismo com a base de Reporting através dos passos abaixo:

a. Acessar o PWA -> Resource Center

b. Selecionar o usuário no Resource Center e Editar

c. Salvar sem fazer qualquer alteração

d. Verificar se o seguinte job é completado com sucesso

 

3. Publicar novamente o projeto e verificar se o job “Reporting (Project Publish)” completa com sucesso.

Informações adicionais

            Conforme dito há várias outras razões que podem ocorrer a falha do job “Reporting (Project Publish)”, mas as causas dependem diretamente da descrição do erro gerado. Duas outras causas mais conhecidas do erro são:

  1. Recurso atribuido a uma tarefa do tipo “Sumarry Task”
  2. Tarefas nas Linhas de base orfãs. Como detectar este cenário e corrigir:

Please test the behavior on a test environment before.

Run the following scripts on your draft and published databases:

- First run this script to detect them:

select PROJ_NAME, MTB.PROJ_UID,TASK_UID,TB_BASE_NUM from MSP_TASK_BASELINES MTB

inner join MSP_PROJECTS MP on MTB.proj_uid=MP.proj_uid

where TASK_UID not in (select TASK_UID from MSP_TASKS)

- Next, we need to delete them:

—Script top run on the draft DB

USE ProjectServer_Draft – specify the appropriate draft database

delete from MSP_TASK_BASELINES

where TASK_UID not in (select TASK_UID from MSP_TASKS)

—Script top run on the published DB

USE ProjectServer_Published — specify the appropriate published database

delete from MSP_TASK_BASELINES

where TASK_UID not in (select TASK_UID from MSP_TASKS)

Erro ao acessar uma lista customizada do SharePoint coletando dados no Project Server 2010

Mensagem de erro:

Unable to display this Web Part. To troubleshoot the problem, open this Web page in a Microsoft SharePoint Foundation-compatible HTML editor such as Microsoft SharePoint Designer. If the problem persists, contact your Web server administrator.

Correlation ID:9b6b1653-baef-46a4-ace8-ff9a1f535f87

Screenshot error:

EPM2014_1

Resolução:

Aumentar o timeout nas listas:

$farm = Get-SPFarm

$farm.XsltTransformTimeOut = 10

$farm.Update()

Link de referencia: http://www.brandonclaps.com/?p=51

This was caused by the XsltTransformTimeout when using an Xslt list view. This is corrected by installing the February 2012 Cumulative Update and by making the following change via PowerShell.

Friday, February 14, 2014

Daylight saving time ended and Sharepoint still off by 1 hour

The daylight saving time ended, but SharePoint still saving all items which require a date time stamp reference with 1 hour less (in my case).

Screenshot of the behavior:

daylight1

1.Modify the Timezone.xml file to include the correct date and time for standard time and for daylight saving time. To do this, follow these steps:

a. Start Notepad, and then open the Timezone.xml file.

The Timezone.xml file is located in the following folder:

SharePoint Server 2013

Drive:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\15\Config

SharePoint Server 2010

Drive:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\Config

Windows SharePoint Services 3.0 / MOSS 2007

Drive:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\12\Config

Microsoft Windows SharePoint Services 2.0

Drive:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\60\Config

b. The contents of the Timezone.xml file should resemble the following example bellow that I will modify.

c. Locate the time zone that you want to modify. In my case was Name=”(UTC-03:00) Brasilia”

<TimeZone ID=”8″ Name=”(UTC-03:00) Brasilia” Hidden=”FALSE”>
<Bias>180</Bias>
<StandardTime>
<Bias>0</Bias>
<Date>
<Month>2</Month>
<Day>4</Day>
<Hour>23</Hour>
<Minute>59</Minute>
<Second>59</Second>
<Milliseconds>999</Milliseconds>
<DayOfWeek>6</DayOfWeek>
</Date>
</StandardTime>
<DaylightTime>
<Bias>-60</Bias>
<Date>
<Month>10</Month>
<Day>3</Day>
<Hour>23</Hour>
<Minute>59</Minute>
<Second>59</Second>
<Milliseconds>999</Milliseconds>
<DayOfWeek>6</DayOfWeek>
</Date>
</DaylightTime>
</TimeZone>

d. Modify the StandardTime element to specify the correct date and time for standard time. For the current time zone, change the Day fields from 4 to 3.

<TimeZone ID=”8″ Name=”(UTC-03:00) Brasilia” Hidden=”FALSE”>
<Bias>180</Bias>
<StandardTime>
<Bias>0</Bias>
<Date>
<Month>2</Month>
<Day>3</Day>
<Hour>23</Hour>
<Minute>59</Minute>
<Second>59</Second>
<Milliseconds>999</Milliseconds>
<DayOfWeek>6</DayOfWeek>
</Date>
</StandardTime>
<DaylightTime>
<Bias>-60</Bias>
<Date>
<Month>10</Month>
<Day>3</Day>
<Hour>23</Hour>
<Minute>59</Minute>
<Second>59</Second>
<Milliseconds>999</Milliseconds>
<DayOfWeek>6</DayOfWeek>
</Date>
</DaylightTime>
</TimeZone>

e. Click Save on the File menu to save your changes.

f. Clean the SharePoint cache using PowerShell on SharePoint 2010 or manually for other versions. Bellow the PowerShell script:

#PowerShell Script to clean SharePoint Configuration cache:

Add-PSSnapin -Name Microsoft.SharePoint.PowerShell –erroraction SilentlyContinue

Stop-Service ProjectQueueService14

Stop-Service ProjectEventService14

Stop-Service SPTimerV4

$folders = Get-ChildItem C:\ProgramData\Microsoft\SharePoint\Config
foreach ($folder in $folders)
{
$items = Get-ChildItem $folder.FullName -Recurse
foreach ($item in $items)
{
if ($item.Name.ToLower() -eq “cache.ini”)
{
$cachefolder = $folder.FullName
}

}
}

$cachefolderitems = Get-ChildItem $cachefolder -Recurse
foreach ($cachefolderitem in $cachefolderitems)
{
if ($cachefolderitem -like “*.xml”)
{
$cachefolderitem.Delete()
}

}

$a = Get-Content  $cachefolder\cache.ini
$a  = 1
Set-Content $a -Path $cachefolder\cache.ini
start-Service SPTimerV4
IISRESET

########################

g. Test your environment again. Now, everything will be working right.

daylight2

Good references:

http://support.microsoft.com/kb/888253/en-us

http://spinternals.blogspot.com.br/2014/01/sharepoint-powershell-script-para.html

Tuesday, February 11, 2014

SharePoint – PowerShell script to list all Webs and Site Templates

One more gequick post today, this PowerShell script will iterate through all Webs within a Site Collection, print out their Title, URL, WebTemplate (Site Template) name and it language.

#############################################

cls

Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue

$site = Get-SPSite “http://mysite.mydomain.local

foreach ($web in $site.AllWebs) {

$web | Select-Object -Property Title,Url,WebTemplate,Language

}

$site.Dispose()

#############################################

Wednesday, February 5, 2014

LoopbackCheck – O que você deveria saber

O feature de segurança Loopback Security Check foi introduzido no Windows Server 2003 SP1 porque muitos exploits tentam a atacar o sistema operacional via “Reflect”. O Loopback Security Check bloqueia basicamente qualquer acesso no servidor a um site local ao usar o FQDN (fully qualified domain name) ou um host header personalizado.

Até aqui tudo bem, porém temos a situação que o SharePoint acessa as pagina locais, por exemplo na indexação da busca ou a consumir um dos próprios Web Services.

Nós podemos observar os seguintes eventos com Loopback Security Check habilitado:

No navegador ou no ULS:

HTTP 401.1 – Unauthorized: Logon Failed

E nos eventos do Windows:

Event Type: Failure Audit
Event Source: Security
Event Category: Logon/Logoff
Event ID: 537
Date: Date
Time: Time
User: NT AUTHORITY\SYSTEM
Computer: Computer_Name
Description: Logon Failure:
Reason: An error occurred during logon
User Name: User_Name
Domain: Domain_Name
Logon Type: 3
Logon Process: Ðùº
Authentication Package: NTLM
Workstation Name: Computer_Name
Status code: 0xC000006D
Substatus code: 0×0
Caller User Name: -
Caller Domain: -
Caller Logon ID: -
Caller Process ID: -
Transited Services: -
Source Network Address: IP_Address
Source Port: Port_Number

Eu vi muitas fazendas do SharePoint em produção com o Loopback Check desabilitado, ou veja vulnerável. Nós precisamos criar exceções em vez de desabilitar o recurso para as paginas do SharePoint para evitar os eventos acima seguindo o metodo 1 do KB896861.

Existem as seguintes formas para automatizar o procedimento:

Powershell

Substitue o valor SERVERNAME pelo endereço desejado

New-ItemProperty HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Lsa\MSV1_0 -Name “BackConnectionHostNames” -value “SERVERNAME” -PropertyType multivalue

Policy

O Harbar escreveu um artigo excelente sobre o assunto - http://www.harbar.net/archive/2010/02/12/groundhog-day-configuring-back-connection-host-names-using-group-policy.aspx

[]

David

SharePoint Support Engineer

Blog: http://spinternals.blogspot.com.br/