Woocommerce.NET + C#: get the ID of product from SKU - c#

I am making a small app using C# with Woocommerce.NET wrapper.
I would like to edit a product, but I do not have the ID of a product - only SKU.
What would be the easiest way to get product ID from SKU number?
I have tried this:
RestAPI rest = new RestAPI(url, key, secret);
WCObject wc = new WCObject(rest);
var products = wc.Product.GetAll().GetAwaiter().GetResult();
products.ForEach(p => if p.sku = productSKU)
{
var productIDfromSKU = p.id;
}
EDIT: I have changed the code, to convert to int and it now works!
foreach (var p in products)
{
if (p.sku == SKU)
{
IDfromSKU = Convert.ToInt32(p.id);
};
};
But the problem is, that I only get a list of 10 products - not all.
Is there a setting for that?
My question remain - Is there a more straight forward way?
EDIT 2:
I have implemented your answers, the code works, but it is terribly slow.
2-3 minutes on ~5000 products.
What can I do to speed things up?
EDIT 3:
Sorry, have not done enough testing - the second answer great!
string SKU = "***wanted SKU***";
List<Product> products = new List<Product>();
Dictionary<string, string> pDic = new Dictionary<string, string>();
pDic.Add("sku", SKU);
int productIDfromSKU = 0;
string productNamefromSKU = "";
products = await wc.Product.GetAll(pDic);
if (products.Count > 0)
{
productIDfromSKU = Convert.ToInt32(products[0].id);
productNfromSKU = products[0].name;
}
Consider my problem solved!
Thank you all!

RestAPI rest = new RestAPI(url, key, secret);
WCObject wc = new WCObject(rest);
string SKU = "***wanted SKU***";
List<Product> products = new List<Product>();
Dictionary<string, string> pDic = new Dictionary<string, string>();
pDic.Add("sku", SKU);
int productIDfromSKU = 0;
string productNamefromSKU = "";
products = await wc.Product.GetAll(pDic);
if (products.Count > 0)
{
productIDfromSKU = Convert.ToInt32(products[0].id);
productNfromSKU = products[0].name;
}

RestAPI rest = new RestAPI(url, key, secret);
WCObject wc = new WCObject(rest);
List<Product> products = new List<Product>();
Dictionary<string, string> dic1 = new Dictionary<string, string>();
dic1.Add("per_page", "100");
int pageNumber1 = 1;
dic1.Add("page", pageNumber1.ToString());
bool endWhile1 = false;
while (!endWhile1)
{
var productsTemp = await wc.Product.GetAll(dic1);
if (productsTemp.Count > 0)
{
products.AddRange(productsTemp);
pageNumber1++;
dic1["page"] = pageNumber1.ToString();
}
else
{
endWhile1 = true;
}
}
foreach (Product p in products)
{
if (p.sku == SKU)
{
IDfromSKU = Convert.ToInt32(p.id);
break;
};
}

Related

Get duplicate Realtime Database Firebase results in Xamarin

I'm trying to build realtime chat through Realtime Database Firebase and Xamarin. However there is a problem like this, hope someone can help:
protected async void LoadChat()
{
string userid = "123456789";
var getroom = (await fc.Child("RecordsChat").OnceAsync<GetRoomChats>()).Select(x =>
new GetRoomChats
{
RoomID = x.Key
}).ToList();
List<GetRoomChats> listroomuser = new List<GetRoomChats>();
foreach (var room in getroom)
{
string str = null;
string[] strArr = null;
string roomget = room.RoomID;
str = roomget + "_";
char[] splitchar = { '_' };
strArr = str.Split(splitchar);
var getroomuser = strArr.Distinct().ToList();
foreach (var item in getroomuser)
{
if (item == userid)
{
var roomgetuser = new GetRoomChats()
{
RoomID = roomget
};
listroomuser.Add(roomgetuser);
}
}
}
if (listroomuser.Count() > 0)
{
var FirebaseClient = fc
.Child("RecordsChat")
.AsObservable<GetRoomChats>()
.Subscribe(async(dbevent) =>
{
//IteamGetRoomChats.Clear();
foreach (var room in listroomuser)
{
if (dbevent.Key == room.RoomID)
{
var lst = (await fc.Child("RecordsChat").Child(dbevent.Key).OrderByKey().LimitToLast(1).OnceAsync<MyDatabaseRecord>()).Select(x =>
new MyDatabaseRecord
{
NameUser = x.Object.NameUser,
Content = x.Object.Content,
RoomID = x.Object.RoomID,
DayCreate = x.Object.DayCreate,
AvatarUser = x.Object.AvatarUser,
sender_uid = x.Object.sender_uid,
receiver_uid = x.Object.receiver_uid,
receiver_read = x.Object.receiver_read
});
bool unread = false;
foreach (var i in lst)
{
if(i.sender_uid == userid)
{
i.Content = "You: " + i.Content;
var customerList = await apiServiceUserinfo.GetCustomersInfo(i.receiver_uid);
string nameget = customerList.NameStore;
string avatarget = customerList.AvatarStore;
i.NameUser = nameget;
i.AvatarUser = avatarget;
if (i.sender_read == true)
{
unread = false;
}
}
else
{
if (i.receiver_read == false)
{
i.BackgroundUser = "#f5f4f4";
unread = true;
}
}
var last = new GetRoomChats()
{
NameLast = i.NameUser,
ContentLast = i.Content,
RoomID = i.RoomID,
DayCreateLast = i.DayCreate,
AvatarLast = i.AvatarUser,
BackgroundUnread = i.BackgroundUser,
DotUnread = unread
};
IteamGetRoomChats.Add(last);
}
}
}
});
}
BindingContext = this;
}
In my example above, it actually gets the data. I try to check in the loop, to get the last content of the message. However, the displayed results are duplicated
Looking forward to everyone's help. Thank you!

foreach and index in .ToDictionary C#

I am web-scraping some data and trying to write the scraped data to a json file using C# newtonsoft.Json
I get stuck when writing a foreach in my .ToDictionary function as well as not being able to ++ an index into my .ToDictionary function.
My class:
public class JsonParametersData
{
public bool required { get; set; }
public bool list { get; set; }
public List<string> options { get; set; }
}
My arrays
var jsonData = new List<Dictionary<string, Dictionary<string, JsonParametersData>>>();
var moduleParameters = new List<string>();
var parameterOptionsArray = new List<List<string>>();
var parameterOptions = new List<string>();
var requiredArray = new List<bool>();
var listArray = new List<bool>();
string moduleName = item.Attributes["href"].Value.Replace("_module.html", "");
The code which is commented shows what I am trying to do.
int index = 0;
jsonData.Add(new Dictionary<string, Dictionary<string, JsonParametersData>>()
{
{
moduleName,
moduleParameters
.ToDictionary(n => n,
n => new JsonParametersData
{
required = requiredArray[index],
list = listArray[index],
options = new List<string>() { "option1", "option2" },
/*
foreach (var parameteroption in parameterOptionsArray[index])
{
options.Add(parameteroption);
}
index++;
*/
})
}
});
string json = JsonConvert.SerializeObject(jsonData.ToArray());
//write string to file
System.IO.File.WriteAllText(#"path", json);
Your parameterOptionsArray is not an Array, but a List of lists.
The thing is that parameterOptionsArray[index] is a List, not a string. So you should use AddRange() instead of Add().
parameterOptionsArray.Foreach(parameteroption => options.AddRange(parameteroption));
As I´ve written in the comments you can make only assignments in an object-initializer. Thus the following is allowed:
var a = new { MyMember = anInstance }
whilst this is not:
var a = new { MyMember = anInstance, anInstance.DoSomething() };
That´s one of those cases where you should not use Linq at all, as it leads to more confusion than it helps. Instead use a good old-styled loop:
int index = 0;
var innerDict = new Dictionary<string, JsonParametersData>();
foreach(var name in moduleParameters)
{
innerDict[name] = new JsonParametersData
{
required = requiredArray[index],
list = listArray[index],
options = new List<string>() { "option1", "option2" },
}
innerDict[name].Options.AddRange(parameterOptionsArray[index]);
index++;
}
var dict = new Dictionary<string, Dictionary<string, JsonParametersData>>();
dict[moduleName] = innerDict;
jsonData.Add(dict);
string json = JsonConvert.SerializeObject(jsonData.ToArray());
You appear to have a jagged array in parameterOptionsArray. You can make use of SelectMany here. Perhaps following sample can help:
string[][] parameterOptionsArray = new string[2][];
parameterOptionsArray[0] = new string[2];
parameterOptionsArray[0][0] = "1";
parameterOptionsArray[0][1] = "2";
parameterOptionsArray[1] = new string[2];
parameterOptionsArray[1][0] = "3";
parameterOptionsArray[1][1] = "4";
var testing = new {options = parameterOptionsArray.SelectMany(x => x).ToList()};
testing.options.ForEach(x => Console.WriteLine(x));

Get Posts (Wall Facebook) of me and my friends

I use
https://developers.facebook.com/tools/access_token/
I create an App. I want get Posts of the wall of me and my friends.
I try me/feed and me/posts but I get nothing.
I have this unit test.
Any suggestions?
[TestMethod]
public void Basic_using_SDK()
{
// http://blog.prabir.me/posts/facebook-csharp-sdk-making-requests
var fb = new Facebook.FacebookClient();
var result = (IDictionary<string, object>)fb.Get("4");
var id = (string)result["id"];
var name = (string)result["name"];
var firstName = (string)result["first_name"];
var lastName = (string)result["last_name"];
var link = (string)result["link"];
var username = (string)result["username"];
var gender = (string)result["gender"];
var male = (string)result["locale"];
var parameters = new Dictionary<string, object>();
parameters["fields"] = "id,name";
result = (IDictionary<string, object>)fb.Get("4", parameters);
id = (string)result["id"];
name = (string)result["name"];
dynamic result2 = fb.Get("4");
id = result2.id;
name = result2.name;
firstName = result2.first_name;
lastName = result2.last_name;
link = result2.link;
username = result2.username;
gender = result2.gender;
male = result2.locale;
dynamic parameters2 = new ExpandoObject();
parameters2.fields = "id,name";
dynamic result3 = fb.Get("4", parameters);
id = result3.id;
name = result3.name;
dynamic me = fb.Get("zuck");
firstName = me.first_name;
lastName = me.last_name;
var client = new FacebookClient(AccessToken);
dynamic me2 = client.Get("me");
string aboutMe = me2.about;
dynamic result4 = client.Get("/me/feed");
foreach (dynamic post in result4.data)
{
var fromName = post.from.name;
Console.WriteLine(fromName);
}
dynamic result5 = client.Get("/me/posts");
for (int i = 0; i < result5.Count; i++)
{
}
// https://www.facebook.com/profile.php?id=xxxxxxx
// https://graph.facebook.com/xxxxxxx
var uidKiquenet = "xxxxx";
var query = string.Format(#"SELECT status_id,message,time,source,uid,place_id
FROM status WHERE uid IN (SELECT uid FROM status WHERE uid = '" + uidKiquenet + "') ORDER BY time DESC");
dynamic parameters6 = new ExpandoObject();
parameters6.q = query;
dynamic results6 = fb.Get("/xxxxx?fields=id,name,age_range,about,email,first_name,gender");
string myMessage = "Hello from Test";
fb.PostTaskAsync("me/feed", new { message = myMessage }).ContinueWith(t =>
{
if (!t.IsFaulted)
{
string message = "Great, your message has been posted to you wall!";
Console.WriteLine(message);
}
});
fb.GetTaskAsync("me").ContinueWith(t =>
{
if (!t.IsFaulted)
{
var result11 = (IDictionary<string, object>)t.Result;
string myDetails = string.Format("Your name is: {0} {1} and your Facebook profile Url is: {3}",
(string)result11["first_name"], (string)result11["last_name"],
(string)result11["link"]);
Console.WriteLine(myDetails);
}
});
// This uses Facebook Query Language
// See https://developers.facebook.com/docs/technical-guides/fql/ for more information.
query = string.Format("SELECT uid,name,pic_square FROM user WHERE uid IN (SELECT uid2 FROM friend WHERE uid1={0}) ORDER BY name ASC", "me()");
fb.GetTaskAsync("fql", new { q = query }).ContinueWith(t =>
{
if (!t.IsFaulted)
{
var result1 = (IDictionary<string, object>)t.Result;
var data = (IList<object>)result1["data"];
var count = data.Count;
var message = string.Format("You have {0} friends", count);
Console.WriteLine(message);
foreach (IDictionary<string, object> friend in data)
Console.WriteLine((string)friend["name"]);
}
});
}
You must authorize with the correct permission in order to get access to feed posts. Try authorizing with user_posts, as it is explained in the docs: https://developers.facebook.com/docs/graph-api/reference/v2.3/user/feed#read
Be aware that this does not get you access to posts of friends, unless they posted on the wall of the authorized user.
About review, you may want to read this: https://developers.facebook.com/docs/facebook-login/review/faqs#what_is_review
Btw, FQL is deprecated and will only work in v2.0 Apps - not in newer ones.
Same thing happened to me . Here is my Solution
I made my project registered on Facebook developer console. Then I did my code same as you but could not get posts / information . After some time i submitted my application for app review to facebook team (it was still in early development phase) and after their feedback I got my code working . So pending Application review can be your issue also . This option is available in application setting . Give it a shot
Update
Another code sample is here
if (Request["code"] == null)
{
Response.Redirect(string.Format("https://graph.facebook.com/oauth/authorize?client_id={0}&redirect_uri={1}&scope={2}",
FB_app_id, Request.Url.AbsoluteUri, FB_scope));
return false;
}
else
{
Dictionary<string, string> tokens = new Dictionary<string, string>();
string url = string.Format("https://graph.facebook.com/oauth/access_token?client_id={0}&redirect_uri={1}&scope={2}&code={3}&client_secret={4}&perms=status_update"
, FB_app_id, Request.Url.AbsoluteUri, FB_scope, Request["code"].ToString(), FB_secret_id);
HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
StreamReader rd = new StreamReader(response.GetResponseStream());
string vals = rd.ReadToEnd();
foreach (string token in vals.Split('&'))
{
tokens.Add(token.Substring(0, token.IndexOf('=')), token.Substring(token.IndexOf("=") + 1, token.Length - token.IndexOf('=') - 1));
}
string access_token = tokens["access_token"];
Session["fb_access_token"] = access_token;
return true;
}
}

Why doesn't StartWorkflow() start my workflow in C#?

I am attempting to programatically start a SharePoint 2013 workflow. The workflow takes five parameters, puts them in an email body and e-mails them to me. When I go to the SharePoint website I can start this workflow manually, so I know the workflow is correct. When I try to use the SharePoint API's to start the workflow, I get no errors, I get an empty Guid back, and the workflow does not run.
public Guid Add(Project project)
{
var result = Guid.Empty;
var siteUri = new Uri(ConfigurationManager.AppSettings["SharePoint.Site"]);
var workflowName = ConfigurationManager.AppSettings["SharePoint.WorkflowName"];
using (var clientContext = TokenHelper.GetS2SClientContextWithWindowsIdentity(siteUri, null))
{
var workflowServiceManager = new WorkflowServicesManager(clientContext, clientContext.Web);
var workflowSubscriptionService = workflowServiceManager.GetWorkflowSubscriptionService();
var subscriptions = workflowSubscriptionService.EnumerateSubscriptions();
clientContext.Load(subscriptions, subs => subs.Where(sub => sub.Name == workflowName));
clientContext.ExecuteQuery();
foreach (var subscription in subscriptions)
{
var instanceService = workflowServiceManager.GetWorkflowInstanceService();
var initiationData = new Dictionary<string, object>
{
{"pProjectName", project.Name},
{"pDivision", _divisionData.GetDivisionName(project.DivisionId ?? Guid.Empty) },
{"pOperatingGroup", "****TODO: Operating Group****"},
{"pClientName", _clientData.GetClientName(project.ClientId ?? Guid.Empty) },
{"pSiteUrl", "****TODO: Site URL****" }
};
var startResult = instanceService.StartWorkflow(subscription, initiationData);
result = startResult.Value;
}
}
return result;
}
string subscriptionID = "WFListSubscriptionID of your wf";//it is a guid
int itemID = "Item.ID, Id of a item that you start wf for";
Guid workflowSubscriptionIdGuid = new Guid(subscriptionID);
var workflowServiceManager = new WorkflowServicesManager(item.Web);
var workflowSubscriptionService = workflowServiceManager.GetWorkflowSubscriptionService();
var workflowSubscription = workflowSubscriptionService.GetSubscription(workflowSubscriptionIdGuid);
var inputParameters = new Dictionary<string, object>();
workflowServiceManager.GetWorkflowInstanceService().StartWorkflowOnListItem(workflowSubscription, itemID, inputParameters);

How to Create a campaign in MailChimp using ASP.Net

I need to create and send immediately campaigns in MailChimp.com. I used C# wrapper Percepective MCAPI.dll for this purpose.
from the MailChimp API, Its clear that we cannot lists but can create campaigns. I tried code but the campaignID is retured null; no exception thrown atleast. I did set the campaigntype to Auto.
here is my code snippet:
try
{
string apiKey = "api-us2"; // API KEY is valid
string emailAddress = "ravinderpal.singh#abc.net";
listsForEmailInput lstForEmailInput = new listsForEmailInput(apiKey, emailAddress);
listsForEmail cmd = new listsForEmail(lstForEmailInput);
listsForEmailOutput lstEmailOutPut = cmd.Execute();
List lstResults = lstEmailOutPut.result;
string listID = lstResults[0]; // Got Precraeted List ID( Valid Confirmed )
Console.WriteLine("\n" + listID);
// compaign Create
campaignCreateOptions campaignCreateOpt = new campaignCreateOptions();
campaignCreateOpt.list_id = listID;
campaignCreateOpt.subject = " New Campaign from dev_Anil";
campaignCreateOpt.from_email = "anil.k#abc.net";
campaignCreateOpt.from_name = "anil";
Dictionary content = new Dictionary();
content.Add("html", "Helloaasdsa");
content.Add("text", "Hi all !! this is dev_anil");
content.Add("url", "");
content.Add("archive", "");
campaignSegmentOptions csOptions = new campaignSegmentOptions();
csOptions.match = "any"; // Could not set Condition -- need help for this
// Need to set a Dictionary typeOptions because null is not supported
Dictionary typeOptions = new Dictionary();
campaignCreateParms campaignCreateParms = new campaignCreateParms(apiKey, EnumValues.campaign_type.auto, campaignCreateOpt, content, csOptions, typeOptions);
campaignCreateInput campaignCreateInput = new campaignCreateInput(campaignCreateParms);
campaignCreate campaignCreate = new campaignCreate(campaignCreateInput);
campaignCreateOutput ccOutput = campaignCreate.Execute(campaignCreateInput);
string abc = ccOutput.result; // This comes out to null
}
catch(Exception ee)
{
Console.WriteLine("\n\n Exception :" + ee.Message); // no exception
}
can anybody show me the right direction and what is wrong with the code.
any help would be much appreciated.
thanks.
I solved this problem and here is code as solution. here listID is precreated List ID in your account in Mailchimp.
private void CreateCampaignAndSend(string apiKey, string listID)
{
Int32 TemplateID = 100;
string campaignID =string.Empty;
// compaign Create Options
campaignCreateOptions campaignCreateOpt = new campaignCreateOptions();
campaignCreateOpt.list_id = listID;
campaignCreateOpt.subject = "subject";
campaignCreateOpt.from_email = "abc#xyz.com";
campaignCreateOpt.from_name = "abc";
campaignCreateOpt.template_id = TemplateID;
// Content
Dictionary<string, string> content = new Dictionary<string, string>();
content.Add("html_ArticleTitle1", "ArticleTitle1");
content.Add("html_ArticleTitle2","ArticleTitle2");
content.Add("html_ArticleTitle3", "ArticleTitle3");
content.Add("html_Article1", "Article1");
content.Add("html_Article2", "Article2");
// Conditions
List<campaignSegmentCondition> csCondition = new List<campaignSegmentCondition>();
campaignSegmentCondition csC = new campaignSegmentCondition();
csC.field = "interests-" + 123; // where 123 is the Grouping Id from listInterestGroupings()
csC.op = "all";
csC.value = "";
csCondition.Add(csC);
// Options
campaignSegmentOptions csOptions = new campaignSegmentOptions();
csOptions.match = "all";
// Type Options
Dictionary<string, string> typeOptions = new Dictionary<string, string>();
typeOptions.Add("offset-units", "days");
typeOptions.Add("offset-time", "0");
typeOptions.Add("offset-dir", "after");
// Create Campaigns
campaignCreate campaignCreate = new campaignCreate(new campaignCreateInput(apiKey, EnumValues.campaign_type.plaintext, campaignCreateOpt, content, csOptions, typeOptions));
campaignCreateOutput ccOutput = campaignCreate.Execute();
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);
}
}
}
I removed the url and archive from the content. Then the campaign was created just fine:
// campaign Create
campaignCreateOptions campaignCreateOpt = new campaignCreateOptions();
campaignCreateOpt.list_id = listId;
campaignCreateOpt.subject = " New Campaign from Someemone";
campaignCreateOpt.from_email = "someone#home.com";
campaignCreateOpt.from_name = "someone";
Dictionary<string, string> content = new Dictionary<string, string>();
content.Add("html", "Lots of cool stuff here.");
campaignSegmentOptions csOptions = new campaignSegmentOptions();
csOptions.match = "any"; // Could not set Condition -- need help for this
// Need to set a Dictionary typeOptions because null is not supported
Dictionary<string,string> typeOptions = new Dictionary<string, string>();
campaignCreateParms campaignCreateParms = new campaignCreateParms(apiKey, EnumValues.campaign_type.trans, campaignCreateOpt, content, csOptions, typeOptions);
campaignCreateInput campaignCreateInput = new campaignCreateInput(campaignCreateParms);
campaignCreate campaignCreate = new campaignCreate(campaignCreateInput);
campaignCreateOutput ccOutput = campaignCreate.Execute(campaignCreateInput);
string newCampaignId = ccOutput.result; // Not null anymore

Categories

Resources