Monday, August 9, 2010

Sample "web service" for file upload and update metadata using C#

Here is a sample "web service" for file upload and update metadata for uploaded file in Moss 2007 using C# language.

using Microsoft.VisualBasic;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.Web;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.Configuration;
using System.Xml;
using System.Net;

[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[Microsoft.VisualBasic.CompilerServices.DesignerGenerated()]
public class Service : System.Web.Services.WebService
{
[WebMethod()]
public string HelloWorld()
{
return "Hello World";
}
[System.Web.Services.WebMethod(Description = "Upload files to Portal")]

public string sUploadandUpdateFiles(string sFolder)
{
string sSharedPath = ConfigurationManager.AppSettings("GlobalSharedPath");
sFolder = sSharedPath + sFolder;
int counter = 0;

Collection oCollFiles = null;
object vFromFile = null;
string sFromFile = null;
string UploadFileFlag = null;
string sToFile = null;
string UpdateListFlag = null;
string sSampleVal = "Test Value";
try {
oCollFiles = GetFileColl(ref sFolder);


if (oCollFiles.Count() > 0) {
foreach (object vFromFile_loopVariable in oCollFiles) {
vFromFile = vFromFile_loopVariable;
sFromFile = sFolder + "\\" + Convert.ToString(vFromFile);
sToFile = vFromFile;
bEnableVersion(true);
UploadFileFlag = UploadDocument(sFromFile, sToFile);
bEnableVersion(false);
UpdateListFlag = WSSUpdateFile(sToFile, sToFile, sSampleVal);
counter = counter + 1;
}
}
return counter + " Files moved";
} catch (Exception ex) {
return ex.Message;
}
}
private Collection GetFileColl(ref string sPath)
{
Collection functionReturnValue = null;
string sFile = null;
Collection oReturnColl = null;
oReturnColl = new Collection();
// ERROR: Not supported in C#: OnErrorStatement

sFile = FileSystem.Dir(sPath + "\\*.*");
do {
if (!string.IsNullOrEmpty(sFile)) {
oReturnColl.Add(sFile);
sFile = FileSystem.Dir();
}
} while (!(string.IsNullOrEmpty(sFile)));
errGetColl:

functionReturnValue = oReturnColl;
return;
return functionReturnValue;

}
[WebMethod()]

public string bEnableVersion(bool bEnable)
{
string sUser = ConfigurationManager.AppSettings("User");
string sPwd = ConfigurationManager.AppSettings("Pwd");
string sDomain = ConfigurationManager.AppSettings("Domain");
string sSPURL = ConfigurationManager.AppSettings("SharePointServer");
string sDocLib = ConfigurationManager.AppSettings("DocLibrary");
System.Net.NetworkCredential netAccess = new System.Net.NetworkCredential(sUser, sPwd, sDomain);
SPLists.Lists L = new SPLists.Lists();
L.Credentials = netAccess;
L.Url = sSPURL + "/_vti_bin/lists.asmx";

try {
XmlNode anode = L.GetList(sDocLib);
XmlDocument aXMLDoc = new XmlDocument();
XmlElement aXMLElement = aXMLDoc.CreateElement("List");
aXMLElement.SetAttribute("EnableVersioning", bEnable);

L.UpdateList(anode.Attributes("ID").Value, aXMLElement, null, null, null, anode.Attributes("Version").Value);

return "TRUE";

} catch (Exception ex) {
return Err.Description;
}


}
[WebMethod()]

public string CreateFolder(string sFolderName, bool sSAM)
{
string sSPURL = ConfigurationManager.AppSettings("SharePointServer");
string sDocLib = ConfigurationManager.AppSettings("DocLibrary");
string sUser = ConfigurationManager.AppSettings("User");
string sPwd = ConfigurationManager.AppSettings("Pwd");
string sDomain = ConfigurationManager.AppSettings("Domain");

System.Net.NetworkCredential netAccess = new System.Net.NetworkCredential(sUser, sPwd, sDomain);
DWS.Dws dwsService = new DWS.Dws();
dwsService.Url = sSPURL + "/_vti_bin/DWs.asmx";
dwsService.Credentials = netAccess;

try {
string strResult = null;
string strFolderComplete = sDocLib + sFolderName;
strFolderComplete = Strings.Replace(strFolderComplete, "\\", "/");
strResult = dwsService.CreateFolder(strFolderComplete);
if (IsDwsErrorResult(strResult)) {
int intErrorID = 0;
string strErrorMsg = null;
ParseDwsErrorResult(strResult, ref intErrorID, ref strErrorMsg);
if (intErrorID.ToString() == "13") {
return strFolderComplete;
return;
}
return ("A document workspace error occurred." + Constants.vbCrLf + "Error number: " + intErrorID.ToString() + Constants.vbCrLf + "Error description:" + strErrorMsg);
} else {
return strFolderComplete;
}
} catch (Exception exc) {
return ("An exception occurred." + Constants.vbCrLf + "Description: " + exc.Message);


}
}
private bool IsDwsErrorResult(string ResultFragment)
{
System.IO.StringReader srResult = new System.IO.StringReader(ResultFragment);
System.Xml.XmlTextReader xtr = new System.Xml.XmlTextReader(srResult);
xtr.Read();
if (xtr.Name == "Error") {
return true;
} else {
return false;
}
}

private void ParseDwsErrorResult(string ErrorFragment, ref int ErrorID, ref string ErrorMsg)
{
System.IO.StringReader srError = new System.IO.StringReader(ErrorFragment);
System.Xml.XmlTextReader xtr = new System.Xml.XmlTextReader(srError);
xtr.Read();
xtr.MoveToAttribute("ID");
xtr.ReadAttributeValue();
ErrorID = xtr.Value;
ErrorMsg = xtr.ReadString();
}

private string ParseDwsSingleResult(string ResultFragment)
{
System.IO.StringReader srResult = new System.IO.StringReader(ResultFragment);
System.Xml.XmlTextReader xtr = new System.Xml.XmlTextReader(srResult);
xtr.Read();
return xtr.ReadString();
}
[WebMethod()]
public string UploadDocument(string localFile, string remoteFile)
{
//// Read in the local file
// ERROR: Not supported in C#: OnErrorStatement

byte[] r = null;
System.IO.FileStream Strm = new System.IO.FileStream(localFile, System.IO.FileMode.Open, System.IO.FileAccess.Read);
System.IO.BinaryReader reader = new System.IO.BinaryReader(Strm);
byte[] filecontents = reader.ReadBytes(Convert.ToInt32(Strm.Length));
reader.Close();
Strm.Close();

string sSPURL = ConfigurationManager.AppSettings("SharePointServer");
string sDocLib = ConfigurationManager.AppSettings("DocLibrary");
string sUser = ConfigurationManager.AppSettings("User");
string sPwd = ConfigurationManager.AppSettings("Pwd");
string sDomain = ConfigurationManager.AppSettings("Domain");
string sRemoteFileURL = null;
System.Net.NetworkCredential NC = new System.Net.NetworkCredential(sUser, sPwd, sDomain);

sRemoteFileURL = sSPURL + "/" + sDocLib + "/" + Strings.Trim(Strings.LTrim(Strings.RTrim(remoteFile)));

sRemoteFileURL = Strings.Replace(sRemoteFileURL, " ", "%20");

sRemoteFileURL = Strings.Replace(sRemoteFileURL, "\\", "/");

WebClient m_WC = new WebClient();
m_WC.Credentials = NC;
r = m_WC.UploadData(sRemoteFileURL, "PUT", filecontents);

return "TRUE";

return;
handler:
return Err.Description;
}

public string WSSUpdateFile(string sFileName, string sSiteDoc, string sTestCol)
{
string sUser = ConfigurationManager.AppSettings("User");
string sPwd = ConfigurationManager.AppSettings("Pwd");
string sDomain = ConfigurationManager.AppSettings("Domain");

string sFileIDinList = null;
string strBatch = "";

sSiteDoc = Strings.Replace(sSiteDoc, "%20", " ");
sSiteDoc = Strings.Replace(sSiteDoc, "\\", "/");

string sFinalFilePath = null;

string sSPURL = ConfigurationManager.AppSettings("SharePointServer");
string sDocLib = ConfigurationManager.AppSettings("DocLibrary");
try {
System.Net.NetworkCredential netAccess = new System.Net.NetworkCredential(sUser, sPwd, sDomain);
SPLists.Lists listService = new SPLists.Lists();
listService.Url = sSPURL + "/_vti_bin/lists.asmx";
listService.Credentials = netAccess;

sFileIDinList = sGetID(listService.Url, sDocLib, sFileName);


if (!string.IsNullOrEmpty(sFileIDinList)) {
sFinalFilePath = sSPURL + "/" + sDocLib + "/" + sFileName;

//Now we have FileID so update the list


strBatch = "" + "" + sFileIDinList + "" + "" + sFinalFilePath + "" + "" + sTestCol + "" + "";

object xmlDoc = new System.Xml.XmlDocument();

System.Xml.XmlElement elBatch = xmlDoc.CreateElement("Batch");


elBatch.InnerXml = strBatch;


System.Xml.XmlNode ndreturn = listService.UpdateListItems(sDocLib, elBatch);

}

return "TRUE";

} catch (Exception ex) {
return ex.Message;
}


}

private string sGetID(string sURL, string sListGUID, string sFileName)
{
string sUser = ConfigurationManager.AppSettings("User");
string sPwd = ConfigurationManager.AppSettings("Pwd");
string sDomain = ConfigurationManager.AppSettings("Domain");

System.Net.NetworkCredential netAccess = new System.Net.NetworkCredential(sUser, sPwd, sDomain);
SPLists.Lists L = new SPLists.Lists();
L.Credentials = netAccess;
L.Url = sURL;

XmlDocument xmldoc = new XmlDocument();
XmlNode query = xmldoc.CreateNode(XmlNodeType.Element, "Query", "");
query.InnerXml = "\"";
try {
XmlNode caml = L.GetListItems(sListGUID, null, query, null, "1", null, null);
string id = caml.ChildNodes(1).ChildNodes(1).Attributes("ows_ID").Value;
return id;

} catch (Exception ex) {
return ex.Message;
}
}
}

No comments:

Post a Comment