How
to Create an ASMX Web Service on SharePoint 2010, Using Visual Studio 2010
Back in SharePoint 2007, asmx web
services were quite prevalent, thanks to the WSPBuilder tool, and it’s
templates. They are useful for executing actions between multiple
web applications and can be used by client applications, as well.
Furthermore, InfoPath forms, deployed to SharePoint, could also use these asmx
web services.
Unfortunately, Visual Studio 2010 did
not come with a template for SharePoint web services. So, today I will be
writing about how we can create asmx web services for SharePoint 2010.
All you will need is SharePoint 2010.
First, start a new Empty SharePoint
2010 project. I will call this SPASMXService.
Make sure to deploy it as a farm
solution.
First, you need to close this project
by right clicking on the project and then selecting ‘unload project’.
Then, right click on the project again,
and select, ‘Edit SPASMXService’.
Under
<SandboxedSolution>False</SandboxedSolution> type
in:
<TokenReplacementFileExtensions>asmx</TokenReplacementFileExtensions>
This
will be the result:
Then, save and close
out of this xml file. This will allow Visual Studio to insert the
solution information where necessary. Therefore, this is a crucial
step! Finally, reload the project file.
Next,
we will be creating the web service. Right click on the project, and
select “Add” and then select “New Class…” This will be the code
behind. Let’s just call this SPASMXService.cs.
Now,
open SPASMXService.cs, and make the following changes:
namespace Test
{
[System.ComponentModel.ToolboxItem(false)]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1), WebService(Namespace = "http://www.tempuri.org/")]
[System.Web.Script.Services.ScriptService]
public class PatientDoc_webservice : System.Web.Services.WebService
{
[WebMethod(EnableSession = true,
Description = "Typical Web Method")]
public List<string> Helloworld(string
prefixText, string contextKey)
{
List<string>
ss = new List<string>();
SPSite spSite; SPWeb
spWeb; SPList spList;
DataTable dtCareGiverFile = new DataTable();
DataSet dtcare = new
DataSet();
dtCareGiverFile.TableName = "testname";
spSite = SPContext.Current.Site;
if (contextKey != null)
{
SPSecurity.RunWithElevatedPrivileges(delegate()
{
spSite.AllowUnsafeUpdates = true;
using (spWeb = spSite.OpenWeb())
{
spWeb.AllowUnsafeUpdates = true;
spList = spWeb.Lists["PatientDocuments"];
var query = from SPListItem item in
spList.Items
where Convert.ToString(item["PatientID"]).Equals(contextKey)
select item;
dtCareGiverFile.Columns.Add("FileName");
dtCareGiverFile.Columns.Add("Length");
dtCareGiverFile.Columns.Add("FileData");
dtCareGiverFile.Columns.Add("ID");
dtCareGiverFile.Columns.Add("CreatedBy");
dtCareGiverFile.Columns.Add("CreatedDate");
if
(query != null)
{
foreach (var item in query)
{
SPAttachmentCollection attachments =
item.Attachments;
foreach (var itemA in attachments)
{
var t =
attachments[0].ToLower().StartsWith(prefixText.ToLower());
if (t == true)
{
DataRow dr = dtCareGiverFile.NewRow();
String attachmentAbsoluteURL =
attachments.UrlPrefix + itemA;
SPFile attachmentFile =
spWeb.GetFile(attachmentAbsoluteURL);
int filelength = Convert.ToInt32(attachmentFile.Length
/ 1024);
dr["ID"] = item.ID;
dr["Length"] = filelength;
dr["FileName"] = itemA;
ss.Add(Convert.ToString(itemA));
dr["FileData"] =
attachmentAbsoluteURL.ToString();
dr["CreatedBy"] = Convert.ToString(item["UploadedBy"]);
dr["CreatedDate"] = item["Created"];
dtCareGiverFile.Rows.Add(dr);
}
}
}
}
spWeb.AllowUnsafeUpdates = false;
}
spSite.AllowUnsafeUpdates = false;
});
}
return ss;
}
public DataTable
GetDocuments(string prefixText,string contextKey,string
Discipline)
{
SPSite spSite; SPWeb
spWeb; SPList spList;
SPList spList1; SPList
spList2;
DataTable dtCareGiverFile = new DataTable();
SPSecurity.RunWithElevatedPrivileges(delegate()
{
using (spSite = new
SPSite(SPContext.Current.Site.Url))
{
spSite.AllowUnsafeUpdates = true;
using (spWeb = spSite.OpenWeb())
{
spWeb.AllowUnsafeUpdates
= true;
spList = spWeb.Lists["PatientDocuments"];
spList1 = spWeb.Lists["ActiveDirectoryUserList"];
spList2 = spWeb.Lists["CareGiverProfile"];
dtCareGiverFile.Columns.Add("FileName");
dtCareGiverFile.Columns.Add("Length");
dtCareGiverFile.Columns.Add("FileData");
dtCareGiverFile.Columns.Add("ID");
dtCareGiverFile.Columns.Add("CreatedBy");
dtCareGiverFile.Columns.Add("CreatedDate");
dtCareGiverFile.Columns.Add("Discipline");
var query = from SPListItem item in
spList.Items
where Convert.ToString(item["PatientID"]).Equals(contextKey)
select item;
if (query != null)
{
foreach (var item in query)
{
SPAttachmentCollection attachments =
item.Attachments;
foreach (var itemA in attachments)
{
string attname = attachments[0].ToLower();
var t =
attachments[0].ToLower().StartsWith(prefixText.ToLower());
if (t == true)
{
DataRow dr =
dtCareGiverFile.NewRow();
String attachmentAbsoluteURL =
attachments.UrlPrefix + itemA;
SPFile attachmentFile =
spWeb.GetFile(attachmentAbsoluteURL);
int filelength = Convert.ToInt32(attachmentFile.Length
/ 1024);
dr["ID"] = item.ID;
dr["Length"] = filelength;
dr["FileName"] =Convert.ToString(itemA);
dr["FileData"] =
attachmentAbsoluteURL.ToString();
dr["CreatedBy"] = Convert.ToString(item["UploadedBy"]);
// dr["Discipline"] = Discipline;
string hdndis = Convert.ToString(item["UploadedBy"]);
if(Convert.ToString(item["UploadedBy"])=="system")
{
dr["Discipline"] = "Admin Group";
}
var query1 = from
SPListItem item1 in
spList1.Items
where Convert.ToString(item1["UserLogonName"]).Equals(hdndis)
select item1;
if (query1 != null)
{
foreach
(var item1 in
query1)
{
string s = Convert.ToString(item1["UserType"]);
if (Convert.ToInt32(s)
== 1)
{
dr["Discipline"] = "Admin Group";
}
if (Convert.ToInt32(s)
== 2)
{
dr["Discipline"] = "Agency Group";
}
if (Convert.ToInt32(s)
== 3 || Convert.ToInt32(s) == 4)
{
var query2 = from
SPListItem item2 in
spList2.Items
where Convert.ToString(item2["UserName"].ToString().Split('\\').GetValue(1).ToString()).Equals(hdndis)
select item2;
if (query2 != null)
{
foreach (var item2 in query2)
{
string hdndisid = Convert.ToString(item2["Discipline"]);
if (Convert.ToInt32(hdndisid)
== 1 || Convert.ToInt32(hdndisid) == 2)
{
dr["Discipline"] = "OT";
}
if (Convert.ToInt32(hdndisid)
== 3 || Convert.ToInt32(hdndisid) == 4)
{
dr["Discipline"] = "PT";
}
if (Convert.ToInt32(hdndisid)
== 5 || Convert.ToInt32(hdndisid) == 6)
{
dr["Discipline"] = "SP";
}
}
}
}
}
}
dr["CreatedDate"] = item["Created"];
dtCareGiverFile.Rows.Add(dr);
}
}
}
}
}
}
});
return dtCareGiverFile;
}
public bool
DeleteFileByID(string TicketID, bool IsDel)
{
SPSite spSite; SPWeb
spWeb; SPList spList;
SPSecurity.RunWithElevatedPrivileges(delegate()
{
using (spSite = new
SPSite(SPContext.Current.Site.Url))
{
spSite.AllowUnsafeUpdates = true;
using (spWeb = spSite.OpenWeb())
{
spWeb.AllowUnsafeUpdates = true;
spList = spWeb.Lists["PatientDocuments"];
SPListItem myItem = spList.GetItemById(Convert.ToInt32(TicketID));
if (myItem != null)
{
myItem.Delete();
IsDel = true;
}
spWeb.AllowUnsafeUpdates = false;
}
spSite.AllowUnsafeUpdates = false;
}
}
);
return IsDel;
}
This
is a good start for a web service with a web method. Now, of course we
have a few errors because we still have not brought in the necessary
libraries. Right click on ‘references’ in the Solution Explorer, and
select, ‘Add Reference’. Select System.Web.Services from the .NET
tab. Then, in SPASMXService.cs, add, ‘using System.Web.Services’.
This should look like this:
Finally,
we have to create the service page. I like to keep it in the _layouts
folder, but you can keep it elsewhere using similar steps. Right click on
the project item in the solution explorer, and select add -> SharePoint
“Layouts” Mapped Folder.
You
can also select SharePoint Mapped Folder, and then select ISAPI. This
would cause the page to go into _vti_bin instead.
For
now, I’m going to stick to _layouts:
The
SPASMXService folder was automatically made. Nice.
Inside
the SPASMXService, under Layouts, we will add a new file of type xml. We
Shall call it SPASMXService.asmx.
The
contents of SPASMXService.asmx will be a single line:
<%@ WebService Language=”C#” Debug=”true” Class=”[Class path], $SharePoint.Project.AssemblyFullName$”
%>
Where [class path] is
the full namespace name of the SPASMXService class in SPASMXService.cs.
In my case, the line will be:
namespace Test
{
[System.ComponentModel.ToolboxItem(false)]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1), WebService(Namespace = "http://www.tempuri.org/")]
[System.Web.Script.Services.ScriptService]
public class PatientDoc_webservice : System.Web.Services.WebService
{
[WebMethod(EnableSession = true,
Description = "Typical Web Method")]
public List<string> Helloworld(string
prefixText, string contextKey)
{
List<string>
ss = new List<string>();
SPSite spSite; SPWeb
spWeb; SPList spList;
DataTable dtCareGiverFile = new DataTable();
DataSet dtcare = new
DataSet();
dtCareGiverFile.TableName = "testname";
spSite = SPContext.Current.Site;
if (contextKey != null)
{
SPSecurity.RunWithElevatedPrivileges(delegate()
{
spSite.AllowUnsafeUpdates = true;
using (spWeb = spSite.OpenWeb())
{
spWeb.AllowUnsafeUpdates = true;
spList = spWeb.Lists["PatientDocuments"];
var query = from SPListItem item in
spList.Items
where Convert.ToString(item["PatientID"]).Equals(contextKey)
select item;
dtCareGiverFile.Columns.Add("FileName");
dtCareGiverFile.Columns.Add("Length");
dtCareGiverFile.Columns.Add("FileData");
dtCareGiverFile.Columns.Add("ID");
dtCareGiverFile.Columns.Add("CreatedBy");
dtCareGiverFile.Columns.Add("CreatedDate");
if (query != null)
{
foreach (var item in query)
{
SPAttachmentCollection attachments =
item.Attachments;
foreach (var itemA in attachments)
{
var t =
attachments[0].ToLower().StartsWith(prefixText.ToLower());
if (t == true)
{
DataRow dr = dtCareGiverFile.NewRow();
String attachmentAbsoluteURL =
attachments.UrlPrefix + itemA;
SPFile attachmentFile =
spWeb.GetFile(attachmentAbsoluteURL);
int filelength = Convert.ToInt32(attachmentFile.Length
/ 1024);
dr["ID"] = item.ID;
dr["Length"] = filelength;
dr["FileName"] = itemA;
ss.Add(Convert.ToString(itemA));
dr["FileData"] =
attachmentAbsoluteURL.ToString();
dr["CreatedBy"] = Convert.ToString(item["UploadedBy"]);
dr["CreatedDate"] = item["Created"];
dtCareGiverFile.Rows.Add(dr);
}
}
}
}
spWeb.AllowUnsafeUpdates = false;
}
spSite.AllowUnsafeUpdates = false;
});
}
return ss;
}
Finally, save
everything, and then deploy the solution.
If
everything went right, you should see this using Internet Explorer:
If
you used ISAPI instead of Layouts, _layouts in that screenshot should be
_vti_bin, instead. If you opened this from a front end server with web
service, then you can further test this web service by clicking on that link.
Lastly,
a bit of trouble shooting; you can check on the web service page by going to:
C:\Program
Files\Common Files\Microsoft Shared\Web Server Extensions\14\TEMPLATE\LAYOUTS
If
you used ISAPI instead of LAYOUTS, then instead go to:
C:\Program
Files\Common Files\Microsoft Shared\Web Server Extensions\14\ISAPI
If
the web service does not load on Internet explorer, then you should open the
asmx page from one of these two locations. If you open the asmx page from
one of these two locations, and you still find “$SharePoint.Project.AssemblyFullName$”,
then you need to go back to the top of this article and follow the steps
regarding unloading and reloading the project.
I appreciated your work very thanks
ReplyDeleteSharepoint helpdesk
great post..
ReplyDeleteเว็บไทเกอร์