Archive for the ‘EventHandlers’ Category


In an Item Adding event handler Properties.ListItem will be null. Same is the case with Properties.BeforeProperties & Properties.AfterProperties too. So how to get the values entered in the NewForm.aspx in the ItemAdding method. Here we go..

You can access the value using AfterProperties property. But here you have to pass the internal name of the column whose value you want to access.

properties.AfterProperties[“Internal Name of the column”]

Or in case if you don’t know/want to explicitly specify the internal name you can get the same using Field.InternalName property. The below code snippet I used explains the same.

typeName  = Convert.ToString(site.Lists[properties.ListId].Fields[“Type Of Shoes”].InternalName);
allotedShoeType = Convert.ToString(properties.AfterProperties[typeName]);

Hope it helps..


Advertisements

Event handler code to resize an an image when added as an attachment to a list item.

public override void ItemAdded(SPItemEventProperties properties)
{
     if (String.Compare(properties.ListTitle, “Brief Participant Details”, true) == 0)
    {
         SPSite siteColl = new SPSite(properties.SiteId);
         SPWeb site = siteColl.OpenWeb(properties.RelativeWebUrl);
         SPList listCFPrint = site.Lists[properties.ListTitle];
         ResizeImage resize = new ResizeImage();
         if (properties.ListItem.Attachments.Count > 0)
        {
              string fileName = properties.ListItem.Attachments[0].ToString();
              string strPath = properties.ListItem.Attachments.UrlPrefix + fileName;
              SPWeb web = new SPSite(properties.WebUrl).OpenWeb();
           
              //Get the item
             SPListItem item = properties.ListItem;

             //Get the folder
             SPFolder folder = web.Folders[“Lists”].SubFolders[properties.ListTitle].SubFolders[“Attachments”].SubFolders[item.ID.ToString()];
             SPFile file = folder.Files[0];
             byte[] binFile = file.OpenBinary();
             System.IO.FileStream fstream = System.IO.File.Create(“c:\\UploadedPhotos\\” + file.Name);
             fstream.Write(binFile, 0, binFile.Length);
             fstream.Close();

             //Resize the Image
             byte[] imgResized = resize.Resize(“C:\\UploadedPhotos\\” + fileName);

            //Delete the imag from the attachments
             properties.ListItem.Attachments.Delete(fileName);
 
             //Add the resized imaged to the attachments
             properties.ListItem.Attachments.Add(fileName, imgResized);
             properties.ListItem.Update();
             
             File.Delete(“C:\\UploadedPhotos\\” + fileName);
          }
     } 
}

\\\\ResizeImage.cs\\\\

using System;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.IO;

namespace PhotoResizeEventHandler
{
     class ResizeImage
     {
          public byte[] Resize(string ORIG_PHOTO_URL)
          {
                //Read the original photo in as a byte array
                byte[] rawData = File.ReadAllBytes(ORIG_PHOTO_URL);

               //Crop our file, pass in the new dimensions
               byte[] newImage = ResizeImageFile(rawData, 150);
              
               return newImage;
          }


          private static byte[] ResizeImageFile(byte[] imageFile, int targetSize)
          {
               Image original = Image.FromStream(new MemoryStream(imageFile));
               int targetH, targetW;
               if (original.Height > original.Width)
              {
                   targetH = targetSize;
                   targetW = (int)(original.Width * ((float)targetSize / (float)original.Height));
              }
              else
              {
                   targetW = targetSize;
                   targetH = (int)(original.Height * ((float)targetSize / (float)original.Width));
              }
             
              Image imgPhoto = Image.FromStream(new MemoryStream(imageFile));
        
              // Create a new blank canvas. The resized image will be drawn on this canvas.
              Bitmap bmPhoto = new Bitmap(targetW, targetH, PixelFormat.Format24bppRgb);
              bmPhoto.SetResolution(72, 72);
              Graphics grPhoto = Graphics.FromImage(bmPhoto);
              grPhoto.SmoothingMode = SmoothingMode.AntiAlias;
              grPhoto.InterpolationMode = InterpolationMode.HighQualityBicubic;
              grPhoto.PixelOffsetMode = PixelOffsetMode.HighQuality;
              grPhoto.DrawImage(imgPhoto, new Rectangle(0, 0, targetW, targetH), 0, 0, original.Width, original.Height, GraphicsUnit.Pixel);

              // Save out to memory and then to a file. We dispose of all objects to make sure the files don’t stay locked.
              MemoryStream mm = new MemoryStream();
              bmPhoto.Save(mm, System.Drawing.Imaging.ImageFormat.Jpeg);
              original.Dispose();
              imgPhoto.Dispose();
              bmPhoto.Dispose();
              grPhoto.Dispose();
              return mm.GetBuffer();
          }
     }

}



If you want to create an event handler for a list in sharepoint you need the template Id of that particular list. Here are the list of Id’s

GenericList 100
DocumentLibrary 101
Survey 102
Links 103
Announcements 104
Contacts 105
Events 106
Tasks 107
DiscussionBoard 108
PictureLibrary 109
DataSources 110
WebTemplateCatalog 111
UserInformation 112
WebPartCatalog 113
ListTemplateCatalog 114
XMLForm 115
MasterPageCatalog 116
NoCodeWorkflows 117
WorkflowProcess 118
WebPageLibrary 119
CustomGrid 120
DataConnectionLibrary 130
WorkflowHistory 140
GanttTasks 150
Meetings 200
Agenda 201
MeetingUser 202
Decision 204
MeetingObjective 207
TextBox 210
ThingsToBring 211
HomePageLibrary 212
Posts 301
Comments 302
Categories 303
IssueTracking 1100
AdminTasks 1200

Sharepoint Event Handlers

Posted: October 15, 2008 in EventHandlers, Videos

http://channel9.msdn.com/Shows/In+the+Office/Creating-and-Using-Event-Handlers-in-Windows-SharePoint-Services-V3


In SharePoint there is not any functionality for displaying our customized error page.Like if for data validation in event/item handler we use

properties.ErrorMessage = “Opps… Not allowed”;
properties.Cancel = true;

And validation message displayed in SharePoint error Page which looks error in application.
But with this Context you can use to redirect to any of your custom or any out of the box Page.

SPUtility.Redirect(Url, SPRedirectFlags.Default, current);

Here current is nothing but the HTTPContext object that u create in the constructor of the Event handler class