Showing posts with label SPO. Show all posts
Showing posts with label SPO. Show all posts

Monday, February 25, 2013

Custom Site Provisioning - SP2013 way....

Before I move on to the  content for my blog today .. here's some importnant information..SP2013 preview is ending soon to give way to the live version of SP2013 on the cloud ( o365)
 
O365 launch event info below. Please Sign up to see the new stuff.

Virtual Launch Event on February 27th 2013 as Microsoft celebrates the availability of a major new release coming to Office 365 for businesses.  Demo of new features in enterprise social and show how this has transformed the full Office experience you know into an always up-to-date service. Some real-world stories from customers about their move to the cloud. 
 
Now coming back to code....
 
Recently I had a requirement to do some feasibility study for SP2013 for sandboxed solutions. Well as we all know Microsoft has deprecated sandboxed solutions in o365 2013
This means that the functionality will still be available for use in SharePoint 2013, but primarily for backwards compatibility with existing solutions built using the sandbox solution approach.
 
Microsoft's guidance is that if you are building new applications that in the past you would have deployed as sandbox solutions, you should use the new App model for those solutions instead of using sandbox solutions.
 
More info on an article here...
 
Some SharePoint components are used in end-user scenarios but do not have any equivalents in the SharePoint app model. For these you must use farm solutions.

Well the requirement in this case is to "Create a custom user interface to provision a sub site based off a custom template, add some details to the site and add users"

Well - I plan to try this as an app too.. but from the looks of it if I want to create a custom web Template this is not supported. Hence, my first reaction is to create a Sandbox solution.

Upload a custom SP 2013 Site template in the solutions gallery!

 
 
 
 
 


CODE :
 using System;  
 using System.ComponentModel;  
 using System.Web.UI;  
 using System.Web.UI.WebControls;  
 using System.Web.UI.WebControls.WebParts;  
 using Microsoft.SharePoint;  
 using Microsoft.SharePoint.WebControls;  
 using Microsoft.SharePoint.Client;  
 using System.Collections.Generic;  
 using Microsoft.SharePoint.Navigation;  
 namespace SharePointProject1.CreateSubSite  
 {  
   [ToolboxItem(false)]  
   public partial class CreateSubSite : System.Web.UI.WebControls.WebParts.WebPart  
   {  
     string AccountGroup = "";  
     protected override void OnInit(EventArgs e)  
     {  
       base.OnInit(e);  
       InitializeControl();  
     }  
     protected void Page_Load(object sender, EventArgs e)  
     {  
       AccountGroup = txturl.Text + " Account Group - Contributor";  
       // Create more gropups based on requirements  
     }  
     protected string GetCustomTemplate(SPWeb web)  
     {  
       SPWebTemplate SiteTemplate = null;  
       // Find correct template  
       foreach (SPWebTemplate wt in web.GetAvailableWebTemplates((uint)1033)) // for EN-US use LCID 1033, http://msdn.microsoft.com/en-us/goglobal/bb964664  
       {  
         if (wt.Title == "AccountSiteTemplate")  
         {  
           SiteTemplate = wt;  
           break;  
         }  
       }  
       return SiteTemplate.Title;  
     }  
     protected SPWebTemplate GetCustomSiteTemplate(SPWeb web)  
     {  
       SPWebTemplate SiteTemplate = null;  
       // Find correct template  
       foreach (SPWebTemplate wt in web.GetAvailableWebTemplates((uint)1033))  
       {  
         if (wt.Title == "AccountSiteTemplate")  
         {  
           SiteTemplate = wt;  
           break;  
         }  
       }  
       return SiteTemplate;  
     }  
     private void CreateSPGroup(SPWeb newWeb)  
     {  
      //  AccountGroup = txturl.Text + " Account Group - Contributor";  
       SPGroup groupContributor = newWeb.SiteGroups[AccountGroup];  
       SPRoleDefinition roleDefinitionContributor = newWeb.RoleDefinitions.GetByType(SPRoleType.Contributor);  
       SPRoleAssignment roleAssigmentContributor = new SPRoleAssignment(groupContributor);  
       roleAssigmentContributor.RoleDefinitionBindings.Add(roleDefinitionContributor);  
       newWeb.RoleAssignments.Add(roleAssigmentContributor);  
       lblStatus.Text += "</br>Subsite Groups successfully created!!</br> ";  
     }  
     private void AddUsersToGroups(SPWeb newWeb)  
     {  
      //  AccountGroup = txturl.Text + " Account Group - Contributor";  
       SPUser spUser = newWeb.EnsureUser(txtContributor.Text);  
       if (spUser != null)  
       {  
         SPGroup spGroup = newWeb.Groups[AccountGroup];  
         if (spGroup != null)  
           spGroup.AddUser(spUser);  
       }  
       txtSiteDesc.Text = "";  
       txtSiteName.Text = "";  
       txturl.Text = "";  
       lblStatus.Text += "</br>User Successfully added to the group! ";  
       lblStatus.ForeColor = System.Drawing.Color.Green;  
     }  
     protected void Button1_Click(object sender, EventArgs e)  
     {  
       using (SPSite site = new SPSite(SPContext.Current.Web.Url))  
       {  
         using (SPWeb web = site.OpenWeb())  
         {  
           if (string.IsNullOrEmpty(txturl.Text))  
             txturl.Text = "Demo";  
            if (string.IsNullOrEmpty(txtSiteName.Text))  
             txtSiteName.Text = "Demo";  
            try  
            {  
              web.AllowUnsafeUpdates = true;  
              web.SiteGroups.Add(AccountGroup, web.CurrentUser, web.CurrentUser, string.Empty);  
              SPWeb newWeb = site.AllWebs.Add(txturl.Text, txtSiteName.Text, txtSiteDesc.Text, 1033, GetCustomSiteTemplate(web), true, false);  
              newWeb.Description = " New Account site created!!";  
              lblStatus.Text = "Subsite successfully created!! " + "<a href ='" + newWeb.Url.ToString() + "'> New Subsite Link </a> ";  
              CreateSPGroup(newWeb);  
              AddUsersToGroups(newWeb);  
              newWeb.Dispose();  
              web.Dispose();  
            }  
            catch (Exception ex)  
            {  
              lblStatus.Text = "Exception Occured! Error message : " + ex.Message.ToString();  
              lblStatus.ForeColor = System.Drawing.Color.Red;  
            }  
           finally  
           {  
             web.AllowUnsafeUpdates = false;  
           }  
         }  
       }  
     }  
     protected void txtTemplate_Click(object sender, EventArgs e)  
     {  
       using (SPSite site = new SPSite(SPContext.Current.Web.Url))  
       {  
         using (SPWeb web = site.OpenWeb())  
         {  
           txtSubsiteTemplate.Text = GetCustomTemplate(web);  
         }  
       }  
     }  
   }  
 }  


Upload the sandbox soultion to the solutions gallery

 
 


 



Add the web part top a page and start provisioning sites your way in SP2013...!!

Note:
In case you are thinking about the cool User Interface... This is because I have chosen a Theme - Orbit.. This is super simple and easy...
Please go through my blog to see how this can be done!



 
 

Monday, January 28, 2013

Send email in Sharepoint - Explore Options!

Today I am going to explore options we have to send emails in SharePoint. I find it very interesting that there are a couple of ways to send emails. Sending notifications is a very frequently asked feature from the clients in any application and SharePoint has an out of box feature called alerts.

MSDN - Alerts Details



Option 1:

Store the SMTP server address in the web.config and can utilize the send email function as below:

This ensures that you get the advantages of.NET-style mail delivery while keeping your configuration at one place in your Central Administration.
 
using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Net.Mail;
using Microsoft.SharePoint;

namespace Send_Email.Send_Email
{
    public partial class Send_EmailUserControl : UserControl
    {
        protected void Page_Load(object sender, EventArgs e)
        {
        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            bool sentemail = SendMail("Hello", "Test Body", false, "pallavi.sharma@xyz.com", "pallavi.sharma@neudesic.com", "", "");
        }
        public static bool SendMail(string Subject, string Body, bool IsBodyHtml, string From, string To, string Cc, string Bcc)
        {
            bool mailSent = false;
            try
            {
                SmtpClient smtpClient = new SmtpClient();
                smtpClient.Host = SPContext.Current.Site.WebApplication.
                OutboundMailServiceInstance.Server.Address;
                MailMessage mailMessage = new MailMessage(From, To, Subject, Body);
                if (!String.IsNullOrEmpty(Cc))
                {
                    MailAddress CCAddress = new MailAddress(Cc);
                    mailMessage.CC.Add(CCAddress);
                }
                if (!String.IsNullOrEmpty(Bcc))
                {
                    MailAddress BCCAddress = new MailAddress(Bcc);
                    mailMessage.Bcc.Add(BCCAddress);
                }
                mailMessage.IsBodyHtml = IsBodyHtml;
                smtpClient.Send(mailMessage);
                mailSent = true;
            }
            catch (Exception) { return mailSent; }
            return mailSent;
        }

    }
}


  If the SharePoint context is not available utilize the SPWebApplication reference from a new SPSite object :

public static string GetSharePointMailService(string mysite)
 {
 string address;
 using (SPSite site = new SPSite(mysite))
 {
 address = site.WebApplication.OutboundMailServiceInstance.Server.Address;
 }
 return address;
 }


Option 2 :

Utilize the embedded SharePoint SendEmail. This has reduced capabilities, but is as straightforward as possible, and is the preferred approach if you simply want to send e-mail.

SPUtility.SendEmail(web, useHtml, htmlEncode, to, subject, htmlBody)


 Option 3 :

Sending E-Mail from a WCF Service

try
 {
 using (SPSite site = new SPSite(“http://server name”))
 {
 SPWeb myWeb = site.RootWeb;
 {
 string to = “someone@Someone.com”;
 string subject = “My Subject Message”;
 string body = “My Message Body”;
 HttpContext curCtx = HttpContext.Current;
 HttpContext.Current = null;
 bool success = SPUtility.SendEmail(myWeb, true, true, to, subject, body);
 HttpContext.Current = curCtx;
 }
 }
 }
 catch (Exception ex)
 {// handle error here!!!}

In office 365, you have ability to use SANDBOX solutions so the above classes are not supported. I used this trick to send email in the online environment using Sharepoint designer workflows


Option 4:

Use SP Designer to create email notifications. Quick and Easy and can be conditional too.



You could also create a reusable workflow for a content Type and associate with any list which contains that content type.


 

Wednesday, January 23, 2013

Sharepoint 2013 - Preview Account Get started!

One can easily get an account by registering on the link below.

Microsoft Office 365 Enterprise Preview plan highlights

  • 25 User Licenses
  • Familiar Microsoft Office applications for your Windows PC
  • Email and documents
  • IT admin tools and policies for user management
  • Data Loss Prevention
  • Mail archiving and compliance
  • Team sites for project management
Very Important : Do not migrate your sites to production YET!
Note: The Office 365 Preview is for testing purposes only. All configuration data, user data, and user accounts that were created while testing will be deleted when the preview ends.

You will need the below for account creation:
1. An email Id which will be used by Microsoft to send you important account info.
2. Phone number
3. Company address
4. A mobile number which can get a text message sent by Microsoft for verification purposes for the account creation via the link below.

My preview account got successfully set up and I am super excited as to get some hands-on experience with the new features of SP2013.
As I am exploring SP2013 preview ( office 365 ) I am sure I will come across some very interesting features and learnings which I think will be worth sharing...

 

SP Fest Chicago - What we did on the cloud?


Here's my speaker slide from SP Fest Chicago, where we discussed what we did on the cloud for Hyatt.




 

Friday, June 8, 2012

Data Migration to the cloud!

Data Migration from a third party application to Sharepoint is often a requirement and I had this challenge on the Sharepoint online environment, where we do not have access to the Central Admin or the server itself.

Where there is a will there is a way! We had a challenging situation and we figured out a workaround to do the needful...

Since it was Lotus application data- we needed a means to get the data in a Microsoft format so that we could read it ( any third party connections are not supported in the cloud yet), Lotus connectors are not supported.

Solution : get all the data ported to an excel format which can be read from Sharepoint environment!
The data includes attachments as well - so design your excel in such a manner that the last 2 columns have the below information:


  1. Number of attachments
  2. Path and Name of attachments in the format ( c://attachments/recordId/test1.docx)

This uses the sharepoint client object model to upload the data and since the attachments behaves a little sneaky I used the web services to upload the attachments once the record was created!
There are enough comments in the code to explain the logic but in case you have any questions please let me know!

This console application needs to run in the same domain for picking up Admin credentials of the logged ion user for the upload process and takes a config file which details the parameters like, site, list name etc. Add a web Reference to the
http://localhost/_vti_bin/Lists.asmx and call it "SharepointListWS"

Here is the sample excel format : The second hidden row of the excel is the sharepoint column names from the List where the data is uploaded to.

Here is the code snippet that I created to import data from Lotus apps ( in a Excel format) to SPO world.

   
  
  
  private static void importFromExcel(StreamWriter streamwriterW)
  {
  
  try
  
 {
  
 Microsoft.Office.Interop.Excel.Application excelApp = new Microsoft.Office.Interop.Excel.ApplicationClass();
  
 string workbookPath = _ExcelPath;
  
 Microsoft.Office.Interop.Excel.Workbook excelWorkbook = excelApp.Workbooks.Open(workbookPath, 0, false, 5,
  
 "", "", false, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "", true, false, 0, true);
  
 Microsoft.Office.Interop.Excel.Sheets excelSheets = excelWorkbook.Worksheets;
  
 Microsoft.Office.Interop.Excel.Worksheet excelSheet = (Microsoft.Office.Interop.Excel.Worksheet)excelSheets.get_Item("Sheet1");
  
 object[,] values = excelSheet.get_Range(_ExcelRange).Value as object[,];
  
 ClientContext context = new ClientContext(_SharePointSiteUrl);
  
 context.AuthenticationMode = ClientAuthenticationMode.Default;
  
 Web web = context.Web;
  
 List list = web.Lists.GetByTitle(_ListName);
  
 for (int row = 3; row <= Convert.ToInt32(_ExcelRowNo); row++) // no. of rows of data in excel
  
 {
  
  ListItemCreationInformation listItemCreation = new ListItemCreationInformation();
  
 ListItem listItem = list.AddItem(listItemCreation);
  
 iRecord++;
  
 for (int column = 1; column <= Convert.ToInt32(_iColumnsToImport) + 1; column++) // no of fields/columns in excel to be imported
  
 {
  
 string columnName = values[2, column].ToString();
  
 strcolumnName = columnName;
  
 if (values[row, column] != null)
  
 {
  
  if (columnName == "AttachmentNo")
  
 {
  
 _strNoOfAttachments = values[row, column].ToString();
  
 strcolumnValue = _strNoOfAttachments;
  
 }
  
  else
  
 {
  
 listItem[columnName] = values[row, column];
  
 strcolumnValue = listItem[columnName].ToString(); 
  
 }
  
 }
  
 }
  
 listItem.Update();
  
 context.ExecuteQuery();
  
 string strListItemID = listItem.Id.ToString();
  
 _NoOfRowsImported++;
  
 
 logToFile("Record imported from Excel Row No :" + (iRecord + 2) + " to SP Record Id : " + strListItemID, streamwriterW);
  
 logToFile("No. of Attachments : " + _strNoOfAttachments, streamwriterW);
  
   if (_strNoOfAttachments != "0" && _strNoOfAttachments != null)
  
 {
  
 addAttachment(strListItemID, values[row, Convert.ToInt32(_iColumnsToImport) + 2].ToString(), streamwriterW);// if no. of attachment >0 
  
 }
  
 }
  
 excelWorkbook.Close();
  
 }
  
  catch (Exception e)
  
 {
  
 // log error here 
  
 }
  
 }
  
  private static void addAttachment(string strNewListItemID, string strAttachmentPathUnparsed, StreamWriter streamwriterW)
  
 {
  
  string attachmentUrl = string.Empty;
  
 try
  
 {
  
 //Parse path if delimiter exists 
  
 string[] splitAttachmentPath = strAttachmentPathUnparsed.Split(new Char[] { '|' });
  
 foreach (string strAttachmentPathParsed in splitAttachmentPath)
  
 {
  
  if (strAttachmentPathParsed.Trim() != "")
  
 {
  
 strAttachmentPath = strAttachmentPathParsed;
  
  if (!System.IO.File.Exists(strAttachmentPathParsed))
  
 {
  
 // log error

   return;
  
 }
  
  string fileName = Path.GetFileName(strAttachmentPathParsed);
  
 // Get file contents
  
 Byte[] contents = getFileStream(strAttachmentPathParsed);
  
 // Add the attachment to the new item in the SharePoint list & Instantiate a SharePoint
  
 // List Web Service object
  
 listWs = new SharePointListWS.Lists();
  
 // set the Web Service Credentials
  
 listWs.Credentials = System.Net.CredentialCache.DefaultCredentials;
  
 listWs.Url = _SharePointSiteUrl + "/_vti_bin/lists.asmx";
  
 attachmentUrl = listWs.AddAttachment(_ListName, strNewListItemID, fileName, contents);
  
 }
  
 }
  
    
 }
  
  catch (Exception ex3)
  
 {
  
 //log error  
 }
  
  if (!String.IsNullOrEmpty(attachmentUrl))
  
 {
  
     // log error

 }
  
 }
  
 }
  
 }