How to create k8s deployment using kubernetes-client in c#? - c#

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;
}

Related

GraphQLClient could not be found

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?

LifecycleConfiguration -- The XML you provided was not well-formed or did not validate against our published schema

I am using AWSSDK.dll version 2.1.3.0
i am trying to add new lifecycle rule
here is the code
IAmazonS3 _s3Client = new AmazonS3Client("A*****************Z", "a*************b", bucketRegion);
// Retrieve current configuration
var configuration = _s3Client.GetLifecycleConfiguration(
new GetLifecycleConfigurationRequest
{
BucketName = bucketName
}).Configuration;
//Adding new Rule
configuration.Rules.Add(new LifecycleRule
{
Id = "ATam",
Prefix = "ATam/PanCake QA/Avaniti/",
Expiration = new LifecycleRuleExpiration()
{
Days = 3650
},
Transition = new LifecycleTransition()
{
StorageClass = S3StorageClass.Glacier,
Days = 14
},
Status = LifecycleRuleStatus.Enabled,
});
PutLifecycleConfigurationRequest request = new PutLifecycleConfigurationRequest
{
BucketName = bucketName,
Configuration = configuration
};
var response = _s3Client.PutLifecycleConfiguration(request);
But i am getting this exception
An unhandled exception of type 'Amazon.S3.AmazonS3Exception' occurred in AWSSDK.dll Additional information: The XML you provided was not well-formed or did not validate against our published schema
Can anyone let me know where i am going wrong.
Thanks in advance
You need to set LifecycleTransition properties Days and Storage Class.
LifecycleConfiguration newConfiguration = new LifecycleConfiguration
{
Rules = new List<LifecycleRule>
{
new LifecycleRule
{
Id = "some id here",
Filter = new LifecycleFilter()
{
LifecycleFilterPredicate = new LifecyclePrefixPredicate()
{
}
},
Status = LifecycleRuleStatus.Enabled,
Transitions = new List<LifecycleTransition>
{
new LifecycleTransition
{
Days = 0,
StorageClass = S3StorageClass.Glacier
}
},
Expiration = new LifecycleRuleExpiration()
{
Days = 1
}
}
}
};

bad request - request too long

I use IdentityServer3. My startup class is bellow.
public class Startup
{
public void Configuration(IAppBuilder app)
{
app.Map("/identity", idsrvApp =>
{
var corsPolicyService = new DefaultCorsPolicyService()
{
AllowAll = true
};
var idServerServiceFactory = new IdentityServerServiceFactory()
.UseInMemoryClients(Clients.Get())
.UseInMemoryScopes(Scopes.Get());
//.UseInMemoryUsers(Users.Get());
idServerServiceFactory.CorsPolicyService = new Registration<IdentityServer3.Core.Services.ICorsPolicyService>(corsPolicyService);
idServerServiceFactory.ViewService = new Registration<IViewService, CustomViewService>();
idServerServiceFactory.UserService = new Registration<IUserService>(resolver => new CustomUserService());
var options = new IdentityServerOptions
{
EnableWelcomePage = false,
Factory = idServerServiceFactory,
SiteName = "Justice Identity Server",
IssuerUri = IdentityConstants.ecabinetIssuerUri,
PublicOrigin = IdentityConstants.ecabinetSTSOrigin,
AuthenticationOptions = new IdentityServer3.Core.Configuration.AuthenticationOptions() {
CookieOptions = {
AllowRememberMe=false,
Prefix="IC"
},
EnablePostSignOutAutoRedirect = true,
},
SigningCertificate = LoadSertificate(),
CspOptions = new CspOptions()
{
Enabled = true,
ScriptSrc = "'unsafe-inline'",
ConnectSrc = "*",
FrameSrc = "*"
},
};
idsrvApp.UseIdentityServer(options);
});
}
X509Certificate2 LoadSertificate()
{
return new X509Certificate2(string.Format(#"{0}\certificates\cert.pfx", AppDomain.CurrentDomain.BaseDirectory), "123", X509KeyStorageFlags.MachineKeySet);
}
}
After sometimes I have got "bad request-request too long" ,when I clear cookie it works. I have seen in console a lot of nonce cookies.
Anyone could help me?
thanks you
This is a known issue.
There is more info there: https://github.com/IdentityServer/IdentityServer3/issues/1124

How to create AutoScale Settings programmatically with C# for Windows Azure Web App using Microsoft.WindowsAzure.Management.Monitoring?

What Do I have:
var subscriptionId = "xxx";
var thumbprint = "xxx";
var certificate = GetCertificate(StoreName.My, StoreLocation.CurrentUser, thumbprint);
var autoscaleClient = new AutoscaleClient(new CertificateCloudCredentials(subscriptionId, certificate));
var createParams = new AutoscaleSettingCreateOrUpdateParameters
{
Setting = new AutoscaleSetting
{
Enabled = true,
Profiles = new List<AutoscaleProfile>
{
new AutoscaleProfile
{
Capacity = new ScaleCapacity
{
Default ="1",
Maximum="10",
Minimum="1"
},
Name = "anurag",
Recurrence= new Recurrence
{
Frequency=RecurrenceFrequency.Week,
Schedule = new RecurrentSchedule
{
Days = new List<string>{"Monday", "Thursday", "Friday"},
Hours = {7, 19},
Minutes=new List<int>{0},
TimeZone = "Pacific Standard Time"
}
},
Rules=new List<ScaleRule>
{
new ScaleRule
{
MetricTrigger =new MetricTrigger
{
MetricName="Test Metric",
MetricNamespace="",
MetricSource=
AutoscaleMetricSourceBuilder.BuildWebSiteMetricSource("???", "???"),
Operator=ComparisonOperationType.GreaterThan,
Threshold=2000,
Statistic=MetricStatisticType.Average,
TimeGrain=TimeSpan.FromMinutes(5),
TimeAggregation=TimeAggregationType.Average,
TimeWindow=TimeSpan.FromMinutes(30)
},
ScaleAction = new ScaleAction
{
Direction = ScaleDirection.Increase,
Cooldown = TimeSpan.FromMinutes(20),
Type=ScaleType.ChangeCount,
Value = "4"
}
}
}
}
}
}
};
var resourceId = AutoscaleResourceIdBuilder.BuildWebSiteResourceId("???", "???");
var autoscaleResponse = autoscaleClient.Settings.CreateOrUpdate(resourceId, createParams);
I am confused about two API calls:
AutoscaleResourceIdBuilder.BuildWebSiteResourceId(string webspace, string serverFarmName)
AutoscaleMetricSourceBuilder.BuildWebSiteMetricSource(string webspaceName, string websiteName)
What is a webspace, server farm name, webspace name and web site name? Where Do I get them?

paypal recurring payment with express checkout in c#

I am using following code to create recurring payment profile
CreateRecurringPaymentsProfileReq RPPR = new CreateRecurringPaymentsProfileReq()
{
CreateRecurringPaymentsProfileRequest = new CreateRecurringPaymentsProfileRequestType()
{
Version = UtilPayPalAPI.Version,
CreateRecurringPaymentsProfileRequestDetails = new CreateRecurringPaymentsProfileRequestDetailsType()
{
Token = resp.GetExpressCheckoutDetailsResponseDetails.Token,
RecurringPaymentsProfileDetails = new RecurringPaymentsProfileDetailsType()
{
BillingStartDate =Convert.ToDateTime("1/15/2012 11:10:28 AM"),
SubscriberName = "Shubhangi"
},
ScheduleDetails = new ScheduleDetailsType()
{
PaymentPeriod = new BillingPeriodDetailsType()
{
Amount = new BasicAmountType()
{
currencyID = CurrencyCodeType.USD,
Value = "10.00"
},
BillingFrequency=2,
BillingPeriod=BillingPeriodType.Day
},
ActivationDetails = new ActivationDetailsType()
{
InitialAmount = new BasicAmountType()
{
currencyID=CurrencyCodeType.USD,
Value="10.00"
}
},
}
}
}
};
CreateRecurringPaymentsProfileResponseType dorecurringPaymentResponse = UtilPayPalAPI.BuildPayPalWebservice().CreateRecurringPaymentsProfile(RPPR);
UtilPayPalAPI.HandleError(dorecurringPaymentResponse);
After calling doexpress checkout api, I have made a call to createrecurring profile api. In this doexpress checkout response returns "Success", but after that when I'm calling create recurringprofile it's response is "failure". And error is "Token is invalid"
Could any one suggest any correction in my code?

Categories

Resources