How to update google docs api namedrange text in c#? - c#

I want to insert text from c# textbox1 to google docs template body namedrange "BoddyTitle" and from textbox2 to body namedrange "BoddyContent" .
Because indexes of created namedrange is modifying for every update, I need to get value of that indexes before update with new text.
Pls help get that indexes.
List <Request> requests = new List<Request>
{
};
requests.Add(new Request()
{
ReplaceNamedRangeContent = new ReplaceNamedRangeContentRequest()
{
Text = textBox1.Text, NamedRangeName = "BoddyTitle"
}
}); // Index = 5-50,
requests.Add(new Request()
{
ReplaceNamedRangeContent = new ReplaceNamedRangeContentRequest()
{
Text = textBox2.Text, NamedRangeName = "BoddyContent"
}
}); // Index = 55-10000,
BatchUpdateDocumentRequest body = new BatchUpdateDocumentRequest { Requests = requests };
dservice.Documents.BatchUpdate(body, docid).Execute();

resolved, here the code
List<Request> requests = new List<Request> { };
DocumentsResource.GetRequest req = dservice.Documents.Get(docid);
Document doc = req.Execute();
int max = 0;
for (int i = 0; i < doc.Body.Content.Count; i++)
{
if (doc.Body.Content[i].EndIndex.Value > max)
{
max = doc.Body.Content[i].EndIndex.Value;
}
}
if (max < 3)
{
// requests.Add(new Request() { DeleteNamedRange = new DeleteNamedRangeRequest() { Name = "BoddyTitle" } });
// requests.Add(new Request() { DeleteNamedRange = new DeleteNamedRangeRequest() { Name = "BoddyContent", } });
requests.Add(new Request() { InsertText = new InsertTextRequest() { Text = "\n\nx", Location = new Location { Index = 1 } } });
requests.Add(new Request() { InsertText = new InsertTextRequest() { Text = "\n\nx", Location = new Location() { SegmentId = "", Index = 4 } } });
requests.Add(new Request() { CreateNamedRange = new CreateNamedRangeRequest() { Name = "BoddyTitle", Range = new Range() { SegmentId = "", StartIndex = 3, EndIndex = 4 } } });
requests.Add(new Request() { CreateNamedRange = new CreateNamedRangeRequest() { Name = "BoddyContent", Range = new Range() { SegmentId = "", StartIndex = 6, EndIndex = 7 } } });
}
// requests.Add(new Request() { DeleteContentRange = new DeleteContentRangeRequest() { Range = new Range { StartIndex = 1, EndIndex = max - 1 } } });
if (textBox1.Text != "" && textBox2.Text != "")
{
requests.Add(new Request() { ReplaceNamedRangeContent = new ReplaceNamedRangeContentRequest() { Text = textBox1.Text.Replace("\r\n", "\n"), NamedRangeName = "BoddyTitle" } });
requests.Add(new Request() { ReplaceNamedRangeContent = new ReplaceNamedRangeContentRequest() { Text = textBox2.Text.Replace("\r\n", "\n"), NamedRangeName = "BoddyContent" } });
}
else { MessageBox.Show("Textbox Empty" ); }
if (requests.Count >0)
{
BatchUpdateDocumentRequest body = new BatchUpdateDocumentRequest { Requests = requests };
dservice.Documents.BatchUpdate(body, docid).Execute();Process.Start("https://docs.google.com/document/d/doc_id/edit?usp=sharing");
}

Related

Problem with stock items, always returns 0 wsdl NetSuite c#

I try to return the stock of the items and I can not get it. Could someone guide me and tell me what I'm doing wrong?
This is my code, quantityAvailable is always 0 and location is null. This is an excerpt from my source code:
var recordRefs = new List<RecordRef>();
var ExternalIds = new List<string>();
ExternalIds.Add("REV0001");
ExternalIds.Add("REV0002");
foreach (string externalId in ExternalIds)
{
recordRefs.Add(new RecordRef
{
externalId = externalId,
type = RecordType.InventoryItem,
typeSpecified = true
});
}
var request1 = new ItemSearchBasic
{
externalId = new SearchMultiSelectField
{
#operator = SearchMultiSelectFieldOperator.anyOf,
operatorSpecified = true,
searchValue = recordRefs.ToArray()
}
};
SearchResult response = Client.Service.search(request1);
if (response.status.isSuccess)
{
if (response.totalRecords > 1)
{
Record[] records;
records = response.recordList;
for (int lcv = 0; lcv <= records.Length - 1; lcv++)
{
if (records[lcv].GetType().Name == "InventoryItem")
{
Console.WriteLine(((InventoryItem)records[lcv]).itemId);
Console.WriteLine(((InventoryItem)records[lcv]).internalId);
Console.WriteLine(((InventoryItem)records[lcv]).quantityAvailable);
Console.WriteLine(((InventoryItem)records[lcv]).averageCost);
}
}
}
}

CADES signature with Json data in C#

I have below json data I need to apply CAdES-BES Signature with Automatic JSON Canonicalization. Please find my json data below. Helpful link from https://www.example-code.com/Csharp/itida_egypt_cades_bes_json_canonicalization.asp. I follow the steps but still digital signature is not applying. Its returns normal json data.
[HttpGet]
[Route("api/invoiceLines/")]
public IHttpActionResult getEInvoiceLines()
{
Chilkat.Crypt2 crypt = new Chilkat.Crypt2();
crypt.VerboseLogging = true;
Chilkat.Cert cert = new Chilkat.Cert();
cert.VerboseLogging = true;
// Set the smart card PIN, which will be needed for signing.
cert.SmartCardPin = "1245345";
// There are many ways to load the certificate.
// This example was created for a customer using an ePass2003 USB token.
// Assuming the USB token is the only source of a hardware-based private key..
bool success = cert.LoadFromSmartcard(#"E"); //Is this Right way To load certificate ?
Chilkat.JsonObject cmsOptions = new Chilkat.JsonObject();
// Setting "DigestData" causes OID 1.2.840.113549.1.7.5 (digestData) to be used.
cmsOptions.UpdateBool("DigestData", true);
cmsOptions.UpdateBool("OmitAlgorithmIdNull", true);
// Indicate that we are passing normal JSON and we want Chilkat do automatically
// do the ITIDA JSON canonicalization:
cmsOptions.UpdateBool("CanonicalizeITIDA", true);
crypt.CmsOptions = cmsOptions.Emit();
// The CadesEnabled property applies to all methods that create CMS/PKCS7 signatures.
// To create a CAdES-BES signature, set this property equal to true.
crypt.CadesEnabled = true;
crypt.HashAlgorithm = "sha256";
Chilkat.JsonObject jsonSigningAttrs = new Chilkat.JsonObject();
jsonSigningAttrs.UpdateInt("contentType", 1);
jsonSigningAttrs.UpdateInt("signingTime", 1);
jsonSigningAttrs.UpdateInt("messageDigest", 1);
jsonSigningAttrs.UpdateInt("signingCertificateV2", 1);
crypt.SigningAttributes = jsonSigningAttrs.Emit();
// By default, all the certs in the chain of authentication are included in the signature.
// If desired, we can choose to only include the signing certificate:
crypt.IncludeCertChain = false;
EInvoiceModel.Example ds = new EInvoiceModel.Example();
//Start issuer details
ds.issuer = new EInvoiceModel.Issuer();
ds.issuer.type = "B";
ds.issuer.id = "113317713";
ds.issuer.name = "Issuer Company";
//Start issuer address details
ds.issuer.address = new EInvoiceModel.Address();
ds.issuer.address.branchID = "1";
ds.issuer.address.country = "EG";
ds.issuer.address.governate = "Cairo";
ds.issuer.address.regionCity = "Nasr City";
ds.issuer.address.street = "stree1";
ds.issuer.address.buildingNumber = "Bldg. 0";
ds.issuer.address.postalCode = "68030";
ds.issuer.address.floor = "1";
ds.issuer.address.room = "123";
ds.issuer.address.landmark = "7660 Melody Trail";
ds.issuer.address.additionalInformation = "beside Town Hall";
//Start Receiver details
ds.receiver = new EInvoiceModel.Receiver();
ds.receiver.type = "B";
ds.receiver.id = "3125617";
ds.receiver.name = "Receiver company";
//Start Receiver address datails
ds.receiver.address = new EInvoiceModel.AddressReceiver();
ds.receiver.address.country = "EG";
ds.receiver.address.governate = "Cairo";
ds.receiver.address.regionCity = "Nasr City";
ds.receiver.address.street = "stree1";
ds.receiver.address.buildingNumber = "Bldg. 0";
ds.receiver.address.postalCode = "68030";
ds.receiver.address.floor = "1";
ds.receiver.address.room = "123";
ds.receiver.address.landmark = "7660 Melody Trail";
ds.receiver.address.additionalInformation = "beside Town Hall";
//Document type & version
ds.documentType = "i";
ds.documentTypeVersion = "1.0";
DateTime d = new DateTime();
ds.dateTimeIssued = d; //Invoice date
ds.taxpayerActivityCode = "9478"; //needed info
ds.internalID = "WADIn1234"; //Internal Invoice number
ds.salesOrderReference = "So1234"; //So number //optional
ds.salesOrderDescription = "SO1234"; //So additional Info //optional
ds.proformaInvoiceNumber = "SoPro123"; //optional
//Invoiceline Start
ds.invoiceLines = new List<EInvoiceModel.InvoiceLine>
{
new EInvoiceModel.InvoiceLine
{
description = "Computer1",
itemType = "GPC",
itemCode = "10001774",
unitType = "EA",
quantity = 2,
internalCode = "IC0",
salesTotal = 23.99,
total = 2969.89,
valueDifference = 7.00,
totalTaxableFees = 817.42,
netTotal = 880.71,
itemsDiscount = 5.00,
unitValue = new EInvoiceModel.UnitValue
{
currencySold = "EUR",
amountEGP = 189.40,
amountSold = 10.00,
currencyExchangeRate = 18.94,
},
discount = new EInvoiceModel.Discount
{
rate = 7,
amount = 66.29
},
taxableItems = new List<EInvoiceModel.TaxableItem>
{
new EInvoiceModel.TaxableItem
{
taxType = "T1",
amount = 272.07,
subType = "T1",
rate = 12
}
}
}
}; //Invoice Lines End
//Items total Discount and Sales/NetAmount
ds.totalDiscountAmount = 76.29;
ds.totalSalesAmount = 1609.90;
ds.netAmount = 1533.61;
//Tax Total Start
ds.taxTotals = new List<EInvoiceModel.TaxTotal>
{
new EInvoiceModel.TaxTotal
{
taxType = "T1",
amount = 477.54,
}
};//Tax Total End
//Total Sales Amount & discounts
ds.totalAmount = 5191.50;
ds.extraDiscountAmount = 5.00;
ds.totalItemsDiscountAmount = 14.00;
string strResultJson = JsonConvert.SerializeObject(ds);
//System.IO.File.WriteAllText(#"C:\inetpub\wwwroot\path.json", strResultJson);
// File.WriteAllText(#"ds.json", strResultJson);
// string jsonToSign = "{ ... }";
string jsonToSign = strResultJson;
// Create the CAdES-BES signature.
crypt.EncodingMode = "base64";
// Make sure we sign the utf-8 byte representation of the JSON string
crypt.Charset = "utf-8";
string sigBase64 = crypt.SignStringENC(jsonToSign);
// return Ok(ds);
return Ok(sigBase64);
}
public static string SerializeObject2(object obj, int indent = 0)
{
var sb = new StringBuilder();
if (obj != null)
{
string indentString = new string(' ', indent);
if (obj is string || obj.IsNumber())
{
sb.Append($"\"{obj}\"");
}
else if (obj.GetType().BaseType == typeof(Enum))
{
sb.Append($"\"{obj.ToString()}\"");
}
else if (obj is Array)
{
var elems = obj as IList;
sb.Append($"{indentString}- [{elems.Count}] :\n");
for (int i = 0; i < elems.Count; i++)
{
sb.Append(SerializeObject2(elems[i], indent + 4));
}
}
else
{
Type objType = (obj).GetType();
PropertyInfo[] props = objType.GetProperties();
foreach (PropertyInfo prop in props)
{
if (prop.GetIndexParameters().Length == 0)
{
object propValue = prop.GetValue(obj);
var elems = propValue as IList;
if (elems != null)
{
sb.Append($"\"{prop.Name.ToUpper()}\"");
foreach (var item in elems)
{
sb.Append($"\"{prop.Name.ToUpper()}\"");
sb.Append(SerializeObject2(item, indent + 4));
}
}
else
{
if (Assembly.GetExecutingAssembly().DefinedTypes.Select(p => p.Assembly).ToList().Contains(prop.PropertyType.Assembly))
{
sb.Append($"\"{prop.Name.ToUpper()}\"");
sb.Append(SerializeObject2(propValue, indent + 4));
}
else
{
sb.Append($"\"{prop.Name.ToUpper()}\"\"{propValue}\"");
}
}
}
else if (objType.GetProperty("Item") != null)
{
int count = -1;
if (objType.GetProperty("Count") != null &&
objType.GetProperty("Count").PropertyType == typeof(int))
{
count = (int)objType.GetProperty("Count").GetValue(obj, null);
}
for (int i = 0; i < count; i++)
{
object val = prop.GetValue(obj, new object[] { i });
sb.Append(SerializeObject2(val, indent + 4));
}
}
}
}
}
return sb.ToString();
}

ElasticSearch 5.1 filtered query with multiply filters

I need to use several filters (range and terms) for query request with ElasticSearch 5.1. If I use them separately (only one filter) it is OK:
var o = new
{
size = 20,
query = new
{
#bool = new
{
must = new
{
query_string = new
{
fields = new[] { "Title" },
query = search_query
}
},
filter = new
{
terms = new
{
SourceId = new[] {10,11,12}
}
}
}
}
};
OR
var o = new
{
size = 20,
query = new
{
#bool = new
{
must = new
{
query_string = new
{
fields = new[] { "Title" },
query = search_query
}
},
filter = new
{
range = new
{
PostPubDate = new
{
gte = "2015-10-01T00:00:00",
lte = "2015-11-01T12:00:00"
}
}
}
}
}
};
If I use them both I get response 400 error:
string url = "http://localhost:9200/neg_collector/posts/_search";
var request = (HttpWebRequest)HttpWebRequest.Create(url);
var o = new
{
size = 20,
query = new
{
#bool = new
{
must = new
{
query_string = new
{
fields = new[] { "Title" },
query = search_query
}
},
filter = new
{
terms = new
{
SourceId = new[] {10,11,12}
},
range = new
{
PostPubDate = new
{
gte = "2015-10-01T00:00:00",
lte = "2015-11-01T12:00:00"
}
}
}
}
}
};
request.Method = "POST";
var jsonObj = JsonConvert.SerializeObject(o);
var data = Encoding.UTF8.GetBytes(jsonObj);
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = data.Length;
using (var stream = request.GetRequestStream())
{
stream.Write(data, 0, data.Length);
}
string responseString = string.Empty;
var response = (HttpWebResponse)request.GetResponse();
What am I doing wrong? Thank you
Your filter simply needs to be an array of objects:
...
filter = new object[]
{
new {
terms = new
{
SourceId = new[] {10,11,12}
}
},
new {
range = new
{
PostPubDate = new
{
gte = "2015-10-01T00:00:00",
lte = "2015-11-01T12:00:00"
}
}
}
}

PayPal API & MVC5: Get Price from another controller

I'm trying to set up PayPal to accept payment from my site which calculate fees based on the number of photos they uploaded. Followed a tutorial, but I wanted to pass the price which I calculated in my other controller.
My PayPal controller:
public ActionResult PaymentWithPaypal()
{
APIContext apiContext = PayPalConfig.GetAPIContext();
try
{
string payerId = Request.Params["PayerID"];
if (string.IsNullOrEmpty(payerId))
{
string baseURI = Request.Url.Scheme + "://" + Request.Url.Authority + "/Paypal/PaymentWithPayPal?";
var guid = Convert.ToString((new Random()).Next(100000));
var createdPayment = this.CreatePayment(apiContext, baseURI + "guid=" + guid);
var links = createdPayment.links.GetEnumerator();
string paypalRedirectUrl = null;
while (links.MoveNext())
{
Links lnk = links.Current;
if (lnk.rel.ToLower().Trim().Equals("approval_url"))
{
paypalRedirectUrl = lnk.href;
}
}
Session.Add(guid, createdPayment.id);
return Redirect(paypalRedirectUrl);
}
else
{
var guid = Request.Params["guid"];
var executedPayment = ExecutePayment(apiContext, payerId, Session[guid] as string);
if (executedPayment.state.ToLower() != "approved")
{
return View("FailureView");
}
}
}
catch (Exception ex)
{
Logger.Log("Error" + ex.Message);
return View("FailureView");
}
return View("SuccessView");
}
private PayPal.Api.Payment payment;
private PayPal.Api.Payment ExecutePayment(APIContext apiContext, string payerId, string paymentId)
{
var paymentExecution = new PaymentExecution() { payer_id = payerId };
this.payment = new PayPal.Api.Payment() { id = paymentId };
return this.payment.Execute(apiContext, paymentExecution);
}
private PayPal.Api.Payment CreatePayment(APIContext apiContext, string redirectUrl)
{
var itemList = new ItemList() { items = new List<Item>() };
itemList.items.Add(new Item()
{
name = "Participation Fee",
currency = "USD",
price = "5",
quantity = "1",
sku = "sku"
});
var payer = new Payer() { payment_method = "paypal" };
var redirUrls = new RedirectUrls()
{
cancel_url = redirectUrl,
return_url = redirectUrl
};
var details = new Details()
{
tax = "1",
shipping = "1",
subtotal = "5"
};
var amount = new Amount()
{
currency = "USD",
total = "7",
details = details
};
var transactionList = new List<Transaction>();
transactionList.Add(new Transaction()
{
description = "Transaction description.",
invoice_number = "your invoice number",
amount = amount,
item_list = itemList
});
this.payment = new PayPal.Api.Payment()
{
intent = "sale",
payer = payer,
transactions = transactionList,
redirect_urls = redirUrls
};
return this.payment.Create(apiContext);
}
Controller where my price is calculated:
int Asection;
int Bsection;
int Csection;
int Dsection;
if (viewPhotos.GetA1.Any() || viewPhotos.GetA2.Any() || viewPhotos.GetA3.Any() || viewPhotos.GetA4.Any())
{
Asection = 1;
}
else
{
Asection = 0;
}
if (viewPhotos.GetB1.Any() || viewPhotos.GetB2.Any() || viewPhotos.GetB3.Any() || viewPhotos.GetB4.Any())
{
Bsection = 1;
}
else
{
Bsection = 0;
}
if (viewPhotos.GetC1.Any() || viewPhotos.GetC2.Any() || viewPhotos.GetC3.Any() || viewPhotos.GetC4.Any())
{
Csection = 1;
}
else
{
Csection = 0;
}
if (viewPhotos.GetD1.Any() || viewPhotos.GetD2.Any() || viewPhotos.GetD3.Any() || viewPhotos.GetD4.Any())
{
Dsection = 1;
}
else
{
Dsection = 0;
}
int TotalSection = Asection + Bsection + Csection + Dsection;
viewPhotos.MoneyValue = TotalSection;
int RequiredMoney;
if (TotalSection == 1)
{
RequiredMoney = 20;
}
else if (TotalSection == 2)
{
RequiredMoney = 25;
}
else if (TotalSection == 3)
{
RequiredMoney = 30;
}
else
{
RequiredMoney = 36;
}
viewPhotos.RequiredMoney = RequiredMoney;
return View(viewPhotos);
My view where price was shown to user:
<p>You will need to pay participation fees USD #Model.RequiredMoney.</p>
<h3>Total: USD #Model.RequiredMoney</h3>
#Html.ActionLink("Make Payment with PayPal", "PaymentWithPaypal", "Paypal")
So far the above codes work with the default testing item price and detail on the site. Would appreciate if anyone could help to show how do I set the amount to be collected by PayPal to my calculated price, without any shipping or tax. Thanks in advance.
After searching and reviewing the log for a while, here's how I solved my problem:
At the controller where I calculated my price, I used TempData to store my price:
TempData["ParticipationFee"] = RequiredMoney;
Then at the PaypalController, under CreatePayment function,
var itemList = new ItemList() { items = new List<Item>() };
string FeeAmount = TempData["ParticipationFee"].ToString();
itemList.items.Add(new Item()
{
name = "Participation Fee",
currency = "USD",
price = FeeAmount,
quantity = "1",
sku = "sku"
});
Hit F5 and got a successful response from Paypal Sandbox. Woot!

Can't save invoice on qb online correctly

I am able to create invoice on quickbook online, but when i check quickbook invoice online, it create the item lists but the price and description is missing. What i am doing wrong.
invoice.AlternateId = new NameValue[] { new NameValue() { Name = "InvoiceID", Value = service.InvoiceId } };
InvoiceHeader Header = new InvoiceHeader();
Header.DocNumber = service.InvoiceId;
Header.TxnDate = service.ServiceDate;
Header.TxnDateSpecified = true;
Header.Msg = service.Note.ToString();
Header.Note = service.Note.ToString();
Header.CustomerId = new IdType() { idDomain = idDomainEnum.QBO, Value = service.CustomerNumberOnline };
Header.Currency = currencyCode.USD;
Header.ShipDate = service.ServiceDate;
Header.ShipDateSpecified = true;
//Print and Email Option fields
if (EmailPrintOption == "Both")
{
Header.ToBeEmailed = true;
Header.ToBeEmailedSpecified = true;
Header.ToBePrinted = true;
Header.ToBePrintedSpecified = true;
}
else if (EmailPrintOption == "print")
{
Header.ToBePrinted = true;
Header.ToBePrintedSpecified = true;
}
else if (EmailPrintOption == "email")
{
Header.ToBeEmailed = true;
Header.ToBeEmailedSpecified = true;
}
else
{
Header.ToBeEmailed = false;
Header.ToBeEmailedSpecified = false;
Header.ToBePrinted = false;
Header.ToBePrintedSpecified = false;
}
PhysicalAddress BillAddress = new PhysicalAddress();
BillAddress.Line1 = service.SoldToAddress;
BillAddress.City = service.SoldToCity;
BillAddress.CountrySubDivisionCode = service.SoldToState;
BillAddress.PostalCode = service.SoldToZip;
BillAddress.Tag = new string[] { "Billing" };
Header.BillAddr = BillAddress;
PhysicalAddress ShipAddress = new PhysicalAddress();
ShipAddress.Line1 = service.JobJocationAddress;
ShipAddress.City = service.JobLocationCity;
ShipAddress.CountrySubDivisionCode = service.JobLocationState;
ShipAddress.PostalCode = service.JobLocationZip;
BillAddress.Tag = new string[] { "Shipping" };
Header.ShipAddr = ShipAddress;
decimal discount;
if (decimal.TryParse(service.Discount, out discount))
{
Header.ItemElementName = ItemChoiceType2.DiscountAmt;
Header.Item = -1 * discount; //discount must be negative
}
InvoiceLine[] InvoiceLines = new InvoiceLine[TaskOnlineIDs.Count];
object[] intuitItems = new object[TaskOnlineIDs.Count];
for (int i = 0; i < InvoiceLines.Length; i++)
{
InvoiceLines[i] = new InvoiceLine();
InvoiceLines[i].ItemsElementName = new Intuit.Ipp.Data.Qbo.ItemsChoiceType2[]
{
Intuit.Ipp.Data.Qbo.ItemsChoiceType2.ItemId
};
InvoiceLines[i].Items = new object[] {
new IdType(){idDomain=idDomainEnum.QBO, Value=TaskOnlineIDs[i]}
};
}
invoice.Line = InvoiceLines;
Header.SalesTermName = service.PaymentType;
Header.SalesRepName = service.TechName;
Header.PONumber = service.PurchaseOrder;
invoice.Header = Header;
What i miss here ??
Here what happen is, when i add invoice lines to invoice it set amount of each item to "0" by default, so when i try to add discount pragmatically it give's me error of discount greater than subtotal which is correct. But my question is why do i need to add cost for each item explicitly when i have already defined them earlier. We should add only itemId and rest QB should calculate.

Categories