DocuSign X and Y positions - docusignapi

I have a Pdf XFA document populating from my system. When I extract X and Y positions for the signature field in XML it's in millimeter. DocuSign uses pixels for X and Y coordinates. When I convert Millimeter to a pixel in DocuSign it won't position correctly. Do anyone knows how to convert it correctly for DocuSign? Thanks in Advance.
Adobe XFA XML for Signature field
C# Code
EnvelopeDefinition envDef = new EnvelopeDefinition();
envDef.EmailSubject = "[DocuSign C# SDK] - Please sign this doc";
// Add a document to the envelope
DocuSign.eSign.Model.Document doc = new DocuSign.eSign.Model.Document();
doc.DocumentBase64 = System.Convert.ToBase64String(docuSignfileBytes);
doc.Name = FullFileName;
doc.DocumentId = "1";
envDef.Documents = new List<DocuSign.eSign.Model.Document>();
envDef.Documents.Add(doc);
// Add a recipient to sign the documeent
Signer signer = new Signer();
signer.Name = recipientName;
signer.Email = recipientEmail;
signer.RecipientId = "1";
signer.Tabs = new Tabs();
signer.Tabs.SignHereTabs = new List<SignHere>();
//Loading XML data to string builder
string[] delim = { Environment.NewLine, "\n" }; // "\n" added in case you manually appended a newline
string[] lines = sb.ToString().Split(delim, StringSplitOptions.None);
foreach (string line in lines)
{
if (line.Contains("SignatureField") == true)
{
if (line.Contains("x=") == true)
{
string[] readX = line.Trim().Split(' ');
for (int i = 0; i < readX.Length; i++)
{
if (readX[i].Contains("x=") == true)
{
strXLocation = readX[i].Substring(3, readX[i].Length - 7);
if(strXLocation.Length > 1)
{
double iXLoc = 0;
iXLoc = Convert.ToDouble(strXLocation) * Convert.ToDouble("3.77");
strXLocation = iXLoc.ToString();
strXLocation = strXLocation.Substring(0, strXLocation.IndexOf('.', 0));
}
}
}
}
if (line.Contains("y=") == true)
{
string[] readY = line.Trim().Split(' ');
for (int i = 0; i < readY.Length; i++)
{
if (readY[i].Contains("y=") == true)
{
strYLocation = readY[i].Substring(3, readY[i].Length - 7);
if(strYLocation.Length > 1)
{
double dYLoc = 0;
dYLoc = Convert.ToDouble(strYLocation) * Convert.ToDouble("3.77");
strYLocation = dYLoc.ToString();
strYLocation = strYLocation.Substring(0, strYLocation.IndexOf('.', 0));
}
}
}
}
if (strXLocation.Length > 1 && strYLocation.Length > 1)
{
// Create a |SignHere| tab somewhere on the document for the recipient to sign
SignHere signHere = new SignHere();
signHere.DocumentId = "1";
signHere.PageNumber = "2";
signHere.RecipientId = "1";
signHere.XPosition = strXLocation;
signHere.YPosition = strYLocation;
signer.Tabs.SignHereTabs.Add(signHere);
strXLocation = string.Empty;
strYLocation = string.Empty;
}
}
}
// =======================================
envDef.Recipients = new Recipients();
envDef.Recipients.Signers = new List<Signer>();
envDef.Recipients.Signers.Add(signer);
// set envelope status to "created" send to Draft envelop
envDef.Status = "sent"; //Draft Envelop //"sent";
// Use the EnvelopesApi to send the signature request!
EnvelopesApi envelopesApi = new EnvelopesApi();
EnvelopeSummary envelopeSummary = envelopesApi.CreateEnvelope(accountId, envDef);
EnvelopeID = envelopeSummary.EnvelopeId;

Related

I have free DocuSign Signature Appliance Developer Sandbox account.but can not perform signature operation using DssSign

I have a free DocuSign Signature Appliance Developer Sandbox account.I want to use "https://prime.cosigntrial.com:8080/SAPIWS/dss.asmx" and wan to use DssSign service method to create and attach signature to pdf.But it reutrn "urn:oasis:names:tc:dss:1.0:resultmajor:ResponderError".Please help how can I get username and password to create a new signature programmatically and assign to a pdf using DocuSign API
I already download the code samples found Git "docusign-signature-appliance-api-recipes-master" but can not sucess.
//Sign PDF file
public bool SignPDFFile(
string FileToSign,
string UserName,
string Password,
int X,
int Y,
int Width,
int Height,
int Page,
bool isVisible)
{
//Create Request object contains signature parameters
RequestBaseType Req = new RequestBaseType();
Req.OptionalInputs = new RequestBaseTypeOptionalInputs();
//Here Operation Type is set: Verify/Create Signature Field/Sign/etc
Req.OptionalInputs.SignatureType = SignatureTypeFieldCreateSign;
//Configure Create and Sign operation parameters:
Req.OptionalInputs.ClaimedIdentity = new ClaimedIdentity();
Req.OptionalInputs.ClaimedIdentity.Name = new NameIdentifierType();
Req.OptionalInputs.ClaimedIdentity.Name.Value = UserName; //User Name
Req.OptionalInputs.ClaimedIdentity.Name.NameQualifier = " "; //Domain (relevant for Active Directory environment only)
Req.OptionalInputs.ClaimedIdentity.SupportingInfo = new CoSignAuthDataType();
Req.OptionalInputs.ClaimedIdentity.SupportingInfo.LogonPassword = Password; //User Password
Req.OptionalInputs.SAPISigFieldSettings = new SAPISigFieldSettingsType();
Req.OptionalInputs.SAPISigFieldSettings.X = X; //Signature Field X coordinate
Req.OptionalInputs.SAPISigFieldSettings.XSpecified = true;
Req.OptionalInputs.SAPISigFieldSettings.Y = Y; //Signature Field Y coordinate
Req.OptionalInputs.SAPISigFieldSettings.YSpecified = true;
Req.OptionalInputs.SAPISigFieldSettings.Page = Page; //Page number the signature field will appear on
Req.OptionalInputs.SAPISigFieldSettings.PageSpecified = true;
Req.OptionalInputs.SAPISigFieldSettings.Width = Width; //Signature Field width
Req.OptionalInputs.SAPISigFieldSettings.WidthSpecified = true;
Req.OptionalInputs.SAPISigFieldSettings.Height = Height; //Signature Field Height
Req.OptionalInputs.SAPISigFieldSettings.HeightSpecified = true;
Req.OptionalInputs.SAPISigFieldSettings.Invisible = !isVisible; //Specifies whether the signature will be visible or not
Req.OptionalInputs.SAPISigFieldSettings.InvisibleSpecified = true;
// Set configuration parameters /////////////////////////////////////////////////////////
int numConfigurationParams = 6;
Req.OptionalInputs.ConfigurationValues = new ConfValueType[numConfigurationParams];
for (int i = 0; i < numConfigurationParams; i++)
{
Req.OptionalInputs.ConfigurationValues[i] = new ConfValueType();
}
// Add reason
Req.OptionalInputs.ConfigurationValues[0].ConfValueID = ConfIDEnum.Reason;
Req.OptionalInputs.ConfigurationValues[0].Item = "I am the author of this document";
// Add TSA:
/*
Req.OptionalInputs.ConfigurationValues[1].ConfValueID = ConfIDEnum.UseTimestamp;
Req.OptionalInputs.ConfigurationValues[1].Item = 1;
Req.OptionalInputs.ConfigurationValues[2].ConfValueID = ConfIDEnum.TimestampURL;
Req.OptionalInputs.ConfigurationValues[2].Item = "http://www.ca-soft.com/request.aspx";
Req.OptionalInputs.ConfigurationValues[3].ConfValueID = ConfIDEnum.TimestampAdditionalBytes;
Req.OptionalInputs.ConfigurationValues[3].Item = 4000;
Req.OptionalInputs.ConfigurationValues[4].ConfValueID = ConfIDEnum.TimestampUser;
Req.OptionalInputs.ConfigurationValues[4].Item = "";
Req.OptionalInputs.ConfigurationValues[5].ConfValueID = ConfIDEnum.TimestampPWD;
Req.OptionalInputs.ConfigurationValues[5].Item = "";
// OCSP (NOTE: Server must contain comodo CA in order to use the following OCSP URL)
Req.OptionalInputs.ConfigurationValues[4].ConfValueID = ConfIDEnum.UseOCSP;
Req.OptionalInputs.ConfigurationValues[4].Item = 1;
Req.OptionalInputs.ConfigurationValues[5].ConfValueID = ConfIDEnum.OCSPURL;
Req.OptionalInputs.ConfigurationValues[5].Item = "ocsp.comodoca.com";
*/
// End setting configuration parameters ////////////////////////////////////////////////
//Set Session ID
Req.RequestID = Guid.NewGuid().ToString();
//Prepare the Data to be signed
DocumentType doc1 = new DocumentType();
DocumentTypeBase64Data b64data = new DocumentTypeBase64Data();
Req.InputDocuments = new RequestBaseTypeInputDocuments();
Req.InputDocuments.Items = new object[1];
b64data.MimeType = "application/pdf"; //Can also be: application/msword, image/tiff, pplication/octet-string (ocsp/tsa are supported in PDF only)
Req.OptionalInputs.ReturnPDFTailOnlySpecified = true;
Req.OptionalInputs.ReturnPDFTailOnly = true;
b64data.Value = ReadFile(FileToSign, true); //Read the file to the Bytes Array
doc1.Item = b64data;
Req.InputDocuments.Items[0] = doc1;
//Call sign service
ResponseBaseType Resp = null;
try
{
// Create the Web Service client object
DSS service = new DSS();
service.Url = "https://prime.cosigntrial.com:8080/SAPIWS/dss.asmx"; //This url is constant and shouldn't be changed
// service.Url = "https://prime-dsa-devctr.docusign.net:8080/sapiws/dss.asmx"; //This url is constant and shouldn't be changed
SignRequest sreq = new SignRequest();
sreq.InputDocuments = Req.InputDocuments;
sreq.OptionalInputs = Req.OptionalInputs;
//Perform Signature operation
Resp = service.DssSign(sreq);
if (Resp.Result.ResultMajor != Success )
{
MessageBox.Show("Error: " + Resp.Result.ResultMajor + " " +
Resp.Result.ResultMinor + " " +
Resp.Result.ResultMessage.Value, "Error");
return false;
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error");
if (ex is WebException)
{
WebException we = ex as WebException;
WebResponse webResponse = we.Response;
if (webResponse != null)
MessageBox.Show(we.Response.ToString(), "Web Response");
}
return false;
}
//Handle Reply
DssSignResult sResp = (DssSignResult) Resp;
//object sig = sResp.SignatureObject.Item;
//SignatureObjectTypeBase64Signature sig = (SignatureObjectTypeBase64Signature) sResp.SignatureObject.Item;
DssSignResultSignatureObjectBase64Signature sig = (DssSignResultSignatureObjectBase64Signature)sResp.SignatureObject.Item;
byte[] signature = sig.Value;
return PDFAttachSignature(FileToSign, signature, true); //Attach Signature to the PDF file
}
display error urn:oasis:names:tc:dss:1.0:resultmajor:ResponderError

DocuSign Rest API: Signer can sign a tab which is for a different recipient

I am trying to create a simple scenario with the DocuSign REST API as follows:
I have 2 signers, Signer1 and Signer2
A document is sent to Signer1 to review and sign
Signer 2 is notified and reviews the document and signs below where Signer1 signed
I have this working in order except that when Signer1 reviews the document they see Signer2's tab and have to sign for Signer2 as well. The tabs in the document have different names and I am adding the relevant AnchorStrings to the event notification.
Here is my code:
Signer signer = new Signer();
signer.Email = txtRecipientEmail;
signer.Name = txtRecipientName;
signer.RecipientId = "1";
signer.RoleName = "Candidate";
signer.RoutingOrder = "1";
// Create a |SignHere| tab somewhere on the document for the recipient to sign
signer.Tabs = new Tabs();
signer.Tabs.SignHereTabs = new List<SignHere>();
SignHere signHere = new SignHere();
signHere.DocumentId = "1";
signHere.AnchorString = "PleaseSignHere";
signHere.AnchorXOffset = "-2";
signHere.AnchorYOffset = "0";
signHere.AnchorIgnoreIfNotPresent = "false";
signHere.AnchorUnits = "inches";
signer.Tabs.SignHereTabs.Add(signHere);
signer.Tabs.DateSignedTabs = new List<DateSigned>();
DateSigned dateSigned = new DateSigned();
dateSigned.DocumentId = "1";
dateSigned.AnchorString = "DateSignedHere";
dateSigned.AnchorXOffset = "0";
dateSigned.AnchorYOffset = "0";
dateSigned.AnchorIgnoreIfNotPresent = "false";
dateSigned.AnchorUnits = "inches";
dateSigned.Bold = "true";
signer.Tabs.DateSignedTabs.Add(dateSigned);
// add another signer
Signer signer2 = new Signer();
signer2.Email = txtRecipientEmail2;
signer2.Name = txtRecipientName2;
signer2.RecipientId = "2";
signer2.RoleName = "Referee";
signer2.RoutingOrder = "2";
signer2.Tabs = new Tabs();
signer2.Tabs.SignHereTabs = new List<SignHere>();
SignHere signHere2 = new SignHere();
signHere2.DocumentId = "1";
signHere2.AnchorString = "RefPleaseSignHere";
signHere2.AnchorXOffset = "-2";
signHere2.AnchorYOffset = "0";
signHere2.AnchorIgnoreIfNotPresent = "false";
signHere2.AnchorUnits = "inches";
signer2.Tabs.SignHereTabs.Add(signHere2);
signer2.Tabs.DateSignedTabs = new List<DateSigned>();
DateSigned dateSigned2 = new DateSigned();
dateSigned2.DocumentId = "1";
dateSigned2.AnchorString = "RefDateSignedHere";
dateSigned2.AnchorXOffset = "0";
dateSigned2.AnchorYOffset = "0";
dateSigned2.AnchorIgnoreIfNotPresent = "false";
dateSigned2.AnchorUnits = "inches";
dateSigned2.Bold = "true";
signer2.Tabs.DateSignedTabs.Add(dateSigned2);
envDef.Recipients = new Recipients();
envDef.Recipients.Signers = new List<Signer>();
envDef.Recipients.Signers.Add(signer);
envDef.Recipients.Signers.Add(signer2);
I must be missing something!
The anchorString for Signer1 is also present in anchorString for Signer2.
PleaseSignHere
RefPleaseSignHere
This is causing Signer1 tabs to be additionally placed at Signer2 tab location.
Solution
Set the AnchorMatchWholeWord property to true.
or
Use unique anchorStrings which do not overlap.

Send DataSet data email via attachment Excel File xls ( Not Creating Excel File ) C#

I want to send DataSet data with email excel file attachment in C# but I don't want to create Excel file physically. It can be do with MemoryStream but I couldn't.
Another problem I want to set Excel file's encoding type because data may be Russian or Turkish special character.
Please help me...
Here is my sample code...
<!-- language: c# -->
var response = HttpContext.Response;
response.Clear();
response.Charset = "utf-8";
response.ContentEncoding = System.Text.Encoding.Default;
GridView excelGridView = new GridView();
excelGridView.DataSource = InfoDataSet;
excelGridView.DataBind();
excelStringWriter = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(excelStringWriter);
excelGridView.RenderControl(htw);
byte[] ExcelData = emailEncoding.GetBytes(excelStringWriter.ToString());
MemoryStream ms = new MemoryStream(ExcelData);
mailMessage.Attachments.Add(new Attachment(ms, excelFileName, "application/ms-excel"));
<!-- language: c# -->
here is another one simple and easy with excel attchment
public string SendMail(string LastId)
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["con"].ConnectionString);
SqlCommand cmd = new SqlCommand("sp_GetMailData", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#LastID", LastId);
con.Open();
string result = "0";
string temptext = "";
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt=new DataTable();
da.Fill(dt);
//ExportToSpreadsheet(dt,"My sheet");
GridView gv = new GridView();
gv.DataSource = dt;
gv.DataBind();
AttachandSend(gv);
con.Close();
return result.ToString();
}
public void AttachandSend(GridView gv)
{
StringWriter stw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(stw);
gv.RenderControl(hw);
System.Text.Encoding Enc = System.Text.Encoding.ASCII;
byte[] mBArray = Enc.GetBytes(stw.ToString());
System.IO.MemoryStream mAtt = new System.IO.MemoryStream(mBArray, false);
System.Net.Mail.MailMessage mailMessage = new System.Net.Mail.MailMessage();
MailAddress address = new
MailAddress("xxxxxxxxxxxxx", "Admin");
mailMessage.Attachments.Add(new Attachment(mAtt, "sales.xls"));
mailMessage.Body = "Hi PFA";
mailMessage.From = address;
mailMessage.To.Add("xxxxxxxxxxxx");
mailMessage.Subject = "xxxxxxxxxxxxxx";
mailMessage.IsBodyHtml = true;
var smtp = new SmtpClient();
smtp.Send(mailMessage);
}
Here is your solution
private static Stream DataTableToStream(DataTable table)
{
const string semiColon = ";";
var ms = new MemoryStream();
var sw = new StreamWriter(ms);
foreach (DataColumn column in table.Columns)
{
sw.Write(column.ColumnName);
sw.Write(semiColon);
}
sw.Write(Environment.NewLine);
foreach (DataRow row in table.Rows)
{
for (int i = 0; i < table.Columns.Count; i++)
{
sw.Write(row[i].ToString().Replace(semiColon, string.Empty));
sw.Write(semiColon);
}
sw.Write(Environment.NewLine);
}
return ms;
}
private static MailMessage CreateMail(string from,
string to,
string subject,
string body,
string attname,
Stream tableStream)
{
// using System.Net.Mail
var mailMsg = new MailMessage(from, to, subject, body);
tableStream.Position = 0;
mailMsg.Attachments.Add(
new Attachment(tableStream, attname, CsvContentType));
return mailMsg;
}
private const string CsvContentType = "application/ms-excel";
private static void ExportToSpreadsheetInternal(Stream tableStream, string name)
{
HttpContext context = HttpContext.Current;
context.Response.Clear();
context.Response.ContentType = CsvContentType;
context.Response.AppendHeader(
"Content-Disposition"
, "attachment; filename=" + name + ".xls");
tableStream.Position = 0;
tableStream.CopyTo(context.Response.OutputStream);
context.Response.End();
}
public static void ExportToSpreadsheet(DataTable table, string name)
{
var stream = DataTableToStream(table);
var mailMsg = CreateMail("from#ddd.com",
"to#ddd.com",
"spread",
"the spread",
name,
stream);
//ExportToSpreadsheetInternal(stream, name);
// send the mailMsg with SmtpClient (config in your web.config)
var smtp = new SmtpClient();
smtp.Send(mailMsg);
}
Call this method
ExportToSpreadsheet(DataTable table, string name)

RoutingOrder does not work

When I am getting envelope by RequestStatus all recipients have same routing number. But I am sure and debug that provided different parameter for each recipient. And all recipients gets email in same time. How can I send envelope for each recipient according to RoutingOrder?
Sequential Signing (API) enabled for my account:
My examlple:
WebAPI.Recipient[] recipients = {new WebAPI.Recipient(), new WebAPI.Recipient()};
recipients[0].Email = "JohnDo#gmail.com";
recipients[0].UserName = "John Do";
recipients[0].Type = WebAPI.RecipientTypeCode.Signer;
recipients[0].ID = "2";
recipients[0].RoutingOrder = 2;
recipients[1].Email = "JohnDo2#gmail.com";
recipients[1].UserName = "John Do2";
recipients[1].Type = WebAPI.RecipientTypeCode.Signer;
recipients[1].ID = "1";
recipients[1].RoutingOrder = 1;
// Create envelope
WebAPI.Envelope envelope = new WebAPI.Envelope();
envelope.Subject = "Subject line mandatory!";
envelope.Recipients = recipients;
envelope.AccountId = APIAccountId;
// Create document
envelope.Documents = new WebAPI.Document[1];
WebAPI.Document doc = new WebAPI.Document();
doc.ID = "1";
doc.Name = "Picture PDF";
doc.TransformPdfFields = true;
doc.PDFBytes = Properties.Resources.test;
envelope.Documents[0] = doc;
// Create tab
WebAPI.Tab tab = new WebAPI.Tab();
WebAPI.AnchorTab anchorTab = new WebAPI.AnchorTab();
anchorTab.AnchorTabString = "Adobe";
anchorTab.IgnoreIfNotPresent = true;
anchorTab.IgnoreIfNotPresentSpecified = true;
tab.AnchorTabItem = anchorTab;
tab.CustomTabRequired = false;
tab.SenderRequired = false;
tab.Type = WebAPI.TabTypeCode.SignHere;
tab.DocumentID = "1";
tab.RecipientID = "1";
WebAPI.Tab tab2 = new WebAPI.Tab();
WebAPI.AnchorTab anchorTab2 = new WebAPI.AnchorTab();
anchorTab2.AnchorTabString = "CustomTag";
anchorTab2.IgnoreIfNotPresent = true;
anchorTab2.IgnoreIfNotPresentSpecified = true;
tab2.AnchorTabItem = anchorTab2;
tab2.Type = WebAPI.TabTypeCode.SignHere;
tab2.DocumentID = "1";
tab2.RecipientID = "2";
tab2.SenderRequired = false;
tab2.SharedTab = true;
tab2.TabLabel = "CustomTag";
tab2.Value = "Value2";
envelope.Tabs = new WebAPI.Tab[2];
envelope.Tabs[0] = tab;
envelope.Tabs[1] = tab2;
// Get results
WebAPI.EnvelopeStatus status = apiClient.CreateAndSendEnvelope(envelope);
Request to DocuSing SOAP API:
Request to DocuSing SOAP API
Problem resolved by adding option: for RoutingOrderSpecified = true each recipient ;
This code resolve problem for me:
recipients[0].RoutingOrderSpecified = true;
recipients[1].RoutingOrderSpecified = true;

Bill Filtering only returns default 10 sorted records without doing any filtering from QBO

Please find the below code for for filtering bills, which returns only 10 sorted records even I passed the resultperpage>10.
public IEnumerable<Intuit.Ipp.Data.Qbo.Bill> FilterBills(DataServices dataServices, int startPage, int resultsPerPage, DateTime After, DateTime Before)
{
Intuit.Ipp.Security.OAuthRequestValidator oAuthRequestValidator = ((Intuit.Ipp.Security.OAuthRequestValidator)dataServices.ServiceContext.RequestValidator);
OAuthConsumerContext consumerContext = new OAuthConsumerContext
{
ConsumerKey = oAuthRequestValidator.ConsumerKey,
SignatureMethod = SignatureMethod.HmacSha1,
ConsumerSecret = oAuthRequestValidator.ConsumerSecret
};
OAuthSession oSession = new OAuthSession(consumerContext, "https://oauth.intuit.com/oauth/v1/get_request_token",
"https://workplace.intuit.com/Connect/Begin",
"https://oauth.intuit.com/oauth/v1/get_access_token");
oSession.AccessToken = new TokenBase
{
Token = oAuthRequestValidator.AccessToken,
ConsumerKey = oAuthRequestValidator.ConsumerKey,
TokenSecret = oAuthRequestValidator.AccessTokenSecret
};
var body = "PageNum={0}&ResultsPerPage={1}&Filter=LastUpdatedTime :AFTER: {2} :AND: LastUpdatedTime :BEFORE: {3} & Sort=LastUpdatedTime HighToLow";
body = String.Format(body, startPage, resultsPerPage, After.ToString("yyyy-mm-ddTHH:MM:ssz"), Before.ToString("yyyy-mm-ddTHH:MM:ssz"));
IConsumerRequest conReq = oSession.Request();
conReq = conReq.Post().WithRawContentType("application/x-www-form-urlencoded").WithRawContent(System.Text.Encoding.ASCII.GetBytes(body)); ;
conReq = conReq.ForUrl(dataServices.ServiceContext.BaseUrl + "bills/v2/" + dataServices.ServiceContext.RealmId);
conReq = conReq.SignWithToken();
Intuit.Ipp.Data.Qbo.SearchResults searchResults = (Intuit.Ipp.Data.Qbo.SearchResults)dataServices.ServiceContext.Serializer.Deserialize<Intuit.Ipp.Data.Qbo.SearchResults>(conReq.ReadBody());
IEnumerable<Intuit.Ipp.Data.Qbo.Bill> SearchResult = ((Intuit.Ipp.Data.Qbo.Bills)(searchResults.CdmCollections)).Bill;
return SearchResult;
}
After sending the request i m getting the respose as 10 sorted bill record without getting any error. I am using IPPDotNetDevKit 2.1.12.0 version.
Please Look into this filtering problem.
The OAuth parameters are being passed in the body of the request in your example above and overwriting your request body, so it is defaulting to PageNum=1&ResultsPerPage=20. Also, the date is formatted incorrectly. Here is a code sample that will work.
public IEnumerable<Intuit.Ipp.Data.Qbo.Bill> FilterBills(DataServices dataServices, int startPage, int resultsPerPage, DateTime After, DateTime Before)
{
StringBuilder requestXML = new StringBuilder();
StringBuilder responseXML = new StringBuilder();
var requestBody =
"PageNum={0}&ResultsPerPage={1}&Filter=LastUpdatedTime :AFTER: {2} :AND: LastUpdatedTime :BEFORE: {3}&Sort=LastUpdatedTime HighToLow";
requestBody = String.Format(requestBody, startPage, resultsPerPage, After.ToString("yyyy-MM-ddThh:mm:sszzz"),
Before.ToString("yyyy-MM-ddThh:mm:sszzz"));
HttpWebRequest httpWebRequest =
WebRequest.Create(dataServices.ServiceContext.BaseUrl + "bills/v2/" +
dataServices.ServiceContext.RealmId) as HttpWebRequest;
httpWebRequest.Method = "POST";
httpWebRequest.ContentType = "application/x-www-form-urlencoded";
httpWebRequest.Headers.Add("Authorization", GetDevDefinedOAuthHeader(httpWebRequest, requestBody));
requestXML.Append(requestBody);
UTF8Encoding encoding = new UTF8Encoding();
byte[] content = encoding.GetBytes(requestXML.ToString());
using (var stream = httpWebRequest.GetRequestStream())
{
stream.Write(content, 0, content.Length);
}
HttpWebResponse httpWebResponse = httpWebRequest.GetResponse() as HttpWebResponse;
using (Stream data = httpWebResponse.GetResponseStream())
{
Intuit.Ipp.Data.Qbo.SearchResults searchResults =
(Intuit.Ipp.Data.Qbo.SearchResults)
dataServices.ServiceContext.Serializer.Deserialize<Intuit.Ipp.Data.Qbo.SearchResults>(
new StreamReader(data).ReadToEnd());
return ((Intuit.Ipp.Data.Qbo.Bills) searchResults.CdmCollections).Bill.ToList();
}
}
private string GetDevDefinedOAuthHeader(HttpWebRequest webRequest, string requestBody)
{
OAuthConsumerContext consumerContext = new OAuthConsumerContext
{
ConsumerKey = consumerKey,
ConsumerSecret = consumerSecret,
SignatureMethod = SignatureMethod.HmacSha1,
UseHeaderForOAuthParameters = true
};
consumerContext.UseHeaderForOAuthParameters = true;
OAuthSession oSession = new OAuthSession(consumerContext, "https://www.example.com",
"https://www.example.com",
"https://www.example.com");
oSession.AccessToken = new TokenBase
{
Token = accessToken,
ConsumerKey = consumerKey,
TokenSecret = accessTokenSecret
};
IConsumerRequest consumerRequest = oSession.Request();
consumerRequest = ConsumerRequestExtensions.ForMethod(consumerRequest, webRequest.Method);
consumerRequest = ConsumerRequestExtensions.ForUri(consumerRequest, webRequest.RequestUri);
if (webRequest.Headers.Count > 0)
{
ConsumerRequestExtensions.AlterContext(consumerRequest, context => context.Headers = webRequest.Headers);
if (webRequest.Headers[HttpRequestHeader.ContentType] == "application/x-www-form-urlencoded")
{
Dictionary<string, string> formParameters = new Dictionary<string, string>();
foreach (string formParameter in requestBody.Split('&'))
{
formParameters.Add(formParameter.Split('=')[0], formParameter.Split('=')[1]);
}
consumerRequest = consumerRequest.WithFormParameters(formParameters);
}
}
consumerRequest = consumerRequest.SignWithToken();
return consumerRequest.Context.GenerateOAuthParametersForHeader();
}

Resources