Friday, May 10, 2013

Extract worksheets from Excel into separate files with PowerShell

I recently had need to dust off an old VB script I'd written years ago to get worksheets out of Excel files. I've also been curious about doing more with PowerShell, and besides feeling guilty about putting a VB script into use in 2012, it seemed like a really good learning opportunity.

So why not just rewrite the script in .NET? Well, you can definitely do that; in fact, the code would look very similar. However, not everyone is a .NET developer. I wrote the original VB script on a team where we were building C++ DLLs for ETL processing; .NET wasn't part of our code base. I also think there are plenty of IT roles - DevOps, DBAs, Network Admininstrators to name a few - that might find a simple PowerShell tool like this a little easier to use and/or modify for their needs.

So that being said, just copy & paste the code below into an empty .ps1 file, and you should be good to go. To use it, simply execute the following command (should work from command-line, batch file, or managed code):

PowerShell.exe -command "C:\ScriptFile.ps1" -filepath "C:\Spreadsheet.xls" -output_type "csv"

I did run into one problem / issue while writing this script - getting it to run the first time! Thanks to this great article by Scott Hanselman, I found out that there are some very tight Windows security restrictions on PowerShell scripts - particularly the ones you didn't write yourself. After reading his article, it seemed easier for me (and for anyone who wants to use my code) to just post the source code rather than a downloadable script with certificates, at least in this instance. Maybe if I write another PowerShell article I'll give the certificate thing a go.

If you get the error message I got - "The file C:\ScriptFile.ps1 cannot be loaded. The execution of scripts is disabled on this system. Please see "Get-Help about_signing" for more details." - you can enable execution of PowerShell scripts you'vecreated by running the following command 'As Administrator':

PowerShell.exe Set-ExecutionPolicy RemoteSigned

Anyway, here's my script:


# Purpose: Extract all of the worksheets from an Excel file into separate files.

[CmdletBinding()]
Param ( 
    [Parameter(Mandatory=$true,Position=0)] 
    [string]$filepath,

    [Parameter(Mandatory=$true,Position=1)] 
    [ValidateSet("csv","txt","xls","html")] 
    [string]$output_type 
)

#-----------------------------------------------------------------------------#

# Figures out and returns the 'XlFileFormat Enumeration' ID for the specified format.
# http://msdn.microsoft.com/en-us/library/office/bb241279%28v=office.12%29.aspx 
# NOTE: The code being used for 'xls' is actually a 'text' type, but it seemed
# to work the best for splitting the worksheets into separate Excel files.

function GetOutputFileFormatID 

Param([string]$fomat_name
    $Result = 0 

    switch($fomat_name
    { 
        "csv" {$Result = 6
        "txt" {$Result = 20
        "xls" {$Result = 21
        "html" {$Result = 44
        default {$Result = 51
    } 
    
    return $Result 
}

#-----------------------------------------------------------------------------# 

$Excel = New-Object -ComObject "Excel.Application" 
$Excel.Visible = $false #Runs Excel in the background. 
$Excel.DisplayAlerts = $false #Supress alert messages. 

$Workbook = $Excel.Workbooks.open($filepath

#Loop through the Workbook and extract each Worksheet in the specified file type.  
if ($Workbook.Worksheets.Count -gt 0) { 
    write-Output "Now processing: $WorkbookName" 
    
    $FileFormat = GetOutputFileFormatID($output_type

    #Strip off the Excel extension. 
    $WorkbookName = $filepath -replace ".xlsx""" #Post 2007 extension
    $WorkbookName = $WorkbookName -replace ".xls""" #Pre 2007 extension 

    $Worksheet = $Workbook.Worksheets.item(1

    foreach($Worksheet in $Workbook.Worksheets) { 
        $ExtractedFileName = $WorkbookName + "~~" + $Worksheet.Name + "." + $output_type 

        $Worksheet.SaveAs($ExtractedFileName$FileFormat

        write-Output "Created file: $ExtractedFileName" 
    } 


#Clean up & close the main Excel objects. 
$Workbook.Close() 
$Excel.Quit() 

Deploying Workflow as WSP File


In this article we can learn how to:
  • Create WSP using Visual Studio 2010
  • Deploy WSP to another SharePoint site
  • Export a Workflow as WSP

WSP Extension


A file with WSP extension represents SharePoint Solution Package. It is actually a cab file. When we create a workflow and make a WSP file we can use the file to deploy the Workflow to multiple SharePoint sites.

Creating a WSP File inside Visual Studio


We have to use the Package command for the solution to create the WSP file.


You can get the WSP file inside the bin\Debug folder of the solution.


The WSP file is actually a cabinet file. You can try opening it with Winzip/Winrar as shown below to see the contents.


Deploying WSP to SharePoint


Now we can deploy the WSP file to SharePoint. For this do the following steps.
Open the SharePoint site and use Site Settings > View All Site Content > Site Assets.


Click on the Add document link as highlighted above.



In the appearing dialog box select the WSP file we generated and click the OK button.

After this step we need to activate the solution from Site Settings > Galleries  > Solutions.

Deploying using stsadm

We can deploy the solution using the command line tool of SharePoint. You can open the SharePoint 2010 Management Shell console from the start menu.  Execute the following command once in the debug folder.

Stsadm –o addsolution –filename YourSolution.WSP

Once done with the above command open SharePoint Central Administration and from System Settings > Manage Farm Solutions > Select the workflow and click on Deploy Solution button as shown below.


Now go back to the SharePoint site and use Site Actions > Site Settings > Site collection features to activate the workflow.


Now use the Site Actions > Site Settings > Workflow settings page to add the workflow.

The deployment is completed and the Workflow is activated. You can access the workflow from List > Site Workflows > WF2.

Export a Workflow as WSP

Now we can try exporting a WSP file from an existing SharePoint site. The exported file can be used to deploy to another SharePoint server. For exporting follow the steps below.

Open Site Assets from Site Actions > View All Site Content.


Click on an existing Workflow, for example Contact Workflow in the above screen. The browser will prompt with the Save As dialog. Click the Save button to get the WSP file. This file can be used to deploy the solution to another SharePoint server.

Apps in SharePoint 2013

 Why Apps? What's wrong with Solutions?

The world is getting smaller day by day, thanks to technology. Big desktops became Bulky laptops. Bulky laptops became Notebooks. Notebooks became Ultra books. Now the trend is moving towards Tablets and Smart phones. So does our applications. Web applications becoming Apps. "Apps" is not just a marketing strategy to increase use of SharePoint in wider markets, but also a complete replacement of sandbox approach with many other Pros for both Development, Deployment and Usage.

Do you know that sandbox solutions are deprecated in 2013?

Sandbox Solutions are introduced in SP 2010 and now they are off, to encourage the usage of Apps. May be we should understand the seriousness of Microsoft towards "Apps" in future. Of- course the conventional SP solution approach is still there.

SP 2013 Development Options

  1. Full-trust SharePoint Solutions (WSP)
  2. Apps

Main reasons for "Apps" development

  1. Custom code will not be executed on server. So this can avoid, Application / Server outages.
  2. Custom code will be executed in Client-Browser or may be in some other scope like IIS or Windows Azure, which is completely out of SharePoint scope.
  3. Server Object Model (SOM) code is replaced by Client side object model (CSOM) / Rest Services using which Apps can communicate with Server. Authentication is done by OAuth.
  4. Installing / Updating / Uninstalling of apps can be done without  affecting the SharePoint site.
  5. Better usability in Tablets and Mobile devices.
  6. Taking SharePoint to next level in terms of  Usability, Development, Deployment  and  Hosting(cloud).
  7. Finally, everything in SharePoint 2013 is an App.
I know, the next question is "Most of these reasons are just sounding like reasons for Sandbox Solutions?" Well I have a question for you, how many times we have chosen sandbox solution for real-time implementation?
  1. No full object model . . .
  2. Understanding of Sandbox architecture
  3. Not an easy task to create proxies for execution of full trust code.
What ever may be the reason, real-time applications are tough to develop using a Sandbox solution. That is why "Apps" are introduced in SharePoint 2013 for ease of development and deployment.

Hosting Options in Apps

  1. Provider-hosted
  2. Hosted in the cloud (Windows Azure autohosted)
  3. Hosted in a SharePoint environment
  4. Several combinations of these options.


How apps for SharePoint Work


In above case, App1 is a Provider-hosted or a Cloud-Hosted (Auto-Hosted) app and App2 is a SharePoint Hosted App. So anything related to App1 will be created/Maintained in respective locations, either on Provider or Azure servers. This makes App1 safe and secure in execution perspective.
Now we need to look at App2.
When you create/Imported/Added a SharePoint-Hosted App, it will create a separate sub-web under your SP Web application. This app will be executed in a separate App Domain different from Farm App Domain. So, as process runs under App Domains, any exceptions in Apps will not cause any Outage to SharePoint Farm.


We will see the creation of an SharePoint-Hosted App and issues involved in doing so, in our next post.

Wednesday, May 8, 2013

Developing Sharepoint Windows Forms

Intro:


this Tip is for all developers who would like to make a user friendly Interface using sharepoint sites and Objects.

developing a windows Form is a good choice when it comes to fast interactive tool instead of using Basic console Application 


I'm going to list the steps in details to create the windows form 
Application and how does it support Sharepoint Objects model. 


STEP 1:

First go to Visual Studio 2010 and Create New Project choose the programming language for example C# then choose Windows Forms  Application 


STEP 2:

Rename the Project ,then when it is created right click the Project to edit the properties 


STEP 3:

In the Application tab choose the target frame work  .net FrameWork 3.5.


STEP 4:

In the Build tab change the platform target to Any CPU


STEP 5:

Right click references and add
sharepoint references, Microsoft.SharePoint .dll,
Microsoft.SharePoint.Client, Microsoft.SharePoint.Client.Runtime

select Browse go to the 14%  (C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\ISAPI


STEP 6:

right click the Form and select view code to go to the CS file then Add the using statement in the CS file 
using Microsoft.SharePoint; 



STEP 7:

Design the form (add the controls , labels, textboxes…etc.) I have designed a simple form with 2 labels 1 text box and 1 button.


STEP 8:

If you have button just right click the button and choose view code insert the sharepoint  code in the button action . 
this is only a simple code that will ask the user to enter URL and click on the button that will display the title of the Site. 
   private void button1_Click(object sender, EventArgs e)
        {
            //ask the user to enter Site Collection URL
            string SiteURL = textBox1.Text;
            using (SPSite SiteCollection = new SPSite(SiteURL))
            {
                label2.Visible = true;
               label2.ForeColor = System.Drawing.Color.Green;
                label2.Text = "Site Collection URL is :" + SiteCollection.RootWeb.Title.ToString();
            }
        } 



STEP 9:

you are done now , only run the solution and you can display the windows form



Granting Anonymous Access to Sharepoint List / Library Programmatically


In this post, we will see how to enable and disable Anonymous access to a List or Document library from a Sharepoint feature (C# code).

There are 3 different steps involved in granting Anonymous access to a List/Library in a right way.

STEP1:

Enabling the anonymous access to the Web application from Central Admin. This does not mean that the whole web application is now anonymous. This step signifies that this web application has the ability to host resources that can be accessed by Anonymous user.

Then,

Then,

Now click save and close Central Admin. I am pointing again that the above step will not make the whole web application accessible to anonymous users. This will create scope for hosting something that can be accessible by anonymous user.

STEP2:

Enabling the Anonymous permissions in Web application settings. Go to Site Permission screen. As you have already enabled Anonymous access for this web application from central admin, a new button "Anonymous Access" will appear on the ribbon.


Now, the list can be accessed by unauthenticated / anonymous users.

But, in real time scenarios, step 3 is not recommended as it involves manual intervention in granting access, which is not possible in most of the PRODUCTION scenarios.

So, it is recommended to perform step 3 using a feature activation or de-activation.

Here is the code for making a Document library anonymous while activating a feature.


Here is the code for removing Anonymous access to a Document library while de-activating a feature.

Happy coding!










Change Site Collection URL in SharePoint 2010

The Problem

If you want to change the site name (i.e. http://myserver/sites/SiteName/) in the site collection URL, you can't use Site Setting or Central Administration. Unfortunately, the only way is backup the site, delete it and restore in a new site with the right name.

In Sharepoint 2007, you can use the stsadm command to do this, but in SharePoint 2010 you can't do this. You have to use Windows PowerShell for SharePoint.




First of all, open SharePoint 2010 Management Shell, you can find it under Microsoft SharePoint 2010 Products in the Start menu.

The first step is backup the current site:
//
// Backup-SPSite http://myserver/sites/OldSiteName/ -Path C:\MySite.bak
// 
After that, delete the site using the following code:
//
// Remove-SPSite –Identity http://myserver/sites/OldsiteName/
// 
NOTE: This step is necessary only if you want to restore the buckup in the same server of the old site. You have to do this because after the restore, a lot of items (i.e. lists) use the same IDs of the original site.
Now you can restore the site in a collection with the right name:
//
// Restore-SPSite http://myserver/sites/NewSiteName/ -Path C:\MySite.bak
// 

Create an SSL Site in SharePoint 2010


As part of development activities we might need to create an SSL enabled site inside SharePoint 2010. These sites will be accessed using HTTPS instead of HTTP.

For example:


HTTPS is the secured way of communication between server and client. Here the message is encrypted between client and server. An encryption mechanism is needed protect the message from being manipulated by unwanted parties.

HTTPS works by installing a certificate in the server side web application. This certificate is used to encrypt the messages between client and server.  The encryption is based on a public key and private key usage. The public key will be shared with client for encrypting the message and the decryption is performed on the server side using the private key.

Note: Stealing the public key does not do any favour in decrypting the message using Man In the Middle attack as Public key can only be used for encryption.

Please following the steps given below to create a new SSL enabled SharePoint site.

Step 1: Create New Web Application

Go to Central Administration and open the Manage Web Applications link. Create a new Web Application with the following properties:

  1. Name as My Secured Site
  2. Use Secured Sockets Layer (SSL) Yes



Click the OK button to create the new web application.

Now add a new site collection inside the newly created web application.

Central Administration > Create Sitecollection > Choose current web application

Step 2: Set the Certificate

For SSL enabling you need to specify a Certificate in the Server which contains the public and private keys.

Go to Internet Information Services (IIS / inetmgr.exe) and select the newly created site. Click on the Bindings link from the right side.


In the appearing dialog select the https item and click the Edit button.


In the appearing dialog select the Certificate from drop down list.


Click the OK button to continue.

Step 3: Test the URL.

Now you are ready to test the HTTPS url.  Open a browser and enter the url of the web site. You can also you the Browse link from IIS.

You will get the page as shown below. It says the certificate is not trusted one. You can use the Continue link to proceed with.


Now you should be prompted with the site credentials. Enter the credentials to continue and you should get the site collection which you have created.


Wow! If you can see the above site then you are done with your SSL enabled site. Please note that the URL now starts with https.

Adding SSL (https) support to an existing web application

You can add SSL support to an existing web application by performing the following:
  1. Open IIS manager
  2. Select the web application
  3. Choose Bindings dialog
  4. Add new binding of type https
  5. Select the Certificate
  6. Click the OK button