Sunday, November 29, 2009
Upload file from Document library to FTP Server
{
try
{
// Get Current user and his last name
SPUser user = SPContext.Current.Web.CurrentUser;
username = user.Name;
smtpTo = user.Email;
strarray = username.Split(sepcomma);
userLastname = strarray[0].ToString();
//SPSecurity.RunWithElevatedPrivileges(delegate()
//{
//sharepoint site and web object
using (SPSite site = new SPSite(SPContext.Current.Site.Url.ToString() + "/Test"))
{
using (Microsoft.SharePoint.SPWeb web = site.OpenWeb())
{
SPList lstphoto = web.Lists["Test"];
web.AllowUnsafeUpdates = true;
string folderName;
int plenth = userLastname.Length - 1;
folderName = "Test" + "/" + userLastname.Substring(0, userLastname.Length - plenth);
SPFolder ImageFolder = web.GetFolder(folderName);
// Check whether sub folder is exist or not. If not, create folder in doc lib in user's last name first character format.
if (!ImageFolder.Exists)
{
SPFolderCollection myFolderCollection = web.GetFolder("PFPhyPic").SubFolders;
myFolderCollection.Add(userLastname.Substring(0, userLastname.Length - plenth));
}
// File input stream to read image and save it into document library
if (fileupload.PostedFile.ContentLength > 0)
{
Stream fStream;
SPFileCollection files = ImageFolder.Files;
fStream = fileupload.PostedFile.InputStream;
// Read file in a byte array
byte[] MyData = new byte[fStream.Length];
fStream.Read(MyData, 0, (int)fStream.Length);
strImagename = "123456.jpg";
SPFile filedata = files.Add(strImagename, MyData, true);
Int32 id = filedata.Item.ID;
strImagepath = SPContext.Current.Site.Url.ToString() + "/" + filedata.ServerRelativeUrl;
//update unique name
SPListItem lItemUser = null;
lItemUser = lstphoto.Items.GetItemById(id);
lItemUser["UniqueName"] = lblUID.Text;
lItemUser.Update();
lblMsg.Text = "Photo is uploaded successfully.";
btnCancel.Text = "Next =>";
// SPUtility.SendEmail(SPContext.Current.Web, false, false, useremailid, "Test Email", "Test");
//copy file to local server
try
{
System.IO.Directory.CreateDirectory("C:/FTPLOCALCOPY\\");
strlocalpath = @"C:/FTPLOCALCOPY/" + strImagename;
FileStream fs = new FileStream(strlocalpath, FileMode.Create);
BinaryWriter binaryWriter = new BinaryWriter(fs);
binaryWriter.Write(MyData);
binaryWriter.Close();
}
catch (Exception ex)
{
}
}
}
}
//});
}
catch (Exception ex)
{
lblMsg.Text = ex.Message.ToString();
}
}
public void uploadFileUsingFTP(string CompleteFTPPath, string CompleteLocalPath, string UName, string PWD, string domain)
{
try
{
//Create a FTP Request Object and Specfiy a Complete Path
FtpWebRequest reqObj = (FtpWebRequest)WebRequest.Create(CompleteFTPPath);
//Call A FileUpload Method of FTP Request Object
reqObj.Method = WebRequestMethods.Ftp.UploadFile;
//If you want to access Resourse Protected You need to give User Name and PWD
reqObj.Credentials = new NetworkCredential(UName, PWD, domain);
//FileStream object read file from Local Drive
FileStream streamObj = File.OpenRead(CompleteLocalPath);
//Store File in Buffer
byte[] buffer = new byte[streamObj.Length + 1];
//Read File from Buffer
streamObj.Read(buffer, 0, buffer.Length);
//Upload File to ftp://localHost/ set its object to nothing
reqObj.GetRequestStream().Write(buffer, 0, buffer.Length);
//Close FileStream Object Set its Value to nothing
streamObj.Close();
streamObj = null;
reqObj = null;
}
catch (Exception ex)
{
lblMsg.Text = ex.Message.ToString();
}
}
Wednesday, November 25, 2009
send an e-mail with attachment from SharePoint
I have used SPAdministrationWebApplication for used shaerpoint email credential and send email with attachement through system.net class.
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using Microsoft.SharePoint;
using System.IO;
using Microsoft.SharePoint.Utilities;
using System.Net.Mail;
using Microsoft.SharePoint.Administration;
using System.Net;
//Get the Sharepoint SMTP information from the SPAdministrationWebApplication
string smtpServer = SPAdministrationWebApplication.Local.OutboundMailServiceInstance.Server.Address;
string smtpFrom = SPAdministrationWebApplication.Local.OutboundMailSenderAddress;
//Create the mail message and supply it with from and to info
MailMessage mailMessage = new MailMessage(smtpFrom, smtpTo);
//Set the subject and body of the message
mailMessage.Subject = "Test";
mailMessage.Body = "test email .";
//Download the content of the file with a WebClient
WebClient webClient = new WebClient();
//Supply the WebClient with the network credentials of our user
webClient.Credentials = CredentialCache.DefaultNetworkCredentials;
//Download the byte array of the file
byte[] data = webClient.DownloadData(imagepath);
//Dump the byte array in a memory stream because
//we can write it to our attachment
MemoryStream memoryStreamOfFile = new MemoryStream(data);
//Add the attachment
//mailMessage.Attachments.Add(new System.Net.Mail.Attachment(memoryStreamOfFile, insert_filename_attachment, insert_content_type));
mailMessage.Attachments.Add(new System.Net.Mail.Attachment(memoryStreamOfFile, ImageName));
//, insert_content_type));
//Create the SMTP client object and send the message
SmtpClient smtpClient = new SmtpClient(smtpServer);
smtpClient.Host = "hostname";
//Delivery mothod which get attachement which size is more than 1 MB and immediately send email to user
smtpClient.Port = 2095;
smtpClient.DeliveryMethod = SmtpDeliveryMethod.PickupDirectoryFromIis;
smtpClient.Send(mailMessage);
Hopy this stuff is useful for every developer.
Tuesday, November 24, 2009
Sharepoint Development: Object Model vs Web Services
When you've to develop a custom solution based on WSS/MOSS, I see that sometimes there are doubts on what technology to use in order to interop with the Sharepoint platform: should I use the Sharepoint Object Model APIs or should I use Sharepoint Web Services?
Use the Sharepoint Object Model if your code will be executed on a Sharepoint server farm machine. This is the best way if the final application will run on the Sharepoint server or if you're developing a Sharepoint WebPart.
To work with the Sharepoint Object Model, Right-click your Visual Studio project and add a reference to the Microsoft.SharePoint.dll located on the following directory:
C:\program files\common files\microsoft shared\web server extensions\12\isapi
If you're planning to develop a custom application that needs to interact with Sharepoint from a remote client, the best way is to use Sharepoint Web Services (the object model is not designed to support Remoting).
Saturday, November 14, 2009
Using SPQuery to filter lists by User & Group Column
If you want to filter a list based on the value in the look up field that is of type ‘Person or Group’, We have to consider the following options:
- Filter by the User Name.
- Filter by SPUser ID Property
- Filter by Domain User account
Filter by the User Name:
By default the settings for the ‘Person or Group’ column will have the following settings.
The Show Field will have the “Name with Presence” selected.
When we run a SPQuery search on the list using the following code we will be able to filter the list based on the fullname of the user.
using (SPSite oSite = new SPSite("http://moss:80"))
{
using (SPWeb oWeb = oSite.OpenWeb())
{
oList = oWeb.Lists["Project Tasks"];
SPQuery query = new SPQuery();
query.Query = "<Where><Eq><FieldRef Name='AssignedTo' /><Value Type='User'>Tushar Parikh</Value></Eq></Where>";
SPListItemCollection items = oList.GetItems(query);
}
}
Filtering by SPUser ID :
If you want to filter the list based on the SPUser ID then follow the steps below.
- Add an additional attribute ‘LookupId’ for the queried field in your CAML query
<FieldRef Name='AssignedTo' LookupId='TRUE'/>
using (SPSite oSite = new SPSite("http://moss:80"))
{
using (SPWeb oWeb = oSite.OpenWeb())
{
oList = oWeb.Lists["Project Tasks"];
SPQuery query = new SPQuery();
query.Query = "<Where><Eq><FieldRef Name='AssignedTo' LookupId='TRUE'/><Value Type='User'>7</Value></Eq></Where>";
SPListItemCollection items = oList.GetItems(query);
}
}
Filtering by Domain User Account :
If you want to filter the list based on the Domain User Account then follow the steps below.
- Change the ‘Show Field’ Settings of the Person or Group lookup column to ‘Account’
Modify your code to include the domain account in the filter value.
using (SPSite oSite = new SPSite("http://moss:80"))
{
using (SPWeb oWeb = oSite.OpenWeb())
{
oList = oWeb.Lists["Project Tasks"];
SPQuery query = new SPQuery();
query.Query = "<Where><Eq><FieldRef Name='AssignedTo' /><Value Type='User'>komal\tparikh</Value></Eq></Where>";
SPListItemCollection items = oList.GetItems(query);
}
}
Sunday, November 1, 2009
Feature 'GUID' for list template 'XXX' is not installed in this farm. The operation could not be completed
We had a client receiving this message when accessing a site, and clicking Site Actions/Manage Content and Structure.
Install the Application Template Core Solution into the farm.
Link to Application Template Core Solution from Microsoft:
http://www.microsoft.com/downloads/details.aspx?FamilyId=C1039E13-94DA-4D7D-8CAE-3B96FA5A4045&displaylang=en
How to Install the Application Template Core solution (from Microsoft TechNet)
1. Download the Application Template Core solution to the server.
2. Double-click the .exe file to extract the files.
3. Open a Command Prompt window.
Note:
To open a Command Prompt window, click Start, point to All Programs, point to Accessories, and then click Command Prompt.
4. Type stsadm -o addsolution -filename \ApplicationTemplateCore.wsp, where is the location you extracted the Application Template Core files to, and then press ENTER.
5. Type stsadm -o deploysolution -name ApplicationTemplateCore.wsp -allowgacdeployment, and then press ENTER.
Note:
Additional attributes may be required based on your Windows SharePoint Services 3.0 configuration. For more information about available attributes, type stsadm -help deploysolution, and then press ENTER.
6. Type stsadm -o copyappbincontent, and then press ENTER.