var v = new { email = "test1#yahoo.com", password = "fdsafsdfsdf" };
var request = new GraphQLRequest
{
Query = #"mutation customerCreate($input: CustomerCreateInput!) {
customerCreate(input: $input) {
userErrors {
field
message
}
customer {
id
}
}
}",
Variables = new
{
input = v
}
};
var client = new GraphQLClient("https://kitkatco.myshopify.com/api/graphql");
client.DefaultRequestHeaders.Add("X-Shopify-Storefront-Access-Token", new List<string> { "XXXXXXXXXXXXXXXXXXXXXX" });
var response = await client.PostAsync(request);
When I run this code, it says, GraphQLClient could not be found. So please have a look and let me know which nuggest package should I install?
Related
I'm getting Microsoft.Rest.HttpOperationException: 'Operation returned an invalid status code 'BadRequest'' on this line.
var result = client.CreateNamespacedDeployment(deployment, namespace);
Kubernetes-client has a small number of good resources and most of them is written in other language such as java and python. So i'm referring to these documentations.
this is my implementation so far.
V1Deployment deployment = new V1Deployment()
{
ApiVersion = "extensions/v1beta1",
Kind = "Deployment",
Metadata = new V1ObjectMeta()
{
Name = "...",
NamespaceProperty = env,
Labels = new Dictionary<string, string>()
{
{ "app", "..." }
}
},
Spec = new V1DeploymentSpec
{
Replicas = 1,
Selector = new V1LabelSelector()
{
MatchLabels = new Dictionary<string, string>
{
{ "app", "..." }
}
},
Template = new V1PodTemplateSpec()
{
Metadata = new V1ObjectMeta()
{
CreationTimestamp = null,
Labels = new Dictionary<string, string>
{
{ "app", "..." }
}
},
Spec = new V1PodSpec
{
Containers = new List<V1Container>()
{
new V1Container()
{
Name = "...",
Image = "...",
ImagePullPolicy = "Always",
Ports = new List<V1ContainerPort> { new V1ContainerPort(80) }
}
}
}
}
},
Status = new V1DeploymentStatus()
{
Replicas = 1
}
};
var result = client.CreateNamespacedDeployment(deployment, namespace);
I want to know the proper way on how to create kubernetes deployment using kubernetes-client, and also i want to know the cause of this issue.
For the full clarity and future visitors, it's worth to mention, what is exactly behind this bad request error (code: 400) returned from API server, when using your code sample:
"the API version in the data (extensions/v1beta1) does not match the expected API version (apps/v1)"
Solution:
ApiVersion = "extensions/v1beta1" -> ApiVersion = "apps/v1"
Full code sample:
private static void Main(string[] args)
{
var k8SClientConfig = new KubernetesClientConfiguration { Host = "http://127.0.0.1:8080" };
IKubernetes client = new Kubernetes(k8SClientConfig);
ListDeployments(client);
V1Deployment deployment = new V1Deployment()
{
ApiVersion = "apps/v1",
Kind = "Deployment",
Metadata = new V1ObjectMeta()
{
Name = "nepomucen",
NamespaceProperty = null,
Labels = new Dictionary<string, string>()
{
{ "app", "nepomucen" }
}
},
Spec = new V1DeploymentSpec
{
Replicas = 1,
Selector = new V1LabelSelector()
{
MatchLabels = new Dictionary<string, string>
{
{ "app", "nepomucen" }
}
},
Template = new V1PodTemplateSpec()
{
Metadata = new V1ObjectMeta()
{
CreationTimestamp = null,
Labels = new Dictionary<string, string>
{
{ "app", "nepomucen" }
}
},
Spec = new V1PodSpec
{
Containers = new List<V1Container>()
{
new V1Container()
{
Name = "nginx",
Image = "nginx:1.7.9",
ImagePullPolicy = "Always",
Ports = new List<V1ContainerPort> { new V1ContainerPort(80) }
}
}
}
}
},
Status = new V1DeploymentStatus()
{
Replicas = 1
}
};
Closing this issue (Resolved)
Reference: https://github.com/Azure/autorest/issues/931
Cause of issue: incorrect version of Kubernetes ApiVersion.
Solution: get and replace ApiVersion from kubernetes api.
Can also handle the exception using:
try
{
var result = client.CreateNamespacedDeployment(deployment, namespace);
}
catch (Microsoft.Rest.HttpOperationException httpOperationException)
{
var phase = httpOperationException.Response.ReasonPhrase;
var content = httpOperationException.Response.Content;
}
I have the following code.
[HttpGet]
public async Task<List<TenantManagementWebApi.Entities.SiteCollection>> Get()
{
var tenant = await TenantHelper.GetActiveTenant();
var siteCollectionStore = CosmosStoreFactory.CreateForEntity<TenantManagementWebApi.Entities.SiteCollection>();
await siteCollectionStore.RemoveAsync(x => x.Title != string.Empty); // Removes all the entities that match the criteria
string domainUrl = tenant.TestSiteCollectionUrl;
string tenantName = domainUrl.Split('.')[0];
string tenantAdminUrl = tenantName + "-admin.sharepoint.com";
KeyVaultHelper keyVaultHelper = new KeyVaultHelper();
await keyVaultHelper.OnGetAsync(tenant.SecretIdentifier);
using (var context = new OfficeDevPnP.Core.AuthenticationManager().GetSharePointOnlineAuthenticatedContextTenant(tenantAdminUrl, tenant.Email, keyVaultHelper.SecretValue))
{
Tenant tenantOnline = new Tenant(context);
SPOSitePropertiesEnumerable siteProps = tenantOnline.GetSitePropertiesFromSharePoint("0", true);
context.Load(siteProps);
context.ExecuteQuery();
List<TenantManagementWebApi.Entities.SiteCollection> sites = new List<TenantManagementWebApi.Entities.SiteCollection>();
foreach (var site in siteProps)
{
if(site.Template.Contains("SITEPAGEPUBLISHING#0") || site.Template.Contains("GROUP#0"))
{
string strTemplate= default(string);
if(site.Template.Contains("SITEPAGEPUBLISHING#0"))
{
strTemplate = "CommunicationSite";
};
if (site.Template.Contains("GROUP#0"))
{
strTemplate = "Modern Team Site";
};
try
{
Guid id = Guid.NewGuid();
Entities.SiteCollection sc = new Entities.SiteCollection()
{
Id = id.ToString(),
Owner = site.Owner,
Template = strTemplate,
Title = site.Title,
Active = false,
Url = site.Url
};
var added = await siteCollectionStore.AddAsync(sc);
sites.Add(sc);
}
catch (System.Exception ex)
{
throw ex;
}
}
}
return sites;
};
}
However the following lines, I am repeating them on every method:
var tenant = await TenantHelper.GetActiveTenant();
var siteCollectionStore = CosmosStoreFactory.CreateForEntity<TenantManagementWebApi.Entities.SiteCollection>();
await siteCollectionStore.RemoveAsync(x => x.Title != string.Empty); // Removes all the entities that match the criteria
string domainUrl = tenant.TestSiteCollectionUrl;
string tenantName = domainUrl.Split('.')[0];
string tenantAdminUrl = tenantName + "-admin.sharepoint.com";
KeyVaultHelper keyVaultHelper = new KeyVaultHelper();
await keyVaultHelper.OnGetAsync(tenant.SecretIdentifier);
I will have lots of API controllers on my project
Is there an easy way (not refactor as a method), to make my code cleaner and inject the variables I need without copying and pasting every single time?
I am running on TestNet. I am trying to add multiple transaction inputs TxIn() so as to spend from these inputs. When I broadcast my transaction, it returns successful but I can't see it on the block-explorer. I have handled a transaction with a single TxIn() and when I broadcast it, it was successful and i could view it on the block-explorer. I have been on this for more than 2 days now. Will greatly appreciate your help guys
var bitcoinPrivateKey = new BitcoinSecret("cNZupUgfs54DmsShwxa1wpomQcszUtuJYFvx9zWPbXrT7KsWtiUd");
var network = bitcoinPrivateKey.Network;
var address = bitcoinPrivateKey.GetAddress();
var client = new QBitNinjaClient(network);
var balance = client.GetBalance(address).Result;
var transactionId = uint256.Parse("06c0aec7543467951abad0c28998a2c1fc1cdc34e01113f8ec1fdb22be854771");
var transactionResponse = client.GetTransaction(transactionId).Result;
var tx = new Transaction();
foreach (var operation in balance.Operations)
{
OutPoint spendOutPoint = null;
var coinsReceived = operation.ReceivedCoins;
foreach (var coin in coinsReceived)
{
if (coin.TxOut.ScriptPubKey == bitcoinPrivateKey.ScriptPubKey)
{
spendOutPoint = coin.Outpoint;
tx.Inputs.Add(new TxIn()
{
PrevOut = spendOutPoint
});
}
}
}
var chimaTestDestinationAddress = new BitcoinPubKeyAddress("mxgN2AiqHjKfGvo6Y57fAe4Y754rPdKf4P");
TxOut chimaTestDestinationAddressTxOut = new TxOut()
{
Value = new Money((decimal)0.50, MoneyUnit.BTC),
ScriptPubKey = chimaTestDestinationAddress.ScriptPubKey
};
TxOut ugoChangeBackTxOut = new TxOut()
{
Value = new Money((decimal)2.98, MoneyUnit.BTC),
ScriptPubKey = bitcoinPrivateKey.ScriptPubKey
};
tx.Outputs.Add(chimaTestDestinationAddressTxOut);
tx.Outputs.Add(ugoChangeBackTxOut);
var msg = "ugo the jedi master";
var msgBytes = Encoding.UTF8.GetBytes(msg);
TxOut txDesc = new TxOut()
{
Value = Money.Zero,
ScriptPubKey = TxNullDataTemplate.Instance.GenerateScriptPubKey(msgBytes)
};
tx.Outputs.Add(txDesc);
tx.Inputs[0].ScriptSig = bitcoinPrivateKey.PubKey.WitHash.ScriptPubKey;
tx.Inputs[1].ScriptSig = bitcoinPrivateKey.PubKey.WitHash.ScriptPubKey;
tx.Inputs[2].ScriptSig = bitcoinPrivateKey.PubKey.WitHash.ScriptPubKey;
tx.Inputs[3].ScriptSig = bitcoinPrivateKey.PubKey.WitHash.ScriptPubKey;
tx.Inputs[4].ScriptSig = bitcoinPrivateKey.PubKey.WitHash.ScriptPubKey;
tx.Sign(bitcoinPrivateKey, false);
BroadcastResponse broadcast = client.Broadcast(tx).Result;
if (!broadcast.Success)
{
Console.WriteLine("ErrorCode: " + broadcast.Error.ErrorCode);
Console.WriteLine("Error message: " + broadcast.Error.Reason);
}
else
{
Console.WriteLine("Success, you can now checkout the transaction in any block explorer");
Console.WriteLine("Hash: " + tx.GetHash());
}
I am new in stripe, how can we set default payment method in stripe.
And can we pass cardId/sourceId to charge customer along with customerId.
Code:-
private static async Task<string> ChargeCustomer(string customerId)
{
return await System.Threading.Tasks.Task.Run(() =>
{
var myCharge = new StripeChargeCreateOptions
{
Amount = 50,
Currency = "gbp",
Description = "Charge for property sign and postage",
CustomerId = customerId
};
var chargeService = new StripeChargeService();
var stripeCharge = chargeService.Create(myCharge);
return stripeCharge.Id;
});
}
And 1 more question, how to get charge-list, I am using below code but getting exception(conversion error):-
private IEnumerable<StripeCharge> GetChargeList()
{
var chargeService = new StripeChargeService();
return chargeService.List();
}
This is what I ended up doing. Not sure why Stripe Checkout didn't set the card for the subscription setup as the default. Anyway, this fires triggered from the payment_intent.succeeded web hook. Sure there is a better way, but...
var customerService = new CustomerService(Configs.STRIPE_SECRET_KEY);
var c = customerService.Get(pi.CustomerId);
if (!string.IsNullOrEmpty(c.InvoiceSettings.DefaultPaymentMethodId)) {
status = "already has default payment method, no action";
hsc = HttpStatusCode.OK;
return;
}
var paymentMethodService = new PaymentMethodService(Configs.STRIPE_SECRET_KEY);
var lopm = paymentMethodService.ListAutoPaging(options: new PaymentMethodListOptions {
CustomerId = pi.CustomerId,
Type = "card"
});
if (!lopm.Any()) {
status = "customer has no payment methods";
hsc = HttpStatusCode.BadRequest;
return;
}
var pm = lopm.FirstOrDefault();
customerService.Update(pi.CustomerId, options: new CustomerUpdateOptions {
InvoiceSettings = new CustomerInvoiceSettingsOptions {
DefaultPaymentMethodId = pm.Id
}
});
hsc = HttpStatusCode.OK;
return;
We can pass cardId/BankAccountId/TokenId/SourceId in SourceTokenOrExistingSourceId property of StripeChargeCreateOptions,
private static async Task<string> ChargeCustomer(string customerId, string cardId)
{
try
{
return await System.Threading.Tasks.Task.Run(() =>
{
var myCharge = new StripeChargeCreateOptions
{
Amount = 50,
Currency = "gbp",
Description = "Charge for property sign and postage",
CustomerId = customerId,
SourceTokenOrExistingSourceId = cardId
};
var chargeService = new StripeChargeService();
var stripeCharge = chargeService.Create(myCharge);
return stripeCharge.Id;
});
}
catch(Exception ex)
{
return "";
}
}
To set/change default payment method:-
public void ChangeDefaultPayment(string customerId, string sourceId)
{
var myCustomer = new StripeCustomerUpdateOptions();
myCustomer.DefaultSource = sourceId;
var customerService = new StripeCustomerService();
StripeCustomer stripeCustomer = customerService.Update(customerId, myCustomer);
}
Still looking for how to get charge-list.
public async Task<IActionResult> Contact1()
{
if (Convert.ToBoolean(HttpContext.Session.GetString("login")))
{
var pass = new ContactViewModel();
var username = HttpContext.Session.GetString("username");
Program.readname(HttpContext.Session.GetString("username"));
var names = HttpContext.Session.GetString("studentnames");
var obj1 = JsonConvert.DeserializeObject<Program.Data>(names);
if (Program.datecheck(username, DateTime.Today.Date))
{
try{
var handler = new HttpClientHandler { Credentials = new NetworkCredential(user, password) };
using (var client = Program.CreateHttpClient(handler, user, database3))
{
string check = username + Convert.ToString(DateTime.Today.Date);
var readresponse = client.GetStringAsync(check).Result;
var obj2 = JsonConvert.DeserializeObject<Program.Data>(readresponse);
}
catch(Exception ee)
{ ViewBag.m6 = ee.Message; ViewBag.attendance = "Attendace is not take yet";}
}
pass.studentattend = obj2.studentattend1;
}
}
else { ViewBag.attendance = "Attendace is not take yet"; }
pass.studentname = obj1.studentname1;
pass.studentrollno = obj1.studentrollno1;
pass.date = DateTime.Today.Date;
HttpContext.Session.SetInt32("classselect", 1);
ViewData["Message"] = "Student Attendance of Class: " + HttpContext.Session.GetString("classname1");
ViewBag.Login = HttpContext.Session.GetString("login");
ViewBag.name = HttpContext.Session.GetString("name");
ViewBag.classname1 = HttpContext.Session.GetString("classname1");
ViewBag.classname2 = HttpContext.Session.GetString("classname2");
ViewBag.classname3 = HttpContext.Session.GetString("classname3");
ViewBag.classname4 = HttpContext.Session.GetString("classname4");
return View("/Views/Home/Contact.cshtml", pass);
}
else
{
ViewData["Message"] = "Please Login First!!";
return View("/Views/Home/Login.cshtml");
}
}
The above code is runnig well in my local ISS server but when i run this on bluemix then i am getting blank page. I tried to find out the problem and get to the conclusion that if the control does not enter in the if part of that code:
if (Program.datecheck(username, DateTime.Today.Date))
{
var handler = new HttpClientHandler { Credentials = new NetworkCredential(user, password) };
using (var client = Program.CreateHttpClient(handler, user, database3))
{
string check = username + Convert.ToString(DateTime.Today.Date);
var readresponse = client.GetStringAsync(check).Result;
var obj2 = JsonConvert.DeserializeObject<Program.Data>(readresponse);
pass.studentattend = obj2.studentattend1;
}
}
else { ViewBag.attendance = "Attendace is not take yet"; }
then it will run fine.I am unable to find what is wrong in that query.