Sending Data to Soap Service by SharePoint 2013 or SPD2013 - web-services

I have a SOAP service that takes a USERID and a Qualification Code and returns a Boolean(true) if the User was found and the Qualification Code was added to their name. Inside Visual Studio I had no problem writing a simple page that had 2 text boxes where I took the info from those text boxes and submitted it to the web service. I can't figure out how to do this inside SharePoint or SharePoint Designer both are 2013. I have followed these directions to add the service as a Data source but I'm unsure how to work with it.
The overall project is I have a training site and when an employee passes a test I want to pass the user and qualification to the SOAP web service to be updated in another environment. Yes it's duplicated info but it's how the company wants it. The information in SharePoint is stored in a list.
Edit
So I think I have to do it in ParameterBindings. If I just change the location to Controls(textboxid) I'm assuming this will call the web service with whatever is in these text boxes but so far it's not.
<parameterbindings>
<ParameterBinding Name="userID" Location="Control(UserIDTB)" DefaultValue="domain\user"/>
<ParameterBinding Name="qualificationCode" Location="Control(QualCode)" DefaultValue="PIT"/>
<ParameterBinding Name="dvt_apos" Location="Postback;Connection"/>
<ParameterBinding Name="ManualRefresh" Location="WPProperty[ManualRefresh]"/>
<ParameterBinding Name="UserID" Location="CAMLVariable" DefaultValue="CurrentUserName"/>
<ParameterBinding Name="Today" Location="CAMLVariable" DefaultValue="CurrentDate"/>
<ParameterBinding Name="dvt_firstrow" Location="Postback;Connection"/>
<ParameterBinding Name="dvt_nextpagedata" Location="Postback;Connection"/>
</parameterbindings>

So for me I couldn't figure out or maybe it's not possible to do this in SharePoint Designer. I had to create an Event Receiver inside Visual Studio that connects to SOAP service then sends Data from my list to that service. The completed code is below. I doubt I need all the additions at the top but I just left them as it was working.
using System;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Utilities;
using Microsoft.SharePoint.Workflow;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Net;
namespace CompletedTraining.TrainingCompleteListener
{
/// <summary>
/// List Item Events
/// </summary>
public class TrainingCompleteListener : SPItemEventReceiver
{
/// <summary>
/// An item was added.
/// </summary>
public override void ItemAdded(SPItemEventProperties properties)
{
//Item was just added to the list
base.ItemAdded(properties);
using (SPWeb web = properties.OpenWeb())
{
try
{
//get the item that was just added
SPListItem currentItem = properties.ListItem;
//create a new connection to the NavSoapService
NAVSoapService.EmployeeQualificationMgt service = new NAVSoapService.EmployeeQualificationMgt();
//Use the default credentials for this service
service.Credentials = CredentialCache.DefaultCredentials;
//convert the Name field from the list to a string we'll use to pass to the NavSoapService. We need the username(superb\user) instead of just name(first last) the next 3 lines do this conversion
string nameField = currentItem["Name"].ToString();
SPFieldUserValue userField = (SPFieldUserValue)currentItem.Fields["Name"].GetFieldValue(nameField);
SPUser user = userField.User;
//Once we have user id we need to get their login name(superb\user) and remove the 7 junk characters to the left
string loginName = (user.LoginName).Substring(7);
//Call the service with the login name and the Qualification code store the result in the result variable.
bool result = service.AddEmployeeQualification(loginName, (string)currentItem["Qualification Code"]);
//write the result in the Uploaded to NAV column
currentItem["Uploaded to NAV"] = result;
//update the current item in the list.
currentItem.Update();
}
catch (Exception ex)
{
throw ex;
}
}
}
}
}
Two other items needed and 1 is in your project you need to connect to the Web Service and 2 is to change the Elements.xml file if you only want this to have an affect on 1 list.
<!--<Receivers ListTemplateId="100">-->
<Receivers ListUrl="Lists/Completed Training">

Related

Crystal Report 2011 Report/SQL Server 2008/ASPX Issues

I have a webserver configured with ColdFusion 10. Within an application I have built in ColdFusion, I want to deploy a Crystal Report that requires a parameter that the user would enter. I built the report in Crystal Reports 2011. The report works within the Designer.
I then used Recrystallize to generate the ASPX, ASPX.VB, and Web.config pages that go with the report.
I had to adjust the IIS settings to accommodate the fact that ColdFusion requires the enabling of 32 bit applications and the Crystal Reports components require the disabling of 32 bit applications by putting the Crystal Report and pages in their own folder, converting them to an application and setting that application to a different Application Pool than the ColdFusion application.
The report viewer initially opened with the prompt for the parameter that the report was built on. When you entered the parameter and clicked OK, the report would error with a dialog of: Failed to open the connection. Failed to open the connection. [with the report name].
I am not sure where to begin troubleshooting this.
Any help that you can provide would be greatly appreciated.
this is aspx file.....
<asp:UpdatePanel ID="updpnlReport" runat="server">
<ContentTemplate>
<CR:CrystalReportViewer ID="crvAccountReportParameter" runat="server"
oninit="crvAccountReportParameter_Init"
EnableParameterPrompt="False" HasToggleParameterPanelButton = "false" HasCrystalLogo ="False"/>
</ContentTemplate>
</asp:UpdatePanel>
This is .cs fie..........
protected void btnSubmit_Click(object sender, EventArgs e)
{
LoadData();
}
protected void LoadData()
{
string pstrType;
pstrType = Request.QueryString["Type"];
string strCompanyName = objSession.SelCompanyName;
string strBranchName = objSession.SelBranchName;
string strHeading = "";
DataSet dsData = null;
dsData = objAccountReportBAL.getAccountRegister(Convert.ToInt16(objSession.FyId), int.MinValue, long.MinValue, Convert.ToDateTime(RadDtpFromDate.SelectedDate), Convert.ToDateTime(RadDtpToDate.SelectedDate), pstrType);
dsData.Tables[0].TableName = "Account_Trn_v";
if (pstrType == "JV")
{
strHeading = "Journal Voucher Register Report";
rptDoc.Load(Server.MapPath("~/ReportCrystal/Account/Detail/GeneralVoucharRegister.rpt"));
}
rptDoc.SetDataSource(dsData.Tables[0]);
rptDoc.SetParameterValue("#CompanyName", objSession.SelCompanyName);
rptDoc.SetParameterValue("#BranchName", objSession.SelBranchName);
rptDoc.SetParameterValue("#Heading", strHeading);
rptDoc.SetParameterValue("#Stdate", RadDtpFromDate.SelectedDate);
rptDoc.SetParameterValue("#EnDate", RadDtpToDate.SelectedDate);
crvAccountReportParameter.ReportSource = rptDoc;
crvAccountReportParameter.DataBind();
}

Deleting a file from sharepoint using web service

I am trying to delete a file from a sharepoint document library.
My application is in C#, which uses the web services of sharepoint.
Would like to know how this can be done.
Thanks in advance.
Delete a Document in SharePoint using Web Services
1.Add Web Reference to http://[your site]/_vti_bin/Lists.asmx
2.You need Document ID, Library Name, and Url to the document to be deleted
var spWebServiceLists = "http://[your site]/_vti_bin/Lists.asmx";
var listService = new Lists
{
Credentials = CredentialCache.DefaultCredentials,
Url = spWebServiceLists
};
string id = 10;
string library = #"Shared Documents";
string url = #"http://[your site]/Shared Documents/Test.docx";
string xml = "<Method ID='1' Cmd='Delete'>" +
"<Field Name='ID'>" + id + "</Field>" +
"<Field Name='FileRef'>" + HttpUtility.UrlDecode(url) + "</Field>" +
"</Method>";
/*Get Name attribute values (GUIDs) for list and view. */
System.Xml.XmlNode ndListView = listService.GetListAndView(library, "");
string strListID = ndListView.ChildNodes[0].Attributes["Name"].Value;
string strViewID = ndListView.ChildNodes[1].Attributes["Name"].Value;
/*Create an XmlDocument object and construct a Batch element and its
attributes. Note that an empty ViewName parameter causes the method to use the default view. */
System.Xml.XmlDocument doc = new System.Xml.XmlDocument();
System.Xml.XmlElement batchElement = doc.CreateElement("Batch");
batchElement.SetAttribute("OnError", "Continue");
batchElement.SetAttribute("ListVersion", "1");
batchElement.SetAttribute("ViewName", strViewID);
/*Specify methods for the batch post using CAML. To update or delete,
specify the ID of the item, and to update or add, specify
the value to place in the specified column.*/
batchElement.InnerXml = xml;
XmlNode item;
item = listService.UpdateListItems(library, batchElement);
I just tested this code and works well.
For more information please see following links
Lists.UpdateListItems Method
How to: Update List Items
If you work with SharePoint 2010, you can use CSOM to access SharePoint web services. This link could be helpful to execute crud operations. If you work with SharePoint 2013 there is also CSOM API, it has similar funcitonality as in 2010.

EventReceiver not Firing on SharePoint List

I am trying to create an EventReceiver for a blog site (for the Posts list) and am having some trouble getting it working. I want to change the Created By column to Anonymous. Basically I have this whole thing working in a console application, however, that will only change the Created By column names when the console application is executed.
I need it to change the Created By whenever a new item is added to the list. My code is below....how do I modify this to use in an EventReceiver project??? Since I already tell the EventReceiver project the URL I want the EventReceiver attached to, I'm not sure what I can remove from this code, right now it just doesn't do anything, no error and no changing of the Created By column when I debug.
using (SPSite site = new SPSite("http://test-sharepoint/subsite/"))
{
using (SPWeb web = site.OpenWeb())
{
SPList list = web.Lists["Posts"];
SPListItemCollection listItemCollection = list.Items;
foreach (SPListItem listItem in listItemCollection)
{
SPFieldUserValue userName = new SPFieldUserValue(web, 22, "Anonymous");
listItem["Author"] = userName;
listItem["Editor"] = userName;
listItem.Update();
}
web.Update();
}
}
EDIT: Code is in ItemAdded method
EDIT #2: This is trying the same code except without the loop and using properties.ListItem, this was my attempt in a Event Recevier project but no luck. It just doesn't change the Created By field, or any field for that matter (I tried the Title as well)
SPSite site = new SPSite("http://test-sharepoint/subsite/");
SPWeb web = site.OpenWeb();
SPFieldUserValue userName = new SPFieldUserValue(web, 22, "Anonymous");
properties.ListItem["Author"] = userName;
properties.ListItem["Editor"] = userName;
properties.ListItem.Update();
*Also from my understanding the SPFieldUserValue will grab either a User or a SharePoint User Group (Permissions) so in my code, the 22 grabs the SharePoint User Group that I want and "Anonymous" is the user from that group...
EDIT #3: More progress, this code works without issues for a list, however, not for the Posts or Comments lists, for those it does not change the Created By field. Could it be because of the approve/reject for all items??? Whether approved orpending it still does not show annonymous, BUT like I mentioned, it works fine in a different list.
public override void ItemAdded(SPItemEventProperties properties)
{
base.ItemAdded(properties);
SPSite site = new SPSite("http://test-sharepoint/hr/blog/"); //SPContext.Current.Site;
SPWeb web = site.OpenWeb();
SPFieldUserValue userName = new SPFieldUserValue(web,22,"Anonymous");
SPListItem currentItem = properties.ListItem;
//currentItem["Title"] = userName; //DateTime.Now.ToString();
currentItem["Author"] = userName;
currentItem["Editor"] = userName;
currentItem.SystemUpdate();
}
**EDIT #4: Alright I found my issue, when creating the project I chose Custom List as my list to attach to but I needed to choose Posts or Comments and now the above code works!!!
But now I have another problem, all posts on the blog are first submitted for approval...and due to this the event receiver doesn't seem to work for users other than the admin. It works fine for the admin account where I can just directly publish a post or comment but for a user with Contribute permissions whose posts are submitted for approval still shows their name on the Manage Posts page...what could I do about this? Any ideas?**
The code that works:
public override void ItemAdded(SPItemEventProperties properties)
{
base.ItemAdded(properties);
SPSite site = new SPSite("http://test-sharepoint/hr/blog/"); //SPContext.Current.Site;
SPWeb web = site.OpenWeb();
SPFieldUserValue userName = new SPFieldUserValue(web, 23, "Anonymous");
SPListItem currentItem = properties.ListItem;
currentItem["Author"] = userName;
currentItem["Editor"] = userName;
currentItem.SystemUpdate();
}
In response to edit #4, when working with SharePoint, if code works when executed by the administrator account, but does not work when executed by a "normal" account, permissions are likely to blame.
See the answer to the question SharePoint/WSS: Modify “created by” field? for an example of an SPItemEventReceiver that modifies the Author field.
Note: Many SharePoint developers recommend against the use of RunWithElevatedPrivileges and suggest using impersonation instead. See my answer to the question In which situation use SPSecurity.RunWithElevatedPrivileges with superusertoken? for more details.

Parsing XML webservice and storing the data for presentation on a windows phone 7 device

I'm working on an app that requires extracting data from an xml web service, then I want to store that data (images+titles+datetime ...) to display it on my app then select an item and navigate to another page that displays more info about this item.
Is there a detailed tutorial that explains the parsing and storing process clearly (with the threads) because I'm gonna need it a lot for my app.Thanks!
I usually use this method, but didn't always get me what i want:
var doc = XDocument.Load(new StringReader(e.Result));
var items = from c in doc.Descendants("item")
select new RSSitem()
{
Title = c.Element("title").Value,
Photo = c.Element("img").Attribute("src").Value,
Description = c.Element("description").Value,
Link = c.Element("link").Value,
};
ListBoxNews.ItemsSource = items;
Sounds like you are in over your head (based on the vague nature of your question). So I'm offering my advise to get up to speed, so you can get started and ask a question that we can help give a definitive answer to.
With WP7 and .NET you shouldn't really have to do much manual parsing of Web Services. You should be able to add a Service Reference and generate a proxy which will handle this for you. This will also generate business objects for the data returned by your service.
Once you have that done, you can look into Windows Phone Navigation which should help you transition between pages in your application.
To consume web services:
String baseUri = “your service URI";
WebClient wc = new WebClient();
public MainPage()
{
InitializeComponent();
wc.DownloadStringCompleted += new DownloadStringCompletedEventHandler(wc_downloadstringcompleted);
// event handler that will handle the ‘downloadstringsompleted’ event
wc.DownloadStringAsync(new Uri(baseUri));
// this method will download your string URI asynchronously
}
void wc_downloadstringcompleted(Object sender, DownloadStringCompletedEventArgs e)
{
// method will get fired after URI download completes
// writes your every code here
}
To parse the data:
using (XmlReader reader = XmlReader.Create(new StringReader(xmlString)))
{
while (reader.Read())
{
switch (reader.NodeType)
{
case XmlNodeType.Element:
break;
case XmlNodeType.Text:
break;
case XmlNodeType.EndElement:
break;
}
}
}
}
To store in isolated storage: http://msdn.microsoft.com/en-us/library/system.io.isolatedstorage.isolatedstoragesettings%28v=vs.95%29.aspx
For navigation:
NavigationService.Navigate(new Uri("/SecondPage.xaml?msg=" + navigationstring, UriKind.Relative));

AJAX AutocompleteExtender isn't working. Web Service works

This is c# .net 2.0. I am using a masterpage.
The WebService works fine on its own.
I am completely stumped. When I type in the TextBox, nothing happens.
Files:
EditTicket.aspx
AutoComplete.asmx
App_Code/AutoComplete.cs
EditTicket.aspx:
<%# Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="cc2" %>
<asp:ScriptManager id="ScriptManager1" runat="server" EnablepageMethods="true">
<Services>
<asp:ServiceReference Path="AutoComplete.asmx" />
</Services>
</asp:ScriptManager>
<cc2:AutoCompleteExtender
runat="server"
ID="AutoCompleteExtender1"
ServicePath="AutoComplete.asmx"
ServiceMethod="AutoComplete2"
MinimumPrefixLength="1"
CompletionSetCount="12"
TargetControlID="TextBox3"
EnableCaching="True" >
</cc2:AutoCompleteExtender>
<asp:TextBox ID="TextBox3" runat="server"></asp:TextBox>
AutoComplete.asmx:
<%# WebService Language="C#" CodeBehind="~/App_Code/AutoComplete.cs" Class="AutoComplete" %>
AutoComplete.cs:
using System;
using System.Web;
using System.Collections;
using System.Web.Services;
using System.Web.Script.Services;
using System.Web.Services.Protocols;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Configuration;
using System.Data;
/// <summary>
/// Summary description for AutoComplete
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[ScriptService]
public class AutoComplete : System.Web.Services.WebService {
public AutoComplete () {
//Uncomment the following line if using designed components
//InitializeComponent();
}
[WebMethod]
[ScriptMethod]
public string[] AutoComplete2(string prefixText,int count)
{
string conString = ConfigurationManager.ConnectionStrings["DB"].ConnectionString;
SqlConnection connection = new SqlConnection(conString);
connection.Open();
SqlParameter prm;
string sql = "Select program_name FROM CM_Programs WHERE program_name LIKE #prefixText";
SqlDataAdapter cmd = new SqlDataAdapter(sql, connection);
prm = new SqlParameter("#prefixText", SqlDbType.VarChar, 50);
prm.Value = prefixText+ "%";
cmd.SelectCommand.Parameters.Add(prm);
DataTable dt = new DataTable();
cmd.Fill(dt);
string[] items = new string[dt.Rows.Count];
int i = 0;
foreach (DataRow dr in dt.Rows)
{
items.SetValue(dr["program_name"].ToString(),i);
i++;
}
connection.Close();
return items;
}
}
"Nothing happens" is not an easy description to go on. When you say nothing happens, have you checked that
The server code is being hit for the
web service?
Your query is being executed and
returning results?
Your items array is being populated
correctly?
If "nothing" is that none of the above is happening, I would start checking that there are no javascript errors on the page and that your AutoComplete extender is rendering correctly (examine the page controls in a trace).
Try fiddling with the CompletionInterval property. I have used this control in the past and wasn't seeing the behavior I expected until I set the CompletionInterval to a much lower value. It defaults to 1000 (ms), I would give it a shot with a value of 1, just to see if everything is working as it should (and womp's steps should help to narrow down where the communication issues are happening) and if it does work, keep increasing the value until you hit a value that makes sense (1 ms sends a lot of requests to the server). Report back on what works and what doesn't.