2013년 4월 2일 화요일

powershell 솔루션 업로드

powershell 솔루션 업로드 배포하기


Add-SPSolution "C:\Deploy\EventRec_SendMail.wsp"
Install-SPSolution -Identity EventRec_SendMail.wsp -GACDeployment -webapplication "http://ddd.aa.co.kr"

Update-SPSolution -Identity EventRec_SendMail.wsp -LiteralPath "C:\Deploy\EventRec_SendMail.wsp" -GacDeployment
Uninstall-SPSolution -Identity EventRec_SendMail.wsp
Remove-SPSolution -Identity EventRec_SendMail.wsp

2013년 4월 1일 월요일

EventContext context = properties.Context;


EventContext context = properties.Context;


http://code.lamsfoundation.org/fisheye/browse/~raw,r=1.1/lams/LamsSharePointIntegration/LamsSharePointIntegration/Src/LAMSLessonListEventHandler.cs



/****************************************************************
 * Copyright (C) 2008 LAMS Foundation (http://lamsfoundation.org)
 * =============================================================
 * License Information: http://lamsfoundation.org/licensing/lams/2.0/
 * 
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License version 2.0 
 * as published by the Free Software Foundation.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301
 * USA
 * 
 * http://www.gnu.org/licenses/gpl.txt
 * ****************************************************************
 */

using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.SharePoint;

namespace LamsSharePointIntegration
{
    /// <summary>
    /// This class handles events to do with the site's LAMS lesson table
    /// </summary>
    class LAMSLessonListEventHandler : SPItemEventReceiver
    {
        private string FormatCompanyName(string value)
        {
            return value.ToUpper();
        }

        public override void ItemAdding(SPItemEventProperties properties)
        {
            // Validation handled by SharePoint
        }

        /// <summary>
        /// Handles the event when a new lesson is added to the LAMS lesson table for the site
        /// </summary>
        /// <param name="properties">Properties of the item to be added</param>
        public override void ItemAdded(SPItemEventProperties properties)
        {
            // Get the site context information
            SPEventContext context = properties.Context;
            SPSite site = new SPSite(properties.SiteId);
            SPWeb siteWeb = site.OpenWeb(properties.RelativeWebUrl);
            SPUser user = siteWeb.CurrentUser;
            DisableEventFiring();

            // Get the title for the lesson, not null
            string title = properties.ListItem["Title"].ToString();
            
            // Get the description for the leson
            string description = "";
            if (properties.ListItem["Description"] != null)
            {
                description = properties.ListItem["Description"].ToString();
            }

            // Get the sequence id for the lesson, not null
            string sequenceId = properties.ListItem["SequenceID"].ToString();
                        
            // The lesson id of the started lesson, if successful
            string lessonId;
            try
            {
                lessonId = LAMSSecurityUtil.startLesson(user, siteWeb, sequenceId, title, description, "start");
            }
            catch (System.Net.WebException e)
            {
                properties.ErrorMessage = "Request to LAMS server to start lesson failed. Please Contact System Administrator";
                properties.Cancel = true;
                properties.Status = SPEventReceiverStatus.CancelWithError;
                properties.ListItem.Delete();
                return;
            }

            // Set the LessonID param for the item and the start and end date to null
            properties.ListItem["LessonID"] = lessonId;
            properties.ListItem["Start Date"] = null; 
            properties.ListItem["End Date"] = null; 
            
            properties.ListItem.Update();
            EnableEventFiring();
        }
    }
}

웹파트 배포시 에러 "컴퓨터의 SPUserCodeV4 서비스를 시작할 수



웹파트 배포시 에러 "컴퓨터의 SPUserCodeV4 서비스를 시작할 수

출처 : http://sharepoint.tistory.com/226

VS 2010 을 이용해서 개발한 쉐어포인트 모듈(샌드박스 모듈)을 배포하는데 에러가 발생합니다

컴퓨터의 SPUserCodeV4 서비스를 시작할 수 없습니다
라고 메세지가 뜨면서 에러가 발생하는데, 해결법은 이렇습니다.

중앙관리 사이트에 접속하여 시스템설정->서버의 서비스 관리로 이동합니다.

샌드박스 관련 서비스가 꺼져 있는 것을 볼 수 있습니다.

“시작” 을 눌러 서비스를 시작시킵니다.
 

해결완료 !!

sharepoint mail send


Send Email from SharePoint - SPUtility.SendEmail


Sending email is a key function of enterprises solutions. Inside SharePoint collaboration environment you always need to send email from within SharePoint. For this purpose you can use SPUtility class SendEmail method.

 
Did you ever need to send an email out, from your SharePoint custom web application? When you have such a task, perhaps the first idea that you have is to use System.Net.Mailnamespace. However, this requires that your application maintains a setting for the SMTP server, reply address and etc.
If you want the task of storing this configuration to SharePoint (and its Administrator) and instead, just focus on sending out the actual email then the solution is the Microsoft.SharePoint.Utilities.SPUtilityclass! It has the very convenient method 'SendEmail'. This is basically SharePoint's native functionality for email delivery.

The first thing you (or the SharePoint Administrator) need to do is setup the Outgoing email SMTP server. Open Central Admin àSystem SettingsàConfigure Outgoing Email
There, you need to set the Outbound SMTP server, From address and Reply-to address.
Now, you actually send email from your code as follows:
First, it is always a good idea to check if the email server is set:
bool blnIsEmailServerSet = SPUtility.IsEmailServerSet(web);

If this returns false, you should not bother trying to send the email. Instead, show an error message or notify the SharePoint administrator, to check the settings of the server. If it returns true, you are good to go:
SPWeb web = SPContext.Current.Web;
bool appendHtmlTag = false;
bool htmlEncode = false;
string toAddress = "test@example.com";
string subject = "Subject";
string message = "Message text";
bool result = SPUtility.SendEmail(web, appendHtmlTag, htmlEncode, toAddress, subject, message);

In some cases, you may need to run this code with elevated privileges:
SPSecurity.RunWithElevatedPrivileges(delegate()
{
bool result = SPUtility.SendEmail(web, appendHtmlTag, htmlEncode, toAddress, subject, message);
});
SendEmail method returns a boolean, indicating if sending the email was successful or not.

As you can see that sending email using SPUtility is straightforward, please also note the following considerations
1.   No attachment allowed
2.   Message body size cannot exceed 2048 characters.
3.   The from address will be the “Outbound Sender Address” configured in the central admin.





http://emailfromsharepoint.blogspot.kr/2012/04/send-email-from-sharepoint.html
http://www.mindfiresolutions.com/Send-Email-in-Sharepoint-using-SPUtilitySendEmail-using-HTML-tags-1271.php

2013년 3월 20일 수요일

c# - Claim auth from ADFS



c# - Claim auth from ADFS

jwillmer release 2013-03-21 04:29:01 View:1

I try to connect to a SharePoint Online instance via a WPF-Application. I have found this article[1] that discribes a possible solution but the problem is that the specific instance has a Active Directory Federation Services (ADFS) infront and I don't know how to get the auth-token. (I can't create a certificate for my application to authentificate against the adfs.)
Anyone who have already done this and can support me with some code snippets?
[1] http://www.wictorwilen.se/Post/How-to-do-active-authentication-to-Office-365-and-SharePoint-Online.aspx
------ Solutions --------------------------------------------------------
I've played with Fiddler. Basically the flow goes like this:
  • Get a SAML token from ADFS
  • Post it to https://login.microsoftonline.com/login.srf (body should be wa=wsignin1.0, wresult=<requestsecuritytokenresponse>…token…</rstr> and wctx=MEST=0&LoginOptions=2&wa=wsignin1%2E0&rpsnv=2&ct=1343219880&rver=6%2E1%2E6206%2E0&wp=MBI&wreply=https%3A%2F%2Fspirit365%2Esharepoint%2Ecom%2F%5Fforms%2Fdefault%2Easpx&id=500046&cbcxt=mai&wlidp=1&guest=1&vv=910&mkt=EN-US&lc=1033&bk=1343219930
  • Capture the input hidden named "t" from the Form
  • POST that "t" to /_layouts/Authenticate.aspx. That should give you the FedAuth and rtFa cookie.
From that point this is the same as the code here: http://www.wictorwilen.se/Post/How-to-do-active-authentication-to-Office-365-and-SharePoint-Online.aspx
------ Solutions --------------------------------------------------------
I have found the solution and made a post about it. I also put it on github. You can find my blog post along with the github link at my blog:http://jwillmer.de/blog/2013/01/04/sharepoint-online-with-adfs-authentication/
I hope this helps you as much as it helped me :-)

2013년 3월 11일 월요일

Treeview Recursive trawl using the SP Client Object Model

Recursive trawl using the SP Client Object Model


Here’s a simple example of SP2010’s managed Client Object Model being used to build up a TreeView of subsites and lists, for a given site. 

I’m using WinForms just to show the concept, if you’d like to recreate it, simply create a form and insert a TreeView control (called tv1), and a Label (called label1). Don’t forget to add a reference to Microsoft.SharePoint.Client as well.

Screen Shot 2011-09-13 at 2.43.16 PM

Optionally comment out the “Short Version” and uncomment the Long - This additional code goes an extra level, i.e. it iterates through the items of each list. Bear in mind this will slow down considerably, and there is also the 5000 row List Threshold limit to take into account. 

I had expected File Size to be a property in the COM (let me know if it is!) but I just couldn’t find anything related. This means we’re still stuck with dealing with CAML / Internal Names, etc. when it comes to bringing these back, e.g. File_x0020_Size :(

Check out MSDN’s Using the SharePoint Foundation 2010 Managed Client Object Model as a good starting point. The way Linq is used to ‘queue up’ only the relevant list properties we’re after, and filter the list collection to ignore hidden lists is pretty neat, makes for very simple / brief code.

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using System.Windows.Forms;
using Microsoft.SharePoint.Client;

namespace WindowsFormsApplication1
{
    public partial class Form1 : System.Windows.Forms.Form
    {
        private SPItems items = new SPItems();

        public Form1()
        {
            InitializeComponent();

            items.ItemAdded += new SPItems.OnItemAdded(items_ItemAdded);
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            new Thread(() =>
            {
                using (ClientContext clientContext = new ClientContext("http://mysite”))
                {
                    clientContext.AuthenticationMode = ClientAuthenticationMode.Default;
                    clientContext.Credentials = System.Net.CredentialCache.DefaultNetworkCredentials;

                    var web = clientContext.Web;

                    ProcessWeb(clientContext, web, new Guid());
                }

                tv1.Invoke(new Action(() =>
                {
                    tv1.Nodes.Add(items.getTreeNodeCollection());
                    tv1.Nodes[0].Text = "Site Structure";
                    tv1.SelectedNode = tv1.Nodes[0];
                    tv1.ShowNodeToolTips = true;
                    tv1.ExpandAll();
                }));

            }).Start();
        }

        protected void items_ItemAdded(object sender, SPItem i)
        {
            label1.Invoke(new Action(() => label1.Text = i.Title));
        }

        private void ProcessWeb(ClientContext c, Web web, Guid parentID)
        {            
            c.Load(web);
            c.Load(web.Lists, lists => lists.Include(l => l.Title, 
                                                    l => l.Id, 
                                                    l => l.DefaultViewUrl,
                                                    l => l.ParentWebUrl).Where(l => !l.Hidden));
            c.Load(web.Webs);
            c.ExecuteQuery();

            items.AddItem(new SPItem() { ID = web.Id, 
                                         ParentID = parentID, 
                                         Title = web.ServerRelativeUrl });

            foreach (List l in web.Lists)
            {
                /* SHORT VERSION */

                items.AddItem(new SPItem()
                {
                    ID = l.Id,
                    ParentID = web.Id,
                    Title = l.Title
                });

                /* END SHORT VERSION  */
                
                /* LONG VERSION - Iterates through every listitem to get file size */

                //var cml = new CamlQuery() { ViewXml = @"<View><ViewFields><FieldRef Name='File_x0020_Size' /></ViewFields><Query></Query></View>" };
                //var lic = l.GetItems(cml);

                //try
                //{
                //    c.Load(lic);
                //    c.ExecuteQuery();

                //    long totalSize = 0;
                //    long totalItems = 0;

                //    foreach (ListItem li in lic)
                //    {
                //        if (li.FieldValues.Keys.Contains("File_x0020_Size"))
                //        {
                //            long size = 0;

                //            if (long.TryParse(li.FieldValues["File_x0020_Size"].ToString(), out size))
                //                totalSize += size;
                //        }

                //        totalItems++;
                //    }

                //    items.AddItem(new SPItem()
                //    {
                //        ID = l.Id,
                //        ParentID = web.Id,
                //        Title = l.Title,
                //        ItemCount = totalItems,
                //        ItemSizeBytes = totalSize
                //    });
                //}
                //catch (Exception exc)
                //{
                //    Debug.WriteLine("EXCEPTION: " + exc.Message);
                //}

                /* END LONG VERSION - Iterates through every listitem to get file size */
            }

            foreach (Web sub in web.Webs)
            {
                try
                {
                    ProcessWeb(c, sub, web.Id);
                }
                catch (Exception exc)
                {
                    Debug.WriteLine("EXCEPTION: " + exc.Message);
                }
            }
        }
    }

    public class SPItems : List<SPItem>
    {
        public delegate void OnItemAdded(object sender, SPItem i);
        public event OnItemAdded ItemAdded;

        public void AddItem(SPItem item)
        {
            this.Add(item);
            ItemAdded(this, item);
        }

        public TreeNode getTreeNodeCollection()
        {
            var n = new TreeNode();
            
            foreach (SPItem o in this)
            {
                if (o.ParentID == new Guid())
                    n.Nodes.Add(getNode(o));
                else
                {
                    var found = n.Nodes.Find(o.ParentID.ToString(), true);

                    if (found.Length > 0)
                        found[0].Nodes.Add(getNode(o));
                }
            }

            return n;
        }

        private TreeNode getNode(SPItem o)
        {
            return new TreeNode(o.Title)
            {
                Name = o.ID.ToString(),
                ToolTipText = "ITEM COUNT = " + o.ItemCount + Environment.NewLine + "ITEM SIZE = " + o.ItemSizeBytes
            };
        }
    }

    public class SPItem
    {
        public Guid ID { get; set; }
        public Guid ParentID { get; set; }
        public string Title { get; set; }
        public long? ItemCount { get; set; }
        public long? ItemSizeBytes { get; set; }
    }
}

How to get SubSites using client object model





How to get SubSites using client object model 




Try this code to get list of all sub sites
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint.Client;
using Microsoft.SharePoint.Client.Utilities;

private static void GetAllSubSites()
{
ClientContext clientContext = new ClientContext(“http://{yoursiteurl}/“);
Web oWebsite = clientContext.Web;
clientContext.Load(oWebsite,
website => website.Webs,
website => website.Title
);
clientContext.ExecuteQuery();
Console.WriteLine(“Available sites Count: ” + oWebsite.Webs.Count);
for (int i = 0; i != oWebsite.Webs.Count; )
{
Console.WriteLine(“Site Title: “+ oWebsite.Webs[i].Title);
}
}

My SharePoint Blog 
http://dhireny.blogspot.com