Add List Item to Remote Sharepoint 2007 using Powershell - web-services

I am attempting to automatically add records to a list in Sharepoint. I am following along in this post
http://blogs.msdn.com/b/powershell/archive/2010/06/24/using-new-webserviceproxy-to-get-modify-and-add-items-to-a-list-in-sharepoint-2007.aspx
but keep receiving an error.
Code to date:
$packet = [System.Xml.Linq.XElement]::Parse(#"
<Batch OnError="Continue" ListVersion="1">
<Method ID="1" Cmd="New">
<Field Name="Checked At">2006-1-11T09:15:30Z</Field>
<Field Name="Cold">0</Field>
<Field Name="Inbox">0</Field>
</Method>
</Batch>
"#).Root;
$uri = "http://.../_vti_bin/Lists.asmx";
$listName = "Daily Check";
$lists = New-WebServiceProxy -Uri $uri -UseDefaultCredential;
$lists.UpdateListItems($listName,$packet);
This keeps returning the error:
Exception calling "UpdateListItems" with "2" argument(s): "Exception of type 'Microsoft.SharePoint.SoapServer.SoapServerException' was thrown."
At line:14 char:1
+ $lists.UpdateListItems($listName,$packet);
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : SoapException
There doesn't seem to be much other information in the error message.
Output from $lists
SoapVersion : Default
AllowAutoRedirect : False
CookieContainer :
ClientCertificates : {}
EnableDecompression : False
UserAgent : Mozilla/4.0 (compatible; MSIE 6.0; MS Web Services Client Protocol 4.0.30319.0)
Proxy :
UnsafeAuthenticatedConnectionSharing : False
Credentials : System.Net.SystemNetworkCredential
UseDefaultCredentials : True
ConnectionGroupName :
PreAuthenticate : False
Url : http:// ... /_vti_bin/Lists.asmx
RequestEncoding :
Timeout : 100000
Site :
Container :
Update
It appears that read methods are OK, but write is causing the error. Unfortunately, there just isn't enough information about the error to action it.

Your code seems to be fine except that you are sending the name of the list in parameter 1 to updatelistitems. We have similar code, but we use the listid in the first parameter.
To get the id of the list from the name of the list, do the following.
$listidandviewid = $lists.getlistandview($listname, "")
$listid = $listandviewid.childnodes.item(0).name
if you want the viewid as well you can also use.
$viewid = $listandviewid.childnodes.item(1).name
Then finally use the listid
$lists.UpdateListItems($listid,$packet);
Hope it works out for you!

Related

Passing token in header through variable getting an error of ParseException

Will try to be precise in asking question. Sorry if couldn't do it up to the mark!
Was given an assignment to automate api from the given below link
https://restful-booker.herokuapp.com/apidoc/index.html
Using the Api chaining I am suppose to automate "Update booking" api by first generating token from "Create Token" api and passing it in headers for authorization. I checked it on postman its working fine there for karate I wrote this code
* def auth_token = response.token
Given url 'https://restful-booker.herokuapp.com/booking/5591'
* def request_header = { Accept: '*/*' , Accept-Encoding : 'gzip, deflate, br' , Connection : 'keep-alive', Content-Type : 'application/json' , Accept : 'application/json' , Cookie : 'token=' + auth_token }
the variable auth_token is getting token from the first api response and under same scenario I am trying to run update api by using above headers but it keeps giving this error
net.minidev.json.parser.ParseException: Unexpected token + at position 168.
Could not find a valid solution so dropping question here.
I think you need to read and understand the docs, that's not how you set request headers. Here's what I think you were trying to do, and I hope that this helps others who try to use this "Restful Booker" application.
Feature:
Scenario:
* url 'https://restful-booker.herokuapp.com'
* path 'auth'
* request { username: 'admin', password: 'password123' }
* method post
* status 200
* def token = response.token
* header Accept = 'application/json'
* path 'booking'
* request
"""
{
"firstname" : "Jim",
"lastname" : "Brown",
"totalprice" : 111,
"depositpaid" : true,
"bookingdates" : {
"checkin" : "2018-01-01",
"checkout" : "2019-01-01"
},
"additionalneeds" : "Breakfast"
}
"""
* method post
* status 200
* path 'booking', response.bookingid
* cookie token = token
* method delete
* status 201

Get user's IP Address in Lambda (with API Gateway, and Python)

I was using this technique (How could I retrieve AWS Lambda public IP address by using Python?) but it gives the IPAddress of the Lambda Server within AWS.
Based on this: How can I retrieve a user's public IP address via Amazon API Gateway + Lambda (node), it looks like I should be able to use
ip_address = event['requestContext']['identity']['sourceIp'];
My handler starts like this:
def lambda_handler(event, context):
but if I do a pprint.pprint(event), I don't see any RequestContext in it, only the "body".
The last comment by FFXSam on the Jonathan answer says "It should be noted that event.requestContext.identity is not present if you're serving a page that's not behind an authorizer.".
I'm not sure what that means or why it is true. I'm using API Gateway, and JavaScript code on the client side is calling it.
I could ask the client coder to send me the local IP Address in the body, but it seems like I should be able to get it in the Lambda function itself.
Someone ask for the events, even though I said it only had the fields being passed in a json element called "body":
code:
print("pprint event:")
pprint.pprint(event)
2021-06-06T13:30:01.231-05:00 pprint event:
2021-06-06T13:30:01.231-05:00 {'body': {'ResponseTimeMilliseconds': 2225,
2021-06-06T13:30:01.231-05:00 'authToken': '12312312',
2021-06-06T13:30:01.231-05:00 'handNumber': 7}}
I rewarded bounty to Muzaffar Shaikh, but here I will give a more thorough explanation, which seems to be lacking on StackOverflow. His answer got the IP Address, but dropped my "body" field, but it certainly pointed me in the right direction.
In the AWS API Gateway tool, click "Resources" then your method (mine was "Post"), then click on "Integration Request" as shown here.
Scroll down to the bottom, and if there are not any templates, type in "application/json" and click the checkbox (note, "application/json" is there in light gray letters, but just clicking the checkbox without typing it doesn't work).
Then I put in the following template:
{
"client_ip" : "$input.params('X-Forwarded-For')",
"user_agent" : "$input.params('User-Agent')",
"body" : $input.json('$.body')
}
NOTE: if I put $input.json('$') or $input.json('body'), I ended up with a "body" field inside my "body" field, which broke the current logic.
When the web page was completed, it looked like this:
The next step is to redeploy your template to the "deploy stage" (environment) you were using.
By the way, when entering the template, if you click "Method Request passthrough" in the "Generate template" drop down box, it will generate a template like this (I didn't use this option, but will read more about it soon):
## See http://docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-mapping-template-reference.html
## This template will pass through all parameters including path, querystring, header, stage variables, and context through to the integration endpoint via the body/payload
#set($allParams = $input.params())
{
"body-json" : $input.json('$'),
"params" : {
#foreach($type in $allParams.keySet())
#set($params = $allParams.get($type))
"$type" : {
#foreach($paramName in $params.keySet())
"$paramName" : "$util.escapeJavaScript($params.get($paramName))"
#if($foreach.hasNext),#end
#end
}
#if($foreach.hasNext),#end
#end
},
"stage-variables" : {
#foreach($key in $stageVariables.keySet())
"$key" : "$util.escapeJavaScript($stageVariables.get($key))"
#if($foreach.hasNext),#end
#end
},
"context" : {
"account-id" : "$context.identity.accountId",
"api-id" : "$context.apiId",
"api-key" : "$context.identity.apiKey",
"authorizer-principal-id" : "$context.authorizer.principalId",
"caller" : "$context.identity.caller",
"cognito-authentication-provider" : "$context.identity.cognitoAuthenticationProvider",
"cognito-authentication-type" : "$context.identity.cognitoAuthenticationType",
"cognito-identity-id" : "$context.identity.cognitoIdentityId",
"cognito-identity-pool-id" : "$context.identity.cognitoIdentityPoolId",
"http-method" : "$context.httpMethod",
"stage" : "$context.stage",
"source-ip" : "$context.identity.sourceIp",
"user" : "$context.identity.user",
"user-agent" : "$context.identity.userAgent",
"user-arn" : "$context.identity.userArn",
"request-id" : "$context.requestId",
"resource-id" : "$context.resourceId",
"resource-path" : "$context.resourcePath"
}
}
Two reference for mapping templates:
https://docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-mapping-template-reference.html
https://docs.aws.amazon.com/apigateway/latest/developerguide/models-mappings.html
I still have some research to do as to when to user "$input.params" vs "$context.some_value".
You can try this:
Add the X-Forwarded-For to the "HTTP Request Headers" (goto the API-Gateway configuration -> Resources -> Method Request).
Add a Template with Content-Type: application/json (Resources -> Integration Request -> "Mapping Templates")
Add a Mapping to the template
{
"client_ip" : "$input.params('X-Forwarded-For')",
"user_agent" : "$input.params('User-Agent')"
}
Now the Headers are available in Lambda as expected:
event.client_ip
You can also refer to this link :
https://forums.aws.amazon.com/thread.jspa?messageID=648053
I spent a while pulling my hair out not finding how to add a mapping template in my integration request. Not sure what was happening but for anyone stumbling on this what i did was:
Check the Use Lambda Proxy integration checkbox in Integration Request.
Now i can access my headers very easily in my Python lambda function with event.["headers"].
Adding in screenshots to make it easier to find:
Go to Integration Request in the relevant method of your API. (See how i have already added the X-Forwarded-For header in Method Request, as recommended in other answers)
The checkbox is here:
(I did not have to make a mapping template. Really not sure what is going on here.)

google apps script ==> UrlFetchApp, method GET and cookie

I use the UrlFetchApp to send the user and pwd (method POST). After get the cookie, and use in other request (method GET). But this new request not working, I think that this cookie not has correct use in this new request. Can anyone help me?
var opt ={
"method":"post",
"User-Agent" : "Mozilla/5.0",
"Accept" : "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
"Accept-Language" : "en-US,en;q=0.5",
"payload": this.payload.toString(),
"followRedirects" : false
};
var response = UrlFetchApp.fetch("https://edas.info/addTopic.php?c=19349",opt);
var resp1=response.getContentText();
Logger.log(resp1);
response.getResponseCode();
var headers = response.getAllHeaders();
var cookies = headers['Set-Cookie'];
for (var i = 0; i < cookies.length; i++) {
cookies[i] = cookies[i].split( ';' )[0];
};
opt = {
"method" : "get",
"User-Agent" : "Mozilla/5.0",
"Accept" : "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
"Accept-Language" : "en-US,en;q=0.5",
"headers": {
"Cookie": cookies.join(';')
},
"followRedirects" : false
};
response = UrlFetchApp.fetch("https://edas.info/addTopic.php?c=19349", opt);
var resp1=response.getContentText();
Logger.log(resp1);
First off, thanks you for the snippet of code, this got me started with processing cookies in such script. I encountered an issue that was possibly your problem. Sometimes a Web page returns an array of cookies, and then your code works fine. Sometimes it returns a single string (instead of an array of one string). So I had to disambiguate with a test like:
if ( (cookies != null) && (cookies[0].length == 1) ) {
cookies = new Array(1);
cookies[0] = headers['Set-Cookie'];
}
I cannot give you specific help for your problem, one pointer though, as found here
Cookie handling in Google Apps Script - How to send cookies in header?
As https://stackoverflow.com/users/1435550/thierry-chevillard put it:
Be aware also that GAS uses Google IPs. It can happen that two consecutive fetch use different IPs. The server your are connecting to may be session-IP dependant.
Does your code run on the local development server and only fail once deployed to App Engine?
Or does it fail locally, as well?

How to invoke a web service call using vbscript

i am beginner in coding.
I have to call a web service below:
http://www.w3schools.com/webservices/tempconvert.asmx?op=CelsiusToFahrenheit
enter a value like 25 and click Invoke returns you the temperature in Fahrenheit.
For that i used below code:
url = "http://www.w3schools.com/webservices/tempconvert.asmx?op=CelsiusToFahrenheit&Celsius=25"
'Set oHttpReq = CreateObject("Microsoft.XMLHTTP") 'when i use XMLHTTP i am getting error saying "The download of the specified resource has failed."
Set oHttpReq = CreateObject("MSXML2.ServerXMLHTTP") 'If i use it, the response contains Root Element missing
oHttpReq.open "POST", url, False
oHttpReq.send
'Response
responseText = oHttpReq.responseText
WScript.echo responseText
Can anyone help me?
Create at file.vbs (visual basic script)
Compile with external tool to exe
In server task set this.
Const HOST = Sample service in IIS
Const URL = "wsPage.asmx"
Set xmlhttp = CreateObject("Microsoft.XMLHTTP")
xmlhttp.open "POST", HOST & URL & "/wsServiceTest", false
'Set the Content-Type header to the specified value
xmlhttp.setRequestHeader "Content-Type", "application/x-www-form-urlencoded"
' Send the request synchronously
xmlhttp.send ""
WScript.Echo "Load ok..."

Facebook Graph Batch, only takes top-level access_token

I'm using the Facebook Graph Batch API to send one message / different messages to registered people's FB walls.
I'm defining an access_token for each user, and the obliged top-level access_token (used as fallback, according to the doc). For the latter I just use an access_token from the users listed in the batch.
The thing is that the only user recieving the message, is the one who's access_token I used as the top-level/fallback access_token.
The other users get the "(#210) User not visible" error message.
I'm using 3 test users setup at my app-roles.
Any idea what goes wrong here?
Here's my code (python) for generating one message to all registrants:
for soc_reg in self.registrants:
batch_item = {
"method" : "POST",
"relative_url" : FACEBOOK_URL_FEED % (soc_reg['uid']),
"body" : Helper.toURL(publishParams),
"access_token" : soc_reg['access_token'],
}
batch.append(batch_item)
params = {
"access_token" : self.registrants[0]['access_token'], # used as fallback
"batch" : Helper.toJSON(batch),
}
results in following value for "params":
{"access_token": "XYZ", "batch": "[{\"body\": \"caption=&message=is+not+a+test.%0D%0AWe%27re+just+rappin%27+to+the+beat%21&place=146270405429726&link=&description=\", \"access_token\": \"XYZ\", \"method\": \"POST\", \"relative_url\": \"/100003720771245/feed\"}, {\"body\": \"caption=&message=is+not+a+test.%0D%0AWe%27re+just+rappin%27+to+the+beat%21&place=146270405429726&link=&description=\", \"access_token\": \"ZYX\", \"method\": \"POST\", \"relative_url\": \"/100003671211957/feed\"}, {\"body\": \"caption=&message=is+not+a+test.%0D%0AWe%27re+just+rappin%27+to+the+beat%21&place=146270405429726&link=&description=\", \"access_token\": \"YZX\", \"method\": \"POST\", \"relative_url\": \"/100003683601909/feed\"}]"}
So the only user recieving the message is the one defined here: "access_token" : self.registrants[0]['access_token']
When I adjust the index, I can determine the one recieving the message ;)
OK, seems like the documentation and the API itself are not corresponding:
https://developers.facebook.com/bugs/212455918831996
Documentation says:
relative_url => 'alias', 'body' => '{"access_token" => "..."}'
But only this ways seems to work:
'relative_url' => 'alias?access_token=...'
FB seemed to have confirmed the bug and put it on the 'wishlist', so far the latter is the way to go, works for me at least :)