2013년 4월 4일 목요일

sharepoint excel service odc

2013년 4월 2일 화요일

sharepoint email


using System;
using System.Security.Permissions;
using System.Web;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Security;
using Microsoft.SharePoint.Utilities;
using Microsoft.SharePoint.Workflow;

//Code courtesy of @timferro, @dannyjessee, MSDN, and the internet
namespace SharePointProject1.EventReceiver1
{
    /// <summary>
    /// List Item Events
    /// </summary>
    public class EventReceiver1 : SPItemEventReceiver
    {
       /// <summary>
       /// An item is being added.
       /// </summary>
       public override void ItemAdding(SPItemEventProperties properties)
       {
           base.ItemAdding(properties);
       }

       /// <summary>
       /// An item is being updated.
       /// </summary>
       public override void ItemUpdating(SPItemEventProperties properties)
       {
           base.ItemUpdating(properties);
           if ((string)properties.ListItem["Status"] != (string)properties.AfterProperties["Status"])
           {
               properties.AfterProperties["Notes"] = "Status Change";
           }
       }

       /// <summary>
       /// An item is being deleted.
       /// </summary>
       public override void ItemDeleting(SPItemEventProperties properties)
       {
           base.ItemDeleting(properties);
           //Get user object
           SPUser user = properties.Web.SiteUsers.GetByID(properties.CurrentUserId);
           //If the user is not a Site Collection Admin, don't delete the item
           if (!user.IsSiteAdmin)
           {
               //Cancel the request with an error and set the error message
               properties.Status = SPEventReceiverStatus.CancelWithError;
               properties.ErrorMessage = "Only Site Collection Administrators can delete items from this list!";
           }
           
       }

       /// <summary>
       /// An attachment is being added to the item.
       /// </summary>
       public override void ItemAttachmentAdding(SPItemEventProperties properties)
       {
           base.ItemAttachmentAdding(properties);
       }

       /// <summary>
       /// An item was added.
       /// </summary>
       public override void ItemAdded(SPItemEventProperties properties)
       {
           base.ItemAdded(properties);
           //Get the list item that was added
           SPListItem item = properties.ListItem;

           //Set the Notes field with ItemAdded
           item["Notes"] = "ItemAdded";

           //Get a reference to the TestDocument document library
           SPList testDoc = properties.Web.Lists["TestDocument"];

           //Create a new folder in the document library
           SPListItem folder = testDoc.Folders.Add("", SPFileSystemObjectType.Folder, item.Title);
           folder.Update();

           //Get the document library name and folder url
           string[] splitFolderUrl = folder.Url.Split('/');

           //Encode the url string
           string folderUrlEncode = SPHttpUtility.UrlKeyValueEncode("/" + folder.Url);

           //Update the list item with the link
           item["Documents"] = properties.WebUrl + "/" + splitFolderUrl[0].ToString() + "/Forms/AllItems.aspx?RootFolder=" + folderUrlEncode + ", Click Me";
           
           //Disable event firing in this thread to avoid loops
           this.EventFiringEnabled = false;
           //Update the list item
           item.Update();
           //Reenable event firing
           this.EventFiringEnabled = true;
       }

       /// <summary>
       /// An item was updated.
       /// </summary>
       public override void ItemUpdated(SPItemEventProperties properties)
       {
           base.ItemUpdated(properties);
           //Get the updated list item object
           SPListItem item = properties.ListItem;
           //Set the Notes field to ItemUpdated
           item["Notes"] += " - ItemUpdated";

           //If the SetAlert checkbox is checked
           if ((Boolean)item["SetAlert"])
           {
               //Set it back to false
               item["SetAlert"] = false;
               //Get the current user's object
               SPUser user = properties.Web.SiteUsers.GetByID(properties.CurrentUserId);
               //Create a new user alert
               SPAlert alert = user.Alerts.Add();
               alert.Title = item.Title;
               alert.AlertType = SPAlertType.Item;
               alert.AlertFrequency = SPAlertFrequency.Immediate;
               alert.EventType = SPEventType.All;
               alert.Item = item;
               alert.Update(false);
           }

           //If the SendEmail checkbox is checked
           if ((Boolean)item["SendEmail"])
           {
               //Set it back to false
               item["SendEmail"] = false;
               //Send an email using SPUtility.SendEmail
               SPUtility.SendEmail(properties.Web, false, false, "timothy.ferro@gmail.com", "FEDSPUG Test Email", "TEST");
           }

           //Disable event firing in this thread to avoid loops
           this.EventFiringEnabled = false;
           //Update the list item
           item.Update();
           //Reenable event firing
           this.EventFiringEnabled = true;
       }

       /// <summary>
       /// An item was deleted.
       /// </summary>
       public override void ItemDeleted(SPItemEventProperties properties)
       {
           base.ItemDeleted(properties);
       }

       /// <summary>
       /// An attachment was added to the item.
       /// </summary>
       public override void ItemAttachmentAdded(SPItemEventProperties properties)
       {
           base.ItemAttachmentAdded(properties);
       }


    }
}

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