I am trying to connect to ICloud calendars and parse events I can do that if I use the public calendar url and it works fine. However doing that I cannot update the event for that I need CalDav connection.
I am struggling as most of the examples here return 404 Not Found.
Can anyone please guide me "ICloud Caldav connection to get Calendars " in C# a sample or working example.
Keeping in mind the for the above I will only have Username and Password for the account so with that provided I have to load list of Calendar's.
Found this article very helpful in achieving the task:
Sample code:
static string calendarURI = "https://caldav.icloud.com/";
static string username = "abc#icloud.com";
static string password = "xxxx-xxxx-xxxx-xxxx";
//static string content = "<?xml version=\"1.0\" encoding=\"utf-8\"?><propfind xlmns=\"DAV:\"><allprop/></propfind>";
static string content = "<propfind xmlns='DAV:'><prop><current-user-principal/></prop></propfind>";
public async static void GetCalendars()
{
try
{
ResponseStream = ExectueMethod(username, password, calendarURI, "PROPFIND", null, content, "application/x-www-form-urlencoded","0");
XmlDocument = new XmlDocument();
XmlDocument.Load(ResponseStream);
string xmlInner = XmlDocument.InnerXml;
XmlDocument innerXmlDocument = new XmlDocument();
innerXmlDocument.LoadXml(xmlInner);
XmlNode statusCheck = innerXmlDocument.GetElementsByTagName("status")[0];
if (statusCheck != null)
{
string status = statusCheck.InnerText.Trim();
if (status == "HTTP/1.1 200 OK")
{
XmlNode tag = innerXmlDocument.GetElementsByTagName("current-user-principal")[0];
if (tag != null)
{
XmlNode taghref = tag.ChildNodes[0];
if (taghref != null)
{
string href = taghref.InnerText.Trim();
string baseUrl = "https://caldav.icloud.com" + href;
Console.WriteLine("BASSE URL :" + baseUrl);
content = "<propfind xmlns='DAV:' xmlns:cd='urn:ietf:params:xml:ns:caldav'><prop><cd:calendar-home-set/></prop></propfind>";
ResponseStream = ExectueMethod(username, password, baseUrl, "PROPFIND", null, content, "application/x-www-form-urlencoded","0");
XmlDocument = new XmlDocument();
XmlDocument.Load(ResponseStream);
xmlInner = XmlDocument.InnerXml;
innerXmlDocument = new XmlDocument();
innerXmlDocument.LoadXml(xmlInner);
tag = innerXmlDocument.GetElementsByTagName("calendar-home-set")[0];
if (tag != null)
{
taghref = tag.ChildNodes[0];
if (taghref != null)
{
string calURL = taghref.InnerText.Trim();
Console.WriteLine("CALENDER URL :" + calURL);
content = "<propfind xmlns='DAV:'><prop><displayname/><getctag />calendar-data</prop></propfind>";
ResponseStream = ExectueMethod(username, password, calURL, "PROPFIND", null, content, "application/x-www-form-urlencoded","1");
XmlDocument = new XmlDocument();
XmlDocument.Load(ResponseStream);
xmlInner = XmlDocument.InnerXml;
innerXmlDocument = new XmlDocument();
innerXmlDocument.LoadXml(xmlInner);
int xx = 0;
foreach (XmlNode row in innerXmlDocument.GetElementsByTagName("response"))
{
if (xx > 0)
{
string calhrefUrlfinal = row.InnerXml.Remove(row.InnerXml.IndexOf("</href>"));
calhrefUrlfinal = calhrefUrlfinal.Replace("<href xmlns=\"DAV:\">", "");
string Calname = row.InnerXml.Remove(row.InnerXml.IndexOf("</displayname>"));
Calname = Calname.Remove(0, Calname.IndexOf("<displayname>")).Replace("<displayname>", "").Trim();
string statusx = row.InnerXml.Remove(row.InnerXml.IndexOf("</status>"));
statusx = statusx.Remove(0, statusx.IndexOf("<status>")).Replace("<status>", "").Trim();
if (statusx == "HTTP/1.1 200 OK")
{
Console.Write("THIS IS VALID CAL!");
// ADD THIS CAL TO LIST TO SHOW!
content = "<propfind xmlns='DAV:'><prop><calendar-data/><getctag /></prop></propfind>";
ResponseStream = ExectueMethod(username, password, calhrefUrlfinal, "PROPFIND", null, content, "application/x-www-form-urlencoded", "1");
XmlDocument = new XmlDocument();
XmlDocument.Load(ResponseStream);
xmlInner = XmlDocument.InnerXml;
XmlDocument icsSoc = new XmlDocument();
icsSoc.LoadXml(xmlInner);
foreach (XmlNode ics in icsSoc.GetElementsByTagName("href"))
{
string t = ics.InnerText.Trim();
if (t.Contains(".ics"))
{
DownloadICS(t, Calname + ".ics");
break;
}
}
}
}
xx = xx + 1;
}
}
}
}
}
}
}
}
catch (Exception ex)
{ }
}
private static void DownloadICS(string pathUri, string fileNames)
{
WebClient request = new WebClient();
request.Credentials = new NetworkCredential(username, password);
Byte[] data = request.DownloadData(pathUri);
var str = System.Text.Encoding.Default.GetString(data);
string path = "icloudCalenders\\" + fileNames.Substring(fileNames.LastIndexOf(" / ") + 1);
FileStream fs = new FileStream(path, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite);
fs.Write(data, 0, data.Length);
fs.Close();
}
private static Stream ExectueMethod(string username, string password, string caldevURI, string methodName, WebHeaderCollection headers, string content, string contentType,string depth)
{
HttpWebRequest httpGetRequest = (HttpWebRequest)WebRequest.Create(caldevURI);
httpGetRequest.Credentials = new NetworkCredential(username, password);
httpGetRequest.PreAuthenticate = true;
httpGetRequest.Method = methodName;
httpGetRequest.Headers.Add("Depth", depth);
httpGetRequest.Headers.Add("Authorization", username);
//httpGetRequest.UserAgent = "DAVKit/3.0.6 (661); CalendarStore/3.0.8 (860); iCal/3.0.8 (1287); Mac OS X/10.5.8 (9L31a)";
httpGetRequest.UserAgent = "curl/7.37.0";
if (!string.IsNullOrWhiteSpace(contentType))
{
httpGetRequest.ContentType = contentType;
}
using (var streamWriter = new StreamWriter(httpGetRequest.GetRequestStream()))
{
string data = content;
streamWriter.Write(data);
}
//Stream requestStream = httpGetRequest.GetRequestStream();
//requestStream.Write(optionsArray, 0, optionsArray.Length);
//requestStream.Close();
HttpWebResponse httpGetResponse = (HttpWebResponse)httpGetRequest.GetResponse();
Stream responseStream = httpGetResponse.GetResponseStream();
return responseStream;
}
Related
I need your help to solve my issue please give me a solution for this
I am trying a Serialize and Deserialize the Dynamic XML Data but the data was not Deserialized
These are my methods and i am using.
**Button Click Method**
protected void btnCreateSession_Click(object sender, EventArgs e)
{
//System.Threading.Thread.Sleep(2000);
tbodyException.Visible = false;//changes 9/10/12
try
{
CreateSessionRequest request = new CreateSessionRequest();
//ucClientInfo uc =
(ucClientInfo)LoadControl("~Shared/UserControls/ucClientInfo.ascx");
request.applicationId = ucClientInfo1.txtApplicationID.Text;
request.accountType = ddlAccountType.SelectedValue;
request.salesOffice =
ddlSalesoffice.SelectedItem.ToString();//txtSalesOffice.Text;
request.salesAgentId = txtAgentId.Text;
// Thiyagu 10/10/2012 added for deriving metrics by Agent and Outlet details
request.salesAgentName = txtAgentName.Text;
request.outletLocationId = txtOutletID.Text;
request.outletLocationName = txtOutletName.Text;
// Thiyagu 10/10/2012 added for deriving metrics by Agent and Outlet details
Dictionary<string, string> agentDetails = new Dictionary<string, string>();
agentDetails.Add("SubClientId", request.salesOffice);
agentDetails.Add("SalesAgentId", request.salesAgentId);
agentDetails.Add("SalesAgentName", request.salesAgentName);
Session.Add("AgentDetails", agentDetails);
ClientInfo clientinfo = new ClientInfo();
// Thiyagu 10/04/12 populating dummy app server details in client else schema
clientinfo = PreOrderingHelper.mapClientInfoDetails(clientinfo);
clientinfo.name = ucClientInfo1.txtClientName.Text;
clientinfo.clientId = ucClientInfo1.ddlClientID.SelectedValue;
GlobalVariable.ServiceClientID = ucClientInfo1.ddlClientID.SelectedValue;
request.client = clientinfo;
CreateSessionResponse response = new CreateSessionResponse();
string url = (Page.Master as TestBed).COAServiceUrl;
var token = (Page as BasePage).Token;
var _url = (Page as BasePage).AppUrl;
var _action = (Page as BasePage).Action + CurrentFlow.ToString();
bool localDebug = Convert.ToBoolean(System.Configuration.ConfigurationManager.AppSettings["localDebug"]);
if (!localDebug)
{
//ServiceHelper<CreateSessionRequest, CreateSessionResponse> helper = new
ServiceHelper<CreateSessionRequest, CreateSessionResponse>(url);
//response = helper.CallService(request, CurrentFlow.ToString(), TcId);
var webRequest = (HttpWebRequest)CommonUtil.SendSOAPRequest(request, _url, CurrentFlow.ToString(), token, _action, false);
string result;
using (WebResponse resp = webRequest.GetResponse())
{
using (StreamReader rd = new StreamReader(resp.GetResponseStream()))
{
result = rd.ReadToEnd();
response = CommonUtil.DeserializeInnerSoapObject < CreateSessionResponse(result);
}
}
}
else
{
TextReader tr = new StreamReader(#"C:\SampleXmls\CreateSessionResp.xml");
System.Xml.Serialization.XmlSerializer xs = new System.Xml.Serialization.XmlSerializer(typeof(CreateSessionResponse), "http://verizon.com/CoFEEAnywhere/CoAServices/v1");
//response = xs.Deserialize(tr) as SoapResponse.CreateSessionResponse;
response = xs.Deserialize(tr) as CreateSessionResponse;
}
if (response != null && response.output != null &&
!string.IsNullOrEmpty(response.output.sessionId))
{
Session["sessionId"] = response.output.sessionId; // Saving it in session - Can be used elsewehere in later flows
(Page.Master.FindControl("lblGlobalSessionIDValue") as Label).Text = response.output.sessionId; // setting the bottom session area in Preordering.aspx
var masterPage = Page.Master as TestBed;
masterPage.SessionIdUpdatePanel.Update();
(Page as BasePage).SessionID = response.output.sessionId;
lblCreatedSession.Text = (Page as BasePage).SessionID;
lblSalesProfileResult.Text = "SUCCESS";
Session["ClientId"] = ucClientInfo1.ddlClientID.SelectedValue;
Session["ClientName"] = ucClientInfo1.txtClientName.Text;
Session["AppId"] = ucClientInfo1.txtApplicationID.Text;
Session["OrderType"] = ddlOrderType.SelectedValue;
Session["AccountType"] = ddlAccountType.SelectedValue;
}
}
catch (Exception ex)
{
tbodyException.Visible = true;
aExcpetion.InnerText = ex.Message + " | " + ex.InnerException != null ?
ex.InnerException.Message : string.Empty;//aExcpetion.Attributes.Add("onclick",
"OpenExceptionWindow('" + ex.InnerException + "');
}
finally
{
if (!string.IsNullOrEmpty(Session["ClientId"].ToString()) &&
Session["ClientId"].ToString() == "CETC")
{
var masterPage = Page.Master as TestBed;
masterPage.NextFlow.CommandName = FlowType.Recommended.ToString();
masterPage.NextFlow.Text = "Next";
masterPage.NextFlow.Visible = true;
}
else
{
var masterPage = Page.Master as TestBed;
masterPage.NextFlow.Visible = true;
}
}
}
** SOAP Request**
public static object SendSOAPRequest(object req, string _url, string methodName, string token, string _action, bool useSOAP12)
{
ServicePointManager.ServerCertificateValidationCallback = new
RemoteCertificateValidationCallback
(
delegate { return true; }
);
// Create the SOAP envelope
var formXml = new XmlDocument();
string soapXml = "";
soapXml = WsdlRequestToSOAP(req);
if (methodName == "GetBroadbandAvailability")
{
soapXml = soapXml.Remove(0, 21).Replace(methodName + "Request",
"gbbRequest");
}
else if (methodName == "GetQualifiedProducts")
{
soapXml = soapXml.Remove(0, 21).Replace(methodName + "Request",
"productsrequest");
}
else
{
soapXml = soapXml.Remove(0, 21).Replace(methodName + "Request", "req" +
methodName);
}
formXml.LoadXml(soapXml);
var newXml = new XmlDocument();
var rootTag = String.Format("<{0}></{0}>", methodName);
newXml.LoadXml(rootTag);
XmlNode rootNode = newXml.ImportNode(formXml.DocumentElement, true);
newXml.DocumentElement.AppendChild(rootNode);
var stringXml = #"<?xml version=""1.0"" encoding=""utf-8""?>
<soap:Envelope xmlns:soap=""http://schemas.xmlsoap.org/soap/envelope/""
xmlns=""http://some link""
xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance""
xmlns:xsd=""http://www.w3.org/2001/XMLSchema"">
<soap:Body>
{0}
</soap:Body>
</soap:Envelope>";
var s = String.Format(stringXml, newXml.InnerXml);
formXml.LoadXml(s);
// Create the web request
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(_url);
webRequest.Headers.Add("SOAPAction", _action ?? _url);
webRequest.ContentType = (useSOAP12) ? "application/soap+xml;charset=\"utf-8\"" :
"text/xml; encoding=utf-8";
webRequest.Accept = (useSOAP12) ? "application/soap+xml" : "text/xml";
webRequest.Method = "POST";
webRequest.Headers.Add("Authorization", "Bearer " + token);
webRequest.Headers.Add("X-CLIENT-CERT-STATUS", "ok");
webRequest.Headers.Add("X-SUBJECT-NAME", "C=US, ST=Florida, L=Temple Terrace, O =\"Verizon Data Services.LLC\", OU=GTSAP, CN=apigee.coasvcs.verizon.com");
// Insert SOAP envelope
using (Stream stream = webRequest.GetRequestStream())
{
formXml.Save(stream);
}
return webRequest;
}
** AuthorizeRequest**
public static string AuthorizeRequest()
{
string client_id = "t1ehVqcAGYmWC8yvPapwgdZOqOjQd5oO";
string client_secret = "ICo3o8Da8BCpmXk0";
var restClient = new RestClient("https://some link / oauth / client_credential / accesstoken ? grant_type = client_credentials");
var restRequest = new RestRequest(Method.POST);
restRequest.AddHeader("Cache-Control", "no-cache");
restRequest.AddHeader("Content-Type", "application/json");
restRequest.AddParameter("client_id", client_id);
restRequest.AddParameter("client_secret", client_secret);
IRestResponse restResponse = restClient.Execute(restRequest);
var responseJson = restResponse.Content;
var token = JsonConvert.DeserializeObject<Dictionary<string, object>>
(responseJson)["access_token"].ToString();
return token;
}
** WsdlRequestToSOAP**
public static string WsdlRequestToSOAP(object Object)
{
if (Object == null)
{
throw new ArgumentException("Object can not be null");
}
try
{
var serxml = new System.Xml.Serialization.XmlSerializer(Object.GetType());
var ms = new MemoryStream();
serxml.Serialize(ms, Object);
return Encoding.UTF8.GetString(ms.ToArray());
}
catch { throw; }
}
** IndentXMLString**
public static string IndentXMLString(string xml)
{
string outXml = string.Empty;
MemoryStream ms = new MemoryStream();
// Create a XMLTextWriter that will send its output to a memory stream (file)
XmlTextWriter xtw = new XmlTextWriter(ms, Encoding.Unicode);
XmlDocument doc = new XmlDocument();
StreamReader sr = null;`enter code here`
try
{
// Load the unformatted XML text string into an instance
// of the XML Document Object Model (DOM)
doc.LoadXml(xml);
// Set the formatting property of the XML Text Writer to indented
// the text writer is where the indenting will be performed
xtw.Formatting = System.Xml.Formatting.Indented;
// write dom xml to the xmltextwriter
doc.WriteContentTo(xtw);
// Flush the contents of the text writer
// to the memory stream, which is simply a memory file
xtw.Flush();
// set to start of the memory stream (file)
ms.Seek(0, SeekOrigin.Begin);
// create a reader to read the contents of
// the memory stream (file)
sr = new StreamReader(ms);
// return the formatted string to caller
}
catch (Exception ex)
{
}
return sr.ReadToEnd();
}
** Finally this is the DeserializeInnerSoapObject method**
public static T DeserializeInnerSoapObject<T>(string soapResponse)
{
XmlDocument xmlDocument = new XmlDocument();
xmlDocument.LoadXml(soapResponse);
var soapBody = xmlDocument.GetElementsByTagName("s:Body")[0];
string innerObject = IndentXMLString(soapBody.InnerXml); //soapBody.InnerXml;
XmlSerializer deserializer = new XmlSerializer(typeof(T), "http://some link");
using (TextReader reader = new StringReader(innerObject))
{
return (T)deserializer.Deserialize(reader);
}
}
Try following :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Serialization;
using System.IO;
namespace ConsoleApplication1
{
class Program
{
const string FILENAME = #"c:\temp\test.xml";
static void Main(string[] args)
{
string soap = File.ReadAllText(FILENAME);
StringReader sReader = new StringReader(soap);
XmlReader reader = XmlReader.Create(sReader);
XmlSerializer serializer = new XmlSerializer(typeof(Envelope));
Envelope envelope = (Envelope)serializer.Deserialize(reader);
}
}
[XmlRoot(ElementName = "Envelope", Namespace = "http://schemas.xmlsoap.org/soap/envelope/")]
public class Envelope
{
[XmlElement(ElementName = "Body", Namespace = "http://schemas.xmlsoap.org/soap/envelope/")]
public Body body { get; set; }
}
public class Body
{
[XmlElement(ElementName = "CreateSessionResponse", Namespace = "http://some link")]
public CreateSessionResponse CreateSessionResponse { get; set; }
}
public class CreateSessionResponse
{
[XmlElement(ElementName = "CreateSessionResult", Namespace = "http://some link")]
public CreateSessionResult CreateSessionResult { get; set; }
}
public class CreateSessionResult
{
[XmlElement(ElementName = "output", Namespace = "http://some link")]
public Output Output { get; set; }
}
public class Output
{
[XmlElement]
public string sessionId { get; set; }
}
}
Actually this is not the answer
I have shared my output here please check with this and give me the solution for this issue
I got the Soap response like this
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
<soap:Body xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<CreateSessionResponse xmlns="http://some link">
<CreateSessionResult>
<output>
<sessionId>some id</sessionId>
</output>
</CreateSessionResult>
</CreateSessionResponse>
</soap:Body>
</soap:Envelope>
The following method generate a XmlDocument from a string and then call another method to generate a hash of the XmlDocument created.
private void geraXML()
{
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.PreserveWhitespace = true;
string xml = #"<?xml version=""1.0""?>...";
xmlDoc.LoadXml(xml);
string caminho = path/+"xmldoc.xml";
string nomeArquivo = "xmldoc.xml";
xmlDoc.Save(caminho);
//call method to generate hash
geraHASH(caminho, nomeArquivo);
}
This another method convert the same string of first method to stream and send to a webService
private void enviaACCS001(string protocolo, string caminho)
{
string base64 = Convert.ToBase64String(Encoding.Default.GetBytes("user:password"));
string authorization = String.Concat("Basic ", base64);
String finalResult;
HttpWebRequest hwrRequest = (HttpWebRequest)HttpWebRequest.Create("addres/" + protocolo);
hwrRequest.UseDefaultCredentials = true;
hwrRequest.Headers.Add("Authorization", authorization);
hwrRequest.Method = "PUT";
string finalXML = #"<?xml version=""1.0""?>...";
byte[] bytes = Encoding.Default.GetBytes(finalXML);
hwrRequest.ContentLength = bytes.Length;
using (Stream putStream = hwrRequest.GetRequestStream())
{
putStream.Write(bytes, 0, bytes.Length);
}
using (HttpWebResponse response = (HttpWebResponse)hwrRequest.GetResponse())
using (StreamReader reader = new StreamReader(response.GetResponseStream()))
{
finalResult = reader.ReadToEnd();
visualiza.Text = visualiza.Text + "\n " + finalResult;
}
The WebService generate the hash of stream and compare with the first hash generated. So far so good, the compare return true, but the WebService need the encoding="UTF-16BE" and when insert this information into the string the hash not match. What i'm doing wrong?
First method with encoding="UTF-16BE"
private void geraXML()
{
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.PreserveWhitespace = true;
string xml = #"<?xml version=""1.0"" encoding=""UTF-16BE""?>...";
xmlDoc.LoadXml(xml);
string caminho = path/+"xmldoc.xml";
string nomeArquivo = "xmldoc.xml";
xmlDoc.Save(caminho);
//call method to generate hash
geraHASH(caminho, nomeArquivo);
}
Second method with encoding="utf-16bE"
private void enviaACCS001(string protocolo, string caminho)
{
string base64 = Convert.ToBase64String(Encoding.Default.GetBytes("user:password"));
string authorization = String.Concat("Basic ", base64);
String finalResult;
HttpWebRequest hwrRequest = (HttpWebRequest)HttpWebRequest.Create("addres/" + protocolo);
hwrRequest.UseDefaultCredentials = true;
hwrRequest.Headers.Add("Authorization", authorization);
hwrRequest.Method = "PUT";
string finalXML = #"<?xml version=""1.0"" encoding=""UTF-16BE""?>...";
byte[] bytes = Encoding.BigEndianUnicode.GetBytes(finalXML);
hwrRequest.ContentLength = bytes.Length;
using (Stream putStream = hwrRequest.GetRequestStream())
{
putStream.Write(bytes, 0, bytes.Length);
}
using (HttpWebResponse response = (HttpWebResponse)hwrRequest.GetResponse())
using (StreamReader reader = new StreamReader(response.GetResponseStream()))
{
finalResult = reader.ReadToEnd();
visualiza.Text = visualiza.Text + "\n " + finalResult;
}
I'm trying to create a Bulk API to send Data to Salesforce .Here is my Code`
string userName = "XXXX";
//Console.Write("Enter password: ");
string password = "XXX";
string SessionId = SalesforceLogin(userName, password);
string JobId = CreateJob(SessionId, "insert", "Contact");
byte[] inputFileData = null;
string jobId = string.Empty;
string resultId = string.Empty;
string batchId = string.Empty;
if (JobId.Length > 0)
{
System.IO.FileInfo oFile = null;
//oFile = New System.IO.FileInfo("data.csv")
oFile = new System.IO.FileInfo(#"D:\request.txt");
System.IO.FileStream oFileStream = oFile.OpenRead();
long lBytes = oFileStream.Length;
int a = (int)lBytes; //modified after conversion
if ((lBytes > 0))
{
byte[] fileData = new byte[lBytes];
// Read the file into a byte array
oFileStream.Read(fileData, 0, a); //modified after conversion
oFileStream.Close();
//Get the file where the Query is present
inputFileData = fileData;
}
batchId= AddBatch(SessionId, JobId, inputFileData);
After that, I create A Job
private static string CreateJob(string sessionId, string sfOperation, string sfObjectName)
{
string str = "";
string reqURL = "";
byte[] bytes;
XmlDocument reqDoc;
XmlDocument respDoc;
str = ""
+ "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" // added \r\n as recommended by L.B's answer
+ "<jobInfo xmlns=\"http://www.force.com/2009/06/asyncapi/dataload\">"
+ " <operation></operation>" // removed "+sfOperation+"
+ " <object></object>" // removed "+sfObjectName+"
+ " <contentType>XML</contentType>" // should be CSV, NOT XML
+ "</jobInfo>"
;
reqURL = "https://ap2.salesforce.com/services/async/23.0/job";
reqDoc = new XmlDocument();
reqDoc.LoadXml(str);
// added XML modifications
reqDoc.GetElementsByTagName("operation")[0].InnerText = sfOperation;
reqDoc.GetElementsByTagName("object")[0].InnerText = sfObjectName;
bytes = System.Text.Encoding.ASCII.GetBytes(reqDoc.InnerXml);
respDoc = Post(bytes, reqURL, sessionId); // create job
string JobId = (respDoc != null) ?
(respDoc.GetElementsByTagName("id").Count > 0) ?
(respDoc.GetElementsByTagName("id")[0].InnerText) :
"" :
""
;
return JobId;
}`
Then I create A Batch to
private static string AddBatch(string sessionId, string jobId, byte[] fileBytes)
{
string reqURL = "https://ap2.salesforce.com/services/async/23.0/job/" + jobId + "/batch";
XmlDocument respDoc = Post(fileBytes, reqURL, sessionId);
string batchId = (respDoc != null) ?
(respDoc.GetElementsByTagName("id").Count > 0) ?
(respDoc.GetElementsByTagName("id")[0].InnerText) :
"" :
""
;
return batchId;
}
Then the Post Method
private static XmlDocument Post(byte[] bytes, string reqURL, object sfSessionId)
{
WebRequest req = WebRequest.Create(reqURL);
req.Method = "POST";
if ((bytes != null))
{
req.ContentLength = bytes.Length;
}
req.ContentType = "application/xml; charset=UTF-8"; // should be text/csv; when passing a CSV file
req.Headers.Add("X-SFDC-Session: " + sfSessionId);
System.IO.Stream strm = req.GetRequestStream();
if ((bytes != null))
strm.Write(bytes, 0, bytes.Length);
strm.Close();
HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
System.IO.Stream respStrm = resp.GetResponseStream();
XmlDocument respDoc = new XmlDocument();
respDoc.Load(respStrm);
return respDoc;
}
Everything Going Good But when I'm trying to save the Data on Lead it displays the Error
InvalidBatch : Failed to parse XML. Failed to get next element
After Creating Batch I get Result
<?xml version="1.0" encoding="UTF-8"?><batchInfo xmlns="http://www.force.com/2009/06/asyncapi/dataload"><id>7512800000C8OHAAA3</id><jobId>75028000008qk53AAA</jobId><state>Queued</state><createdDate>2017-05-30T14:11:45.000Z</createdDate><systemModstamp>2017-05-30T14:11:45.000Z</systemModstamp><numberRecordsProcessed>0</numberRecordsProcessed><numberRecordsFailed>0</numberRecordsFailed><totalProcessingTime>0</totalProcessingTime><apiActiveProcessingTime>0</apiActiveProcessingTime><apexProcessingTime>0</apexProcessingTime></batchInfo>
One More thing After inserting the Batch, How this job will execute .I'm pasting all the code because it may help Someone if i get the Answer :).
Can anyone please provide a CALDAV example for C#? Thanks in advance. I am struggling to find an example except this one.
https://ovaismehboob.wordpress.com/2014/03/30/sync-calendar-events-using-caldav/
But id does not work for me.
I get the following Error.
{"The remote server returned an error: (400) Bad Request."}
Here is the code,
public class Caldevx
{
static System.IO.Stream ResponseStream;
static System.Xml.XmlDocument XmlDocument;
static string calendarURI = "https://caldav.calendar.yahoo.com/dav/";
static string username = "thanujastech#yahoo.com";
static string password = "******";
static string content = "<?xml version=\"1.0\" encoding=\"utf-8\"?><propfind xlmns\"DAV:\"><allprop/></propfind>";
public void GetCalendars(){
WebHeaderCollection whc = new WebHeaderCollection();
whc.Add(#"Translate", "F");
ResponseStream = ExectueMethod(username, password, calendarURI,"PROPFIND", whc, content, "text/xml");
XmlDocument = new XmlDocument();
XmlDocument.Load(ResponseStream);
string xmlInner = XmlDocument.InnerXml;
XmlDocument innerXmlDocument = new XmlDocument();
innerXmlDocument.LoadXml(xmlInner);
XmlNodeList lst = innerXmlDocument.GetElementsByTagName("DAV:href");
List<string> lstICSs = new List<string>();
foreach(XmlNode node in lst){
if(node.InnerText.EndsWith(".ics"))
{
lstICSs.Add(node.InnerText.Trim());
}
ResponseStream.Close();
if (lstICSs.Count > 0)
{
DownloadICS("https//caldav.calendar.yahoo.com", lstICSs);
}
}
}
private void DownloadICS(string pathUri, List<string> fileNames)
{
WebClient request = new WebClient();
request.Credentials = new NetworkCredential(username, password);
foreach (var file in fileNames)
{
Byte[] data = request.DownloadData(pathUri + file);
var str = System.Text.Encoding.Default.GetString(data);
string path = #"C:\" + file.Substring(file.LastIndexOf("/")+1);
FileStream fs = new FileStream(path, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite);
fs.Write(data, 0, data.Length);
fs.Close();
DDay.iCal.IICalendarCollection calendars = iCalendar.LoadFromFile(path);
foreach (var item in calendars)
{
foreach (Event e in item.Events)
{
Console.WriteLine(e.Description);
}
}
}
}
private Stream ExectueMethod(string username, string password, string caldevURI, string methodName, WebHeaderCollection headers, string content, string contentType)
{
HttpWebRequest httpGetRequest = (HttpWebRequest)WebRequest.Create(caldevURI);
httpGetRequest.Credentials = new NetworkCredential(username, password);
httpGetRequest.PreAuthenticate = true;
httpGetRequest.Method = methodName;
if (headers != null && headers.HasKeys())
{
httpGetRequest.Headers = headers;
}
byte[] optionsArray = Encoding.UTF8.GetBytes(content);
httpGetRequest.ContentLength = optionsArray.Length;
if (!string.IsNullOrWhiteSpace(contentType))
{
httpGetRequest.ContentType = contentType;
}
Stream requestStream = httpGetRequest.GetRequestStream();
requestStream.Write(optionsArray, 0, optionsArray.Length);
requestStream.Close();
HttpWebResponse httpGetResponse = (HttpWebResponse)httpGetRequest.GetResponse();
Stream responseStream = httpGetResponse.GetResponseStream();
return ResponseStream;
}
}
I'm trying to use the new Toggl API (v8) with .NET C#. I've based my code on the example from litemedia (http://litemedia.info/connect-to-toggl-api-with-net), but it was originally created for version 1 of the API.
private const string TogglTasksUrl = "https://www.toggl.com/api/v8/tasks.json";
private const string TogglAuthUrl = "https://www.toggl.com/api/v8/me"; //sessions.json";
private const string AuthenticationType = "Basic";
private const string ApiToken = "user token goes here";
private const string Password = "api_token";
public static void Main(string[] args)
{
CookieContainer container = new CookieContainer();
var authRequest = (HttpWebRequest)HttpWebRequest.Create(TogglAuthUrl);
authRequest.Credentials = CredentialCache.DefaultCredentials;
authRequest.Method = "POST";
authRequest.ContentType = "application/x-www-form-urlencoded";
authRequest.CookieContainer = container;
string value = ApiToken; //= Convert.ToBase64String(Encoding.Unicode.GetBytes(ApiToken));
value = string.Format("{1}:{0}", Password, value);
//value = Convert.ToBase64String(Encoding.Unicode.GetBytes(value));
authRequest.ContentLength = value.Length;
using (StreamWriter writer = new StreamWriter(authRequest.GetRequestStream(), Encoding.ASCII))
{
writer.Write(value);
}
try
{
var authResponse = (HttpWebResponse)authRequest.GetResponse();
using (var reader = new StreamReader(authResponse.GetResponseStream(), Encoding.UTF8))
{
string content = reader.ReadToEnd();
}
HttpWebRequest tasksRequest = (HttpWebRequest)HttpWebRequest.Create(TogglTasksUrl);
tasksRequest.CookieContainer = container;
//var jsonResult = string.Empty;
var tasksResponse = (HttpWebResponse)tasksRequest.GetResponse();
MemoryStream ms = new MemoryStream();
tasksResponse.GetResponseStream().CopyTo(ms);
//using (var reader = new StreamReader(tasksResponse.GetResponseStream(), Encoding.UTF8))
//{
// jsonResult = reader.ReadToEnd();
//}
ms.Seek(0, SeekOrigin.Begin);
DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(Task));
var tasks = ser.ReadObject(ms) as List<Task>;
ms.Close();
//var tasks = DataContractJsonConvert.DeserializeObject<Task[]>(jsonResult);
foreach (var task in tasks)
{
Console.WriteLine(
"{0} - {1}: {2} starting {3:yyyy-MM-dd HH:mm}",
task.Project.Name,
task.Description,
TimeSpan.FromSeconds(task.Duration),
task.Start);
}
}
catch (System.Exception ex)
{
throw;
}
}
The following line is returning a 404 error.
var authResponse = (HttpWebResponse)authRequest.GetResponse();
Here is code that works. Since I was looking for this answer recently there might still be others as lost as me.
Notes: I used Encoding.Default.GetBytes() because Encoding.Unicode.GetBytes() did not give me a correct result on my .NET string. I hope it doesn't depend on the default setup of Visual Studio.
The content-type is "application/json".
Sorry, I haven't tried a POST version yet.
string ApiToken = "user token goes here";
string url = "https://www.toggl.com/api/v8/me";
string userpass = ApiToken + ":api_token";
string userpassB64 = Convert.ToBase64String(Encoding.Default.GetBytes(userpass.Trim()));
string authHeader = "Basic " + userpassB64;
HttpWebRequest authRequest = (HttpWebRequest)WebRequest.Create(url);
authRequest.Headers.Add("Authorization", authHeader);
authRequest.Method = "GET";
authRequest.ContentType = "application/json";
//authRequest.Credentials = CredentialCache.DefaultNetworkCredentials;
try
{
var response = (HttpWebResponse)authRequest.GetResponse();
string result = null;
using (Stream stream = response.GetResponseStream())
{
StreamReader sr = new StreamReader(stream);
result = sr.ReadToEnd();
sr.Close();
}
if (null != result)
{
System.Diagnostics.Debug.WriteLine(result.ToString());
}
// Get the headers
object headers = response.Headers;
}
catch (Exception e)
{
System.Diagnostics.Debug.WriteLine(e.Message + "\n" + e.ToString());
}