I'm trying to send a mail chimp campaign using asp.net, actually i created successfully the campaign and i can see it through my profile but also i want to send it through my code here is my code so if any one can help!!
private static void CreateCampaignAndSend(string apiKey, string listID)
{
Int32 TemplateID = 0;
string campaignID = string.Empty;
// compaign Create Options
var campaignCreateOpt = new campaignCreateOptions
{
list_id = listID,
subject = "subject",
from_email = "cbx#abc.com",
from_name = "abc",
template_id = TemplateID
};
// Content
var content = new Dictionary<string, string>
{
{"html", "Lots of cool stuff here."}
};
// Conditions
var csCondition = new List<campaignSegmentCondition>();
var csC = new campaignSegmentCondition {field = "interests-" + 123, op = "all", value = ""};
csCondition.Add(csC);
// Options
var csOptions = new campaignSegmentOptions {match = "all"};
// Type Options
var typeOptions = new Dictionary<string, string>
{
{"offset-units", "days"},
{"offset-time", "0"},
{"offset-dir", "after"}
};
// Create Campaigns
var campaignCreate = new campaignCreate(new campaignCreateInput(apiKey, EnumValues.campaign_type.plaintext, campaignCreateOpt, content, csOptions, typeOptions));
campaignCreateOutput ccOutput = campaignCreate.Execute();
campaignSendNow c=new campaignSendNow();
List<Api_Error> error = ccOutput.api_ErrorMessages; // Catching API Errors
if (error.Count <= 0)
{
campaignID = ccOutput.result;
}
else
{
foreach (Api_Error ae in error)
{
Console.WriteLine("\n ERROR Creating Campaign : ERRORCODE\t:" + ae.code + "\t ERROR\t:" + ae.error);
}
}
}
Related
I am trying to use AWS SDK for .NET Core.
Create a table to count views on videos.
Add a view count for a day.
Increment existing count for a day.
Query for video counts between two dates for a video.
.NET Core AWS SDK uses Async methods which are not documented in AWS. There is a feature request on their github page for this to happen.... but it is dated from last year. (https://github.com/aws/aws-sdk-net/issues/787)
CREATE THE TABLE
This works and creates a table on the AWS Console.
var ctRequest = new CreateTableRequest
{
AttributeDefinitions = new List<AttributeDefinition>()
{
new AttributeDefinition
{
AttributeName = "ViewUid",
AttributeType = ScalarAttributeType.S
},
new AttributeDefinition
{
AttributeName = "ViewDate",
AttributeType = ScalarAttributeType.S
}
},
KeySchema = new List<KeySchemaElement>
{
new KeySchemaElement
{
AttributeName = "ViewUid",
KeyType = KeyType.HASH //Partition key
},
new KeySchemaElement
{
AttributeName = "ViewDate",
KeyType = KeyType.RANGE
}
},
ProvisionedThroughput = new ProvisionedThroughput
{
ReadCapacityUnits = 5,
WriteCapacityUnits = 6
},
TableName = _settings.AWSDynamoDBViewCountTable
};
var response = _client.CreateTableAsync(ctRequest).Result;
UPDATE AND ITEM WITH AUTO-INCREMENT A FIELD
This, sadly, is where i hit issues. The old docs are found here under the Atomic Counter section. (https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/LowLevelDotNetItemCRUD.html)
Invalid ConditionExpression: Syntax error; token: \"SET\", near: \"SET
VC\"
var viewData = new Document();
viewData["ViewUid"] = videoUid; //Table entry UID
viewData["VideoId"] = videoId; // Video ID
viewData["ViewDate"] = date;
viewData["ViewCount"] = 0;
//Document result = await _viewCountTable.PutItemAsync(viewData);
Expression expr = new Expression();
expr.ExpressionStatement = "SET #VC = #VC + :val";
expr.ExpressionAttributeValues[":val"] = 1;
expr.ExpressionAttributeNames["#VC"] = "ViewCount";
var updateConfig = new UpdateItemOperationConfig() {
ConditionalExpression = expr,
ReturnValues = ReturnValues.UpdatedNewAttributes
};
var result = await _viewCountTable.UpdateItemAsync(viewData, updateConfig);
return result;
QUERY FOR DATE RANGE
Get one video's view count for a date range.
string queryTimeSpanStartString = dateFrom.ToString(AWSSDKUtils.ISO8601DateFormat);
string queryTimeSpanEndString = dateTo.ToString(AWSSDKUtils.ISO8601DateFormat);
var request = new QueryRequest
{
TableName = _settings.AWSDynamoDBViewCountTable,
KeyConditions = new Dictionary<string, Condition>()
{
{
"VideoId", new Condition()
{
ComparisonOperator = "EQ",
AttributeValueList = new List<AttributeValue>()
{
new AttributeValue { S = videoId }
}
}
},
{
"ViewDate",
new Condition
{
ComparisonOperator = "BETWEEN",
AttributeValueList = new List<AttributeValue>()
{
new AttributeValue { S = queryTimeSpanStartString },
new AttributeValue { S = queryTimeSpanEndString }
}
}
}
}
};
var response = await _client.QueryAsync(request);
Any help would be appreciated.
I was able to update the ViewCount with the following code:
string tableName = "videos";
var request = new UpdateItemRequest
{
Key = new Dictionary<string, AttributeValue>() { { "ViewUid", new AttributeValue { S = "replaceVideoIdhere" } } },
ExpressionAttributeNames = new Dictionary<string, string>()
{
{"#Q", "ViewCount"}
},
ExpressionAttributeValues = new Dictionary<string, AttributeValue>()
{
{":incr", new AttributeValue {N = "1"}}
},
UpdateExpression = "SET #Q = #Q + :incr",
TableName = tableName
};
var response = await _dynamoDbClient.UpdateItemAsync(request);
I created a table called "videos" with a partition key named "ViewUid" as string. Let me know if this works for you.
Trying to follow the PayPal .NET tutorial on GitHub.
I've fixed it the best I can but still getting a lot of errors related to missing functions etc. Here is what I have so far:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using PayPal.Api;
using System.Configuration;
using PayPal.Sample.Utilities;
using System.Web.Providers.Entities;
/// <summary>
/// Summary description for OAuthTokenCredential
/// </summary>
public class CredentialManager
{
Dictionary<string, string> _Config = null;
string _AccessToken = string.Empty;
APIContext _APIConText = null;
public CredentialManager()
{
// Get a reference to the config
var config = ConfigManager.Instance.GetProperties();
_Config = config;
// Use OAuthTokenCredential to request an access token from PayPal
var accessToken = new OAuthTokenCredential(config).GetAccessToken();
_AccessToken = accessToken;
//API Context
var apiContext = new APIContext(accessToken);
_APIConText = apiContext;
// Initialize the apiContext's configuration with the default configuration for this application.
apiContext.Config = ConfigManager.Instance.GetProperties();
// Define any custom configuration settings for calls that will use this object.
apiContext.Config["connectionTimeout"] = "1000"; // Quick timeout for testing purposes
// Define any HTTP headers to be used in HTTP requests made with this APIContext object
//if (apiContext.HTTPHeaders == null)
//{
// apiContext.HTTPHeaders = new Dictionary<string, string>();
//}
//apiContext.HTTPHeaders["some-header-name"] = "some-value";
}
public Payment GetPAyment(APIContext apiContext, string paymentid)
{
var payment = Payment.Get(apiContext, paymentid);
return payment;
}
public bool CreatePayment()
{
try
{
bool Success = false;
//var apiContext = Configuration.GetAPIContext();
string payerId = Request.Params["PayerID"];
if (string.IsNullOrEmpty(payerId))
{
var itemList = new ItemList()
{
items = new List<Item>()
{
new Item()
{
name = "Item Name",
currency = "USD",
price = "15",
quantity = "5",
sku = "sku"
}
}
};
var payer = new Payer() { payment_method = "paypal" };
var baseURI = Request.Url.Scheme + "://" + Request.Url.Authority + "/PaymentWithPayPal.aspx?";
var guid = Convert.ToString((new Random()).Next(100000));
var redirectUrl = baseURI + "guid=" + guid;
var redirUrls = new RedirectUrls()
{
cancel_url = redirectUrl + "&cancel=true",
return_url = redirectUrl
};
var details = new Details()
{
tax = "15",
shipping = "10",
subtotal = "75"
};
var amount = new Amount()
{
currency = "USD",
total = "100.00", // Total must be equal to sum of shipping, tax and subtotal.
details = details
};
var transactionList = new List<Transaction>();
transactionList.Add(new Transaction()
{
description = "Transaction description.",
invoice_number = Common.GetRandomInvoiceNumber(),
amount = amount,
item_list = itemList
});
var payment = new Payment()
{
intent = "sale",
payer = payer,
transactions = transactionList,
redirect_urls = redirUrls
};
var createdPayment = payment.Create(_APIConText);
var links = createdPayment.links.GetEnumerator();
while (links.MoveNext())
{
var link = links.Current;
if (link.rel.ToLower().Trim().Equals("approval_url"))
{
this.flow.RecordRedirectUrl("Redirect to PayPal to approve the payment...", link.href);
}
}
Session.Add(guid, createdPayment.id);
Session.Add("flow-" + guid, this.flow);
}
else
{
var guid = Request.Params["guid"];
var paymentId = Session[guid] as string;
var paymentExecution = new PaymentExecution() { payer_id = payerId };
var payment = new Payment() { id = paymentId };
var executedPayment = payment.Execute(apiContext, paymentExecution);
}
return Success;
}
catch(Exception ex)
{
return false;
}
}
}
I'm getting random errors on the following:
using PayPal.Sample.Utilities;
string payerId = Request.Params["PayerID"];
var baseURI = Request.Url.Scheme + "://" + Request.Url.Authority + "/PaymentWithPayPal.aspx?";
invoice_number = Common.GetRandomInvoiceNumber(),
Session.Add(guid, createdPayment.id);
Session.Add("flow-" + guid, this.flow);
var guid = Request.Params["guid"];
var paymentId = Session[guid] as string;
var executedPayment = payment.Execute(_APIConText, paymentExecution);
Errors:
"Request" does not exist
"Common" does not exist
"flow" does not exist
"session" is not valid in its current type
I think I'm just missing a reference or something. I'm trying to do it for C# ASP .Net (not MVC)
You'll find the "Common" class here
Common.GetRandomInvoiceNumber() is just generating a random number. I think you would just replace that with your own generated invoice number.
I am not able to add or update milestones field for the Features in the Rally. If anyone having the code available using C# to update the same, please share with me. I am searching and doing from last one week with no luck.
When I am trying to add/Update milestones in the Features. I am getting the error as "Could not read: Could not read referenced object null". My code is as follows:-
public DynamicJsonObject UpdateFeaturesbyName(string fea, string bFun)
{
//getting list of Feature.
Request feat = new Request("PortfolioItem/Feature");
feat.Query = new Query("Name", Query.Operator.Equals, fea);
QueryResult TCSResults = restApi.Query(feat);
foreach (var res in TCSResults.Results)
{
var steps = res["Milestones"];
Request tsteps = new Request(steps);
QueryResult tstepsResults = restApi.Query(tsteps);
foreach (var item in tstepsResults.Results)
{
}
if (res.Name == fea)
{
var targetFeature = TCSResults.Results.FirstOrDefault();
DynamicJsonObject toUpdate = new DynamicJsonObject();
//toUpdate["Milestones"] = "";
// CreateResult createResult = restApi.Create(steps._ref, toUpdate);
// String contentRef = steps._ref;
//String contentRef = createResult._ref;
string[] value = null;
string AccCri = string.Empty;
if (!string.IsNullOrWhiteSpace(bFun))
{
value = bFun.Split(new string[] { "\r\n", "\n" }, StringSplitOptions.None);
foreach (string item in value)
{
//if (string.IsNullOrWhiteSpace(AccCri))
// AccCri = item;
//else
// AccCri = AccCri + "<br/>" + item;
if (!string.IsNullOrWhiteSpace(item))
{
//Query for Milestone.
Request ms = new Request("Milestone");
ms.Fetch = new List<string>() { "Name", "ObjectID" };
ms.Query = new Query("Name", Query.Operator.Equals, item);
QueryResult msResults = restApi.Query(ms);
var targetMLResult = msResults.Results.FirstOrDefault();
long MLOID = targetMLResult["ObjectID"];
DynamicJsonObject tarML = restApi.GetByReference("Milestone", MLOID, "Name", "_ref", "DisplayColor");
DynamicJsonObject targetML = new DynamicJsonObject();
targetML["Name"] = tarML["Name"];
//targetML["_ref"] = tarML["_ref"];
targetML["_ref"] = "/milestone/" + Convert.ToString(MLOID);
targetML["DisplayColor"] = tarML["DisplayColor"];
// Grab collection of existing Milestones.
var existingMilestones = targetFeature["Milestones"];
long targetOID = targetFeature["ObjectID"];
// Milestones collection on object is expected to be a System.Collections.ArrayList.
var targetMLArray = existingMilestones;
var tagList2 = targetMLArray["_tagsNameArray"];
tagList2.Add(targetML);//
//targetMLArray.Add(targetML);
targetMLArray["_tagsNameArray"] = tagList2;
toUpdate["Milestones"] = targetMLArray;
OperationResult updateResult = restApi.Update(res._ref, toUpdate);
bool resp = updateResult.Success;
}
}
}
//toUpdate["c_AcceptanceCriteria"] = AccCri;
//OperationResult updateResult = restApi.Update(res._ref, toUpdate);
}
}
var features = TCSResults.Results.Where(p => p.Name == fea).FirstOrDefault();
var featuresref = features._ref;
return features;
}
Now that v3.1.1 of the toolkit has been released you can use the AddToCollection method to do this.
Otherwise, you can still always just update the full collection. The value should be an arraylist of objects with _ref properties.
Check out this example (which adds tasks to defects, but should be very similar to what you're doing): https://github.com/RallyCommunity/rally-dot-net-rest-apps/blob/master/UpdateTaskCollectionOnDefect/addTaskOnDefect.cs
I am using C# implementation of netsuite api from web reference com.netsuite.webservices
I released filter fileSearch.basic by name (you can see it commented) it is working fine.
Please help to write function to achieve all attached files for current user. Something is wrong in this code, it filters nothing and showing me all files as it is without any filter. Please help me.
public static void GetFileAttachmentByCustomerId(string customerId)
{
using (NetSuiteService netSuiteService = GetNetSuiteService())
{
FileSearch fileSearch = new FileSearch();
// this works fine (filter files by name)
//SearchStringField nameSearchParams = new SearchStringField
//{
// #operator = SearchStringFieldOperator.contains,
// operatorSpecified = true,
// searchValue = "some name",
//};
//fileSearch.basic = new FileSearchBasic() { name = nameSearchParams };
// this code not filter files at all
{
RecordRef nsCustomerRef = new RecordRef
{
internalId = customerId,
type = RecordType.customer,
typeSpecified = true,
};
SearchMultiSelectField shopperSearchParam = new SearchMultiSelectField
{
#operator = SearchMultiSelectFieldOperator.anyOf,
operatorSpecified = true,
searchValue = new RecordRef[] { nsCustomerRef }
};
fileSearch.shopperJoin = new CustomerSearchBasic { internalId = shopperSearchParam };
}
SearchResult result = netSuiteService.search(fileSearch);
// Get connected objects
{
Customer customer = GetCustomerById(netSuiteService, customerId);
Account account = GetAccountById(netSuiteService, "301395"); //
Folder folder = GetFolderById(netSuiteService, "3962");
}
File file = (File)result.recordList.First();
byte[] fileContent = GetFileContentByInternalId(file.internalId);
}
}
.
Try this:
var nsCustomerRef = new RecordRef
{
internalId = "4",
type = RecordType.employee,
typeSpecified = true,
};
var currentUser = new SearchMultiSelectField()
{
operatorSpecified = true,
#operator = SearchMultiSelectFieldOperator.anyOf,
searchValue = new List<RecordRef>() {nsCustomerRef}.ToArray()
};
var fileSearchBasic = new FileSearchBasic() {owner = currentUser};
var fileSearch = new FileSearch() { basic = fileSearchBasic };
var result = netSuiteService.search(fileSearch);
var file = (File)result.recordList.First();
I'm trying to specify a Product/Service list item for invoice line items of invoices that I am importing to QuickBooks Online (QBO) company file and I am getting an error.
Error I receive is:
Intuit.Ipp.Exception.IdsException: InternalServerError ---> Intuit.Ipp.Exception.EndpointNotFoundException: Ids service endpoint was not found.
The exception doesn't give any further breakdown as to if what I'm doing is valid or not.
My unit test method:
[TestMethod()]
public void CreateTest()
{
Entities.Invoice invoice = new Entities.Invoice();
invoice.ReferenceId = Guid.NewGuid().ToString("N").Substring(0, 10);
invoice.CreatedDate = DateTime.Now;
invoice.CustomerId = 1;
invoice.LineItems.Add(new InvoiceLine() { ItemName = "Initial Funding", Description = "Initial Funding", Amount = 5500 });
invoice.LineItems.Add(new InvoiceLine() { ItemName = "Lien Fee", Description = "Lien Fee", Amount = 100 });
IPPRestProfile restProfile = new IPPRestProfile(realmId, accessToken, accessTokenSecret, Intuit.Ipp.Core.IntuitServicesType.QBO, consumerKey, consumerSecret);
IPP.Invoices target = new IPP.Invoices(restProfile);
Intuit.Ipp.Data.Invoice actual = target.Create(invoice);
if (actual != null)
{
Console.WriteLine("QB Invoice ID: {0}", actual.Id);
Console.WriteLine("QB Sync Token: {0}", actual.SyncToken);
Console.WriteLine("================================================");
ObjectDumper.Write(actual, 4);
}
}
The method that the unit test calls:
public Intuit.Ipp.Data.Invoice Create(Entities.Invoice invoice)
{
// Check pre-conditions
if (invoice == null) { throw new ArgumentException("Invoice object is required.", "invoice"); }
var qboInvoice = new Intuit.Ipp.Data.Invoice();
BuildInvoiceEntity(qboInvoice, invoice);
return _Service.Add(qboInvoice) as Intuit.Ipp.Data.Invoice;
}
And finally the build invoice method:
private void BuildInvoiceEntity(Intuit.Ipp.Data.Invoice qboInvoice, Entities.Invoice invoice)
{
if (qboInvoice != null && invoice != null)
{
IQuickBooksHeader header = invoice as IQuickBooksHeader;
if (String.IsNullOrEmpty(header.Id))
{
qboInvoice.DocNumber = invoice.ReferenceId;
qboInvoice.TxnDate = invoice.CreatedDate;
qboInvoice.TxnDateSpecified = true;
// Customer
qboInvoice.CustomerRef = new ReferenceType()
{
type = objectNameEnumType.Customer.ToString(),
Value = invoice.CustomerId.ToString()
};
// AR Account
qboInvoice.ARAccountRef = new ReferenceType()
{
type = objectNameEnumType.Account.ToString(),
name = "Accounts Receivable"
};
}
if (invoice.LineItems.Count > 0)
{
Intuit.Ipp.Data.Line[] invoiceLineCollection = new Intuit.Ipp.Data.Line[invoice.LineItems.Count];
for (int i = 0; i < invoice.LineItems.Count; i++)
{
var line = invoice.LineItems[i];
var qboInvoiceLine = new Intuit.Ipp.Data.Line()
{
Amount = line.Amount,
AmountSpecified = true,
Description = line.Description,
DetailType = LineDetailTypeEnum.SalesItemLineDetail,
DetailTypeSpecified = true,
AnyIntuitObject = new SalesItemLineDetail()
{
ItemRef = new ReferenceType()
{
name = line.ItemName,
},
ItemElementName = ItemChoiceType.UnitPrice,
AnyIntuitObject = line.Amount
}
};
invoiceLineCollection[i] = qboInvoiceLine;
}
qboInvoice.Line = invoiceLineCollection;
}
}
}
If I remove this piece of code from my build method:
ItemRef = new ReferenceType()
{
name = line.ItemName,
},
the invoice is successfully added with the default "Services" list item for the Product/Service of the invoice line items.
The online documentation for the IPP .NET SDK V3 is vague on what to specify for ReferenceType. What is wrong about just specifying the name of the list item? If I'm wrong about how I'm trying to specify a Product/Service list item for invoice line items, what is the correct way?
After days of researching, I never did find an answer as to why I can't just use the name like I wanted to, even though it works that way when specifying an AccountRef. But I digress, here is my solution:
// Hold a collection of QBO items
private ReadOnlyCollection<Item> _Items;
// I set the collection in the constructor only once
public Invoices(Entities.IPPRestProfile restProfile)
{
if (restProfile == null)
throw new ArgumentException("IPPRestProfile object is required.", "restProfile");
OAuthRequestValidator oAuthValidator = new OAuthRequestValidator(restProfile.OAuthAccessToken, restProfile.OAuthAccessTokenSecret,
restProfile.ConsumerKey, restProfile.ConsumerSecret);
ServiceContext context = new ServiceContext(restProfile.RealmId, restProfile.DataSource, oAuthValidator);
_Service = new DataService(context);
_Items = (new QueryService<Item>(context)).ExecuteIdsQuery("SELECT * FROM Item", QueryOperationType.query);
}
Whenever I build my invoice I query the collection for the Id of the item by name:
private void BuildInvoiceEntity(Intuit.Ipp.Data.Invoice qboInvoice, Entities.Invoice invoice)
{
...
// Get the Id value of the item by name
string itemTypeId = _Items.Where(o => o.Name == line.ItemName).FirstOrDefault().Id;
// Specify the Id value in the item reference of the SalesItemLineDetail
var qboInvoiceLine = new Intuit.Ipp.Data.Line()
{
Amount = (decimal)amount,
AmountSpecified = true,
Description = line.Description,
DetailType = LineDetailTypeEnum.SalesItemLineDetail,
DetailTypeSpecified = true,
AnyIntuitObject = new SalesItemLineDetail()
{
ItemRef = new ReferenceType() { Value = itemTypeId },
AnyIntuitObject = (decimal)line.Rate,
ItemElementName = ItemChoiceType.UnitPrice
}
};
...
}
Hopefully this helps point someone in the right direction to a possible better solution.