paypal recurring payment with express checkout in c# - 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?

Related

How to create event with videoconference in Google Meet in C# using Google Calendar API?

Well.. I'm trying this code to create an Event
CalendarService service;
GoogleCredential credential;
try
{
string[] scopes = new string[] { CalendarService.Scope.Calendar };
using (var stream = new FileStream(#"C:\Prueba\meet.json", FileMode.Open, FileAccess.Read))
{
credential = GoogleCredential.FromStream(stream)
.CreateScoped(scopes);
}
service = new CalendarService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential
});
Event calendarEvent = new Event();
DateTime start = DateTime.Now;
calendarEvent.Kind = "";
calendarEvent.Summary = "prueba";
calendarEvent.Status = "confirmed";
calendarEvent.Visibility = "public";
calendarEvent.Description = "prueba";
calendarEvent.Creator = new Event.CreatorData
{
Email = "email#example.com", //email#example.com
Self = true
};
calendarEvent.Organizer = new Event.OrganizerData
{
Email = "email#example.com",
Self = true
};
calendarEvent.Start = new EventDateTime
{
DateTime = start,
TimeZone = "America/Mexico_City"
};
calendarEvent.End = new EventDateTime
{
DateTime = start.AddHours(1),
TimeZone = "America/Mexico_City"
};
calendarEvent.Recurrence = new String[] { "RRULE:FREQ=DAILY;COUNT=1" };
calendarEvent.Sequence = 0;
calendarEvent.HangoutLink = "";
calendarEvent.ConferenceData = new ConferenceData
{
CreateRequest = new CreateConferenceRequest
{
RequestId = "1234abcdef",
ConferenceSolutionKey = new ConferenceSolutionKey
{
Type = "hangoutsMeet"
},
Status = new ConferenceRequestStatus
{
StatusCode = "success"
}
},
EntryPoints = new List<EntryPoint>
{
new EntryPoint
{
EntryPointType = "video",
Uri = "",
Label = ""
}
},
ConferenceSolution = new ConferenceSolution
{
Key = new ConferenceSolutionKey
{
Type = "hangoutsMeet"
},
Name = "Google Meet",
IconUri = ""
},
ConferenceId = ""
};
//calendarEvent.EventType = "default";
EventsResource.InsertRequest request = service.Events.Insert(calendarEvent, "email#example.com");
request.ConferenceDataVersion = 0;
Event createEvent = request.Execute();
string url = createEvent.HangoutLink;
}
catch (Exception ex)
{
}
The source code is here
When I execute the line 116: Event createEvent = request.Execute();
I get this error: Google.Apis.Requests.RequestError Invalid conference type value. [400] Errors [Message[Invalid conference type value.] Location[ - ] Reason[invalid] Domain[global]
I don't know what means this error o with line I wrong
Could anyone help me with an example to create an event using classes C# from Google API Calendar?
As described in the C# library documentation for createRequest:
Either conferenceSolution and at least one entryPoint, or createRequest is required.
This means that you should use only CreateConferenceRequest as this conference is brand new (if it already existed then you would be wanting to use ConferenceSolution along with EntryPoints ). Therefore, simply remove ConferenceSolution and EntryPoints to leave just CreateConferenceRequest which as specified in the documentation is used for generating a new conference and attach it to the event.

How to create k8s deployment using kubernetes-client in 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;
}

Create Initial Push into Newly Created Repository using VSTS Git API

How to create initial push into newly created Repository using VSTS Git API?
I have created a new repository.
using Microsoft.TeamFoundation.SourceControl.WebApi;
using Microsoft.VisualStudio.Services.WebApi;
using Microsoft.TeamFoundation.Core.WebApi
var accountUri = new Uri("https://mysite.visualstudio.com");
var personalAccessToken = "myaccesstoken";
var connection = new VssConnection(accountUri, new VssBasicCredential(string.Empty, personalAccessToken));
// Get a GitHttpClient to talk to the Git endpoints
var gitClient = connection.GetClient<GitHttpClient>();
var teamProject = projectClient.GetProject("MyProject", true, true).Result;
var repo = gitClient.CreateRepositoryAsync(new GitRepository
{
DefaultBranch = "refs/heads/master",
Name = "TestRepo",
ProjectReference = new TeamProjectReference
{
Id = teamProject.Id
}
}).Result;
The repo is successfully created. But why is the repo.DefaultBranch value is null?
Next step, I'd like to push my initial commit.
var newBranch = new GitRefUpdate
{
RepositoryId = repo.Id,
Name = $"refs/heads/master"
};
string newFileName = "README.md";
GitCommitRef newCommit = new GitCommitRef
{
Comment = "Initial commit",
Changes = new GitChange[]
{
new GitChange
{
ChangeType = VersionControlChangeType.Add,
Item = new GitItem { Path = $"/master/{newFileName}" },
NewContent = new ItemContent
{
Content = "# Thank you for using VSTS!",
ContentType = ItemContentType.RawText,
},
}
}
};
GitPush push = gitClient.CreatePushAsync(new GitPush
{
RefUpdates = new GitRefUpdate[] { newBranch },
Commits = new GitCommitRef[] { newCommit },
}, repo.Id).Result;
I got an error when calling CreatePushAsync:
VssServiceException: The combination of parameters is either not valid
or not complete. Parameter name: baseCommitId
Please help how to create initial commit properly.
You could use the rest api to achieve what you want. The rest api of creating an initial commit (create a new branch) is as below:
POST https://fabrikam.visualstudio.com/_apis/git/repositories/{repositoryId}/pushes?api-version=4.1
{
"refUpdates": [
{
"name": "refs/heads/master",
"oldObjectId": "0000000000000000000000000000000000000000"
}
],
"commits": [
{
"comment": "Initial commit.",
"changes": [
{
"changeType": "add",
"item": {
"path": "/readme.md"
},
"newContent": {
"content": "My first file!",
"contentType": "rawtext"
}
}
]
}
]
}

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?

How to use Paypal Checkout Hosted pages for Credit Card payments in MVC C#

I am facing problem in implementing Credit Card payments using Paypal Checkout Hosted pages for Credit Card transactions.
This is my code for Paypal payments:
public ActionResult CreatePayment(string packageName)
{
#region check client balance
long clientid = Convert.ToInt64(Session["iClientId"]);
string newPaymentMethod = "PayPal";
ClientPackageInfo obj = new ClientPackageInfo();
obj = objPaymentHelper.CalculateNewPackage(packageName, clientid, newPaymentMethod);
#region current package descriptor for paypal display
var newPkg = db.Package.Where(cs => cs.PackageId == obj.newPackageId).SingleOrDefault();
string paypalDisplayDecription = "Package : "+newPkg.Name+", Price : "+newPkg.Price+", Payable : "+obj.paymentAmount+", Description : "+newPkg.Description;
#endregion
if (obj.IsPaymentNeeded == true)
{
#region paypal viewdata
var viewData = new PayPalViewData();
var guid = Guid.NewGuid().ToString();
var paymentInit = new PayPal.Api.Payments.Payment
{
intent = "authorize",
payer = new PayPal.Api.Payments.Payer
{
payment_method = "paypal"
},
transactions = new List<PayPal.Api.Payments.Transaction>
{
new PayPal.Api.Payments.Transaction
{
amount = new PayPal.Api.Payments.Amount
{
currency = "USD",
total = (obj.paymentAmount + 0.0 + 0.0).ToString(),
details = new PayPal.Api.Payments.Details
{
subtotal = obj.paymentAmount.ToString(),
tax = 0.0.ToString(),
shipping = 0.0.ToString()
}
},
description = paypalDisplayDecription,
},
},
redirect_urls = new PayPal.Api.Payments.RedirectUrls
{
return_url = Utilities.ToAbsoluteUrl(HttpContext, String.Format("~/payment/confirmed?id={0}", guid)),
cancel_url = Utilities.ToAbsoluteUrl(HttpContext, String.Format("~/payment/index?id={0}", guid)),
},
};
viewData.JsonRequest = JObject.Parse(paymentInit.ConvertToJson()).ToString(Newtonsoft.Json.Formatting.Indented);
#endregion
#region create payment
try
{
var abc = ConfigManager.Instance.GetProperties()["ClientID"];
var abcc = ConfigManager.Instance.GetProperties()["ClientSecret"];
var accessToken = new PayPal.OAuthTokenCredential(ConfigManager.Instance.GetProperties()["ClientID"], ConfigManager.Instance.GetProperties()["ClientSecret"]).GetAccessToken();
var apiContext = new PayPal.APIContext(accessToken);
var createdPayment = paymentInit.Create(apiContext);
var approvalUrl = createdPayment.links.ToArray().FirstOrDefault(f => f.rel.Contains("approval_url"));
if (approvalUrl != null)
{
Session.Add(guid, createdPayment.id);
return Redirect(approvalUrl.href);
}
viewData.JsonResponse = JObject.Parse(createdPayment.ConvertToJson()).ToString(Newtonsoft.Json.Formatting.Indented);
return View("Error", viewData);
}
catch (PayPalException ex)
{
viewData.ErrorMessage = ex.Message;
return View("Error", viewData);
}
#endregion
}
else
{
#region save client information
SaveClientInfo saveinfo = new SaveClientInfo();
saveinfo = objPaymentHelper.SaveInfo(obj);
if(saveinfo.isSuccessfull == true)
{
Session["message"] = "show";
return RedirectToAction("Index", "iClientPackageHistory");
}
else
{
return View("Error");
}
#endregion
}
#endregion
}
I am not able to find a way to use the Checkout hosted pages of Paypal. I have already generated the code snippet of Paypal to be used on my page. Kindly help me how can I make changes to this code to be able to use Paypal Checkout Hosted Pages using C# MVC.

Categories

Resources