WebApplication to Delete file in Sharepoint - web-services

I am trying to delete a file in Sharepoint from my ASP.NET web application.
For which i have added List.asmx web reference which has Delete attachment method. This method has to be passed with three parameters.
DeleteAttachment(String ListName,String ListItemID, String url);
If my file location is below
http://example.com/sites/xxx/xxx/xxx/Shared Documents/yyy/zzz/Review comments_docx.doc
What would be the ListName, ListItemID, url.
Below is my code. Can anyone suggest also correct if i am doing anything wrong.
wsLists.Lists objList = new wsLists.Lists();
objList.Credentials = new NetworkCredential(GlobalVariablesBO.UserID, GlobalVariablesBO.Password, GlobalVariablesBO.Domain);
objList.Url = string.Concat("http://example.com/sites/xxx/xxx/xxx/_vti_bin/lists.asmx");
string url = Convert.ToString(item.GetDataKeyValue("SharePointURL"));
objList.DeleteAttachment("Shared Documents", "3", url);

UpdateListItems(String ListName, XMLNode updates)
is a actual method to delete a document in sharepoint.

Related

Rally Web Services API: How do I get the URL link of the user story? (getDetailUrl() method)

Please be patient and Do Not flag this as duplicate: Using the Rally REST API, how can I get the non-API (website) URL for a user story?
I want to be able to generate a link for the user story.
Something like this: https://rally1.rallydev.com/#/-/detail/userstory/*********
As opposed to this: https://rally1.rallydev.com/slm/webservice/v2.0/hierarchicalrequirement/88502329352
The link will be integrated into another application for the managers to see the user story.
I did read about the getDetailUrl() method, but in my case I am creating the user stories by parsing email and linking that to a notification service in Slack.
I am aware of the formattedID and (_ref), but I would have to query for it again, and I am creating batches of userstories through a loop. I need the actual web site link to the user story.
Here is my sample code:
public void CreateUserStory(string workspace, string project, string userstoryName){
//authenticate with Rally
this.EnsureRallyIsAuthenticated();
//DynamicJsonObject for HierarchicalRequirement
DynamicJsonObject toCreate = new DynamicJsonObject();
toCreate[RallyConstant.WorkSpace] = workspace;
toCreate[RallyConstant.Project] = project;
toCreate[RallyConstant.Name] = userstoryName;
try
{
//Create the User Story Here
CreateResult createUserStory = _api.Create(RallyConstant.HierarchicalRequirement, toCreate);
Console.WriteLine("Created Userstory: " + "URL LINK GOES HERE");
}
catch (WebException e)
{
Console.WriteLine(e.Message);
}
}
We don't have a method in the .NET toolkit for doing this, but it's easy to create.
The format is this:
https://rally1.rallydev.com/#/detail/<type>/<objectid>
Just fill in the type (hierarchicalrequirement turns into userstory, but all the others are the same as the wsapi type) and the objectid from the object you just created.
var parameters = new NameValueCollection();
parameters["fetch"] = "FormattedID";
var toCreate = new DynamicJsonObject();
var createResult = restApi.create("hierarchicalrequirement", toCreate, parameters);
var type = Ref.getTypeFromRef(createResult.Reference);
var objectID = Ref.getOidFromRef(createResult.Reference);
var formattedID = createResult.Object["FormattedID"];
And you can specify fetch fields to be returned on the created object so you don't have to re-query for it.

how to display absolute url of a websevice in play framework

I am new to play framework. I am having a web service url. To that url I am appending some parameters. I want display that url after appending the values to that url.
Here is my code:
public JsonNode getCustomerDetails(CustomerDto customerDto){
String feedUrl = Constants.ERP_CUSTOMER_URL;
WSRequestHolder wsHolder = null;
wsHolder = WS.url(feedUrl);
wsHolder.setAuth(Constants.ERPUSERNAME, Constants.ERPPASSWORD,Realm.AuthScheme.BASIC);
whereClause.append("mobileno='").append(customerDto.getMobile()).append("'")
.append(ORDER_BY_UPDATED_ASC);
wsHolder.setQueryParameter(_WHERE, whereClause.toString());``
F.Promise<WS.Response> response = wsHolder.get();
json = response.get().asJson();
}
Constants.ERP_CUSTOMER_URL is my webservice url to that I am appending mobileno. I want to display the absolute url of my webservice after appending the values to it. I tried to display wsHolder but it is displaying as play.libs.WS$WSRequestHolder#6afe06a7
You can see it with getUri() on the WS.Response object like:
response.get().map((Function) response -> {
System.out.println(response.getUri());
}
);

Springs RestTemplate doesn't find the right MessageConverter when reciving data from the IMDB api

first I have to say, that I am pretty new to Springs RestTemplate.
I am trying to receive data from the imdb-api. (For example http://imdbapi.org/?title=Avatar&type=xml) Therefore I am using Springs RestTemplate.
But:
the webservice returns the data as application/octet-stream (even I declared that I want it as xml (when I browse the site with my browser I get the data as text/xml))
RestTemplate doesn't find my declared ByteArrayMessageConverter (to convert application/octet-stream)
I realy don't know where my mistakes are.
Here is the code to initialise the restTemplate:
public void onInit() {
_log.debug("Setting up the Spring Resttemplate");
_restTemplate = new RestTemplate();
List<HttpMessageConverter<?>> list = new ArrayList<HttpMessageConverter<?>>();
list.add(new SourceHttpMessageConverter<Source>());
list.add(new ByteArrayHttpMessageConverter());
_restTemplate.setMessageConverters(list);
_log.debug("Setting up the HTTP Headers for Restrequest");
List<MediaType> acceptableMediaTypes = new ArrayList<MediaType>();
_log.trace("allow {}", MediaType.APPLICATION_XML_VALUE);
acceptableMediaTypes.add(MediaType.APPLICATION_XML);
_log.trace("allow {}", MediaType.TEXT_HTML_VALUE);
acceptableMediaTypes.add(MediaType.TEXT_XML);
_log.trace("set accepted charset to uft-8");
List<Charset> acceptableCharsets = new ArrayList<Charset>();
acceptableCharsets.add(Charset.forName("utf-8"));
_httpHeaders = new HttpHeaders();
_httpHeaders.set("User-Agent", "something"); //only a user-agent, because the api returns a 403 if it is not set
_httpHeaders.setAcceptCharset(acceptableCharsets);
_httpHeaders.setAccept(acceptableMediaTypes);
}
Here is the code with the call:
_log.info("connect to Imdb-Webservice {}", _imbdWebserviceBaseUrl);
Map<String, Object> uriVariables = new HashMap<String, Object>();
uriVariables.put("title", pTitle);
ResponseEntity<Source> response = _restTemplate.exchange(_imbdWebserviceBaseUrl, HttpMethod.GET, new HttpEntity<String>(_httpHeaders), Source.class, uriVariables);
_imbdWebserviceBaseUrl is set to http://imdbapi.org/?title={title}&type=xml
Then I am getting this error message:
org.springframework.web.client.RestClientException: Could not extract response: no suitable HttpMessageConverter found for response type [interface javax.xml.transform.Source] and content type [application/octet-stream]
at org.springframework.web.client.HttpMessageConverterExtractor.extractData(HttpMessageConverterExtractor.java:107)
at org.springframework.web.client.RestTemplate$ResponseEntityResponseExtractor.extractData(RestTemplate.java:687)
at org.springframework.web.client.RestTemplate$ResponseEntityResponseExtractor.extractData(RestTemplate.java:673)
at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:491)
at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:454)
at org.springframework.web.client.RestTemplate.exchange(RestTemplate.java:401)
at my.domain.projectname.integrationimpl.WebserviceHelper.getXml(WebserviceHelper.java:131)
Thanks for your help
the web service returns the data as application/octet-stream (even I declared that I want it as xml (when I browse the site with my browser I get the data as text/xml))
As far as I can see this rest service is not giving back the correct Content-Type (text/xml or similar). If your browser renders it correctly that's probably Chrome or Firefox, but IE will just show you html-ish kind of output.
RestTemplate doesn't find my declared ByteArrayMessageConverter (to convert application/octet-stream)
Well you are asking for a Source as far as I can see:
ResponseEntity<Source> response = _restTemplate.exchange(_imbdWebserviceBaseUrl, HttpMethod.GET, new HttpEntity<String>(_httpHeaders), Source.class, uriVariables);
The MessageConverters themselves have a method that determines if this converter is applicable, for ByteArrayHttpMessageConverter this is:
#Override
public boolean supports(Class<?> clazz) {
return byte[].class.equals(clazz);
}
Since you are asking for a Source.class it wont use this converter.

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.