NopCommerce - How Can I use wsdl Service Reference in the plugin - asp.net-mvc

Recently I'm working on a payment plugin for zarinpal.com gate way.
I have to add a service reference by this URL :
https://sandbox.zarinpal.com/pg/services/WebGate/wsdl
Every thing is ok but in PostProcessPayment I face with the error :
Could not find default endpoint element that references contract
'ServiceReference.PaymentGatewayImplementationServicePortType'
in the ServiceModel client configuration section. This might be
because no configuration file was found for your application,
or because no endpoint element matching this contract could be found
in the client element.
and this is my PostProcessPayment method :
public void PostProcessPayment(PostProcessPaymentRequest postProcessPaymentRequest)
{
string urlToRedirect = "";
var zarinpal =
new ServiceReference.PaymentGatewayImplementationServicePortTypeClient();
string outResult = "";
int code = zarinpal.PaymentRequest("5607e960-d64c-4a8b-b03b-0e645bef37d4"
, 2500, "Our Test Store Name"
, "test#gmail.com", "0999999999"
, "http://" + _webHelper.GetStoreLocation(false)
+ "/Plugins/ZarinPal/PDTHandler", out outResult);// test
if (code == 100)
{
urlToRedirect = string.Concat("https://sandbox.zarinpal.com/pg/StartPay/"
, outResult);
}
_httpContext.Response.Redirect(urlToRedirect);
}
I would better to mention that if i add the Service Reference to Nop.Web Project too, it works well, but I want to build this as a module and adding the Service Reference Manually to Nop.Web is Unpleasant.
could you please help me ?

Related

Azure DevOps Client Library - Download Earlier Repository Files

I am trying to download earlier repository versions (.csproj files) from the commit records that I am obtaining from the Azure DevOps NuGet client library. I want to do this so I can access the Assembly Version information in the .csproj file. The GetFile() function I am using to get the current version of the file works fine but I want to download the older versions of the file from the commit records.
This is the GetFile function.
public string GetFile(string projectName, string repoName, string fileName)
{
try
{
var items = ListItems(projectName, repoName);
var projectPath = items.FirstOrDefault(i => i.Path.Contains(fileName))?.Path ?? "";
GitHttpClient gitClient = GetGitHttpClient();
GitRepository repo = GetRepositoryAsync(projectName, repoName);
var stream = gitClient.GetItemTextAsync(repo.Id, projectPath).Result;
var reader = new StreamReader(stream);
return reader.ReadToEnd();
}
catch (Exception e)
{
return "";
}
}
And this function gets the commits.
public async Task<List<GitCommitRef>> GetCommitsAsync(string projectName, string repoName)
{
var client = GetGitHttpClient();
var repo = GetRepositoryAsync(projectName, repoName);
var gitQueryCommitsCriteria = new GitQueryCommitsCriteria();
return await client.GetCommitsAsync(repo.Id, gitQueryCommitsCriteria);
}
Now I want to download each version of the .csproj that relates to each of these commits.
Any help anyone can give me with this would be greatly appreciated.
Kind regards, Stuart
The GetFile() function I am using to get the current version of the
file works fine but I want to download the older versions of the file
from the commit records.
I think you're in the right direction. I once used Azure Devops Rest Api Items-Get to get content of one specific version of file successfully with the help of versionDescriptor parameter.
https://dev.azure.com/MyOrgName/MyProjectName/_apis/git/repositories/MyReposName/Items?path=/README.md&versionDescriptor%5BversionOptions%5D=0&versionDescriptor%5BversionType%5D=2&versionDescriptor%5Bversion%5D={Commit ID}&download=true&resolveLfs=true&%24format=octetStream&api-version=5.0-preview.1
Since functions available in client library are corresponding to that in Rest Api, so client library must have corresponding parameters to do that.
And here's what I found:
Most of the overloads of gitClient.GetItemTextAsync() functions have GitVersionDescriptor versionDescriptor = null as input, and I think this is what you need.
Hope it makes some help.

MachineKeyDataProtector - Invalid link when confirmation email sent through background job

I've been pulling my hair out over this. Anytime a user registration email is sent out via my windows service (background task), I get an "Invalid link".
My setup
I'm using Hangfire as a windows service on our development server. This is where the problematic GenerateEmailConfirmationToken call is happening. It's in a completely different context, outside of the ASP.NET pipeline. So I have setup machineKey values to correspond with that in the web.config of the MVC application:
In the app.config of the Windows Service Console project, which transforms to MyApp.exe.config, I have a machineKey element
In the MVC 5 project - I have a machineKey element that matches the MyApp.exe.config machineKey element.
I've verified that BOTH of these have the same machine key element data.
The Problem
When I generate a user using the ASP.NET MVC context and pipeline (IE without going through the Hangfire Background job processing), the link works fine.
When I use the background job processor, I always get invalid link. I'm all out of ideas here.
Why is this happening? Is it because the token is being generated in a different thread? How do I get around this?
Relevant code for the various projects
IoC Bootstrapping
Gets called by both applications (Windows Service and MVC Web App)
container.Register<IUserTokenProvider<AppUser, int>>(() => DataProtector.TokenProvider, defaultAppLifeStyle);
DataProtector.cs
public class DataProtector
{
public static IDataProtectionProvider DataProtectionProvider { get; set; }
public static DataProtectorTokenProvider<AppUser, int> TokenProvider { get; set; }
static DataProtector()
{
DataProtectionProvider = new MachineKeyProtectionProvider();
TokenProvider = new DataProtectorTokenProvider<AppUser, int>(DataProtectionProvider.Create("Confirmation", "ResetPassword"));
}
}
Things I've Tried
Using a DpapiDataProtectionProvider
Custom MachineKeyProtectionProvider from Generating reset password token does not work in Azure Website
The MachineKeyProtectionProvider.cs code is exactly as the linked post above.
I've also tried other purposes like "YourMom" and "AllYourTokensAreBelongToMe" to no avail. Single purposes, multiple purposes - it doesn't matter - none work.
I'm also calling HttpUtility.UrlEncode(code) on the code that gets generated in both places (Controller and Background Job).
Solution
igor got it right, except it was not a code issue. It was because of a rogue service picking up the job, which had a different machine key. I had been staring at the problem so long that I did not see a second service running.
As I understand your problem there are 2 possible places where failure could occur.
1. MachineKey
It could be that the MachineKey itself is not producing a consistent value between your 2 applications. This can happen if your machineKey in the .config file is not the same in both applications (I did read that you checked it but a simple type-o, added space, added to the wrong parent element, etc. could lead to this behavior.). This can be easily tested to rule it out as a point of failure. Also the behavior might be different depending on the referenced .net framework, MachineKey.Protect
The configuration settings that are required for the MachineKeyCompatibilityMode.Framework45 option are required for this method even if the MachineKeySection.CompatibilityMode property is not set to the Framework45 option.
I created a random key pair for testing and using this key I generated a test value I assigned to variable validValue below in the code. If you copy/paste the following section into your web.config and app.config the Unprotect of that keyvalue will work.
web.config / app.config
<system.web>
<httpRuntime targetFramework="4.6.1"/>
<machineKey decryption="AES" decryptionKey="9ADCFD68D2089D79A941F9B8D06170E4F6C96E9CE996449C931F7976EF3DD209" validation="HMACSHA256" validationKey="98D92CC1E5688DB544A1A5EF98474F3758C6819A93CC97E8684FFC7ED163C445852628E36465DB4E93BB1F8E12D69D0A99ED55639938B259D0216BD2DF4F9E73" />
</system.web>
Service Application Test
class Program
{
static void Main(string[] args)
{
// should evaluate to SomeTestString
const string validValue = "03AD03E75A76CF13FDDA57425E9D362BA0FF852C4A052FD94F641B73CEBD3AC8B2F253BB45550379E44A4938371264BFA590F9E68E59DB57A9A4EB5B8B1CCC59";
var unprotected2 = MachineWrapper.Unprotect(validValue);
}
}
Mvc Controller (or Web Api controller) Test
public class WebTestController : Controller
{
// GET: WebTest
public ActionResult Index()
{
// should evaluate to SomeTestString
const string validValue = "03AD03E75A76CF13FDDA57425E9D362BA0FF852C4A052FD94F641B73CEBD3AC8B2F253BB45550379E44A4938371264BFA590F9E68E59DB57A9A4EB5B8B1CCC59";
var unprotected2 = MachineWrapper.Unprotect(validValue);
return View(unprotected2);
}
}
Common Code
using System;
using System.Linq;
using System.Text;
using System.Web.Security;
namespace Common
{
public class MachineWrapper
{
public static string Protect()
{
var testData = "SomeTestString";
return BytesToString(MachineKey.Protect(System.Text.Encoding.UTF8.GetBytes(testData), "PasswordSafe"));
}
public static string Unprotect(string data)
{
var bytes = StringToBytes(data);
var result = MachineKey.Unprotect(bytes, "PasswordSafe");
return System.Text.Encoding.UTF8.GetString(result);
}
public static byte[] StringToBytes(string hex)
{
return Enumerable.Range(0, hex.Length)
.Where(x => x % 2 == 0)
.Select(x => Convert.ToByte(hex.Substring(x, 2), 16))
.ToArray();
}
public static string BytesToString(byte[] bytes)
{
var hex = new StringBuilder(bytes.Length * 2);
foreach (byte b in bytes)
hex.AppendFormat("{0:x2}", b);
return hex.ToString().ToUpper();
}
}
}
If this passes both Console and the Web Application will get the same value and not throw a CryptographicException message Error occurred during a cryptographic operation. If you want to test with your own keys just run Protect from the common MachineWrapper class and record the value and re-execute for both apps.
2. UserManager uses Wrong Type
I would start with the previous section BUT the other failure point is that your custom machine key provider is not being used by the Microsoft.AspNet.Identity.UserManager. So here are some questions/action items that can help you figure out why this is happening:
Is container.Register the Unity IoC framework or are you using another framework?
Are you sure that your Di framework is also injecting that instance in the Microsoft.AspNet.Identity.UserManager in both the Service application as well as the Web application?
Have put a break point in public byte[] Protect of your MachineKeyDataProtector class to see if this is called in both the Service application as well as the Web application?
From examples I have seen so far (including the one you posted with the custom MachineKey solution) you need to manually bootstrap the type during application startup but then again I have not ever tried to hook into the Identity framework to replace this component using DI.
If you look at the default Visual Studio template code that is provided when you create a new MVC application the code file App_Start\IdentityConfig.cs would be the place to add this new provider.
Method:
public static ApplicationUserManager Create(IdentityFactoryOptions<ApplicationUserManager> options, IOwinContext context)
Replace
var dataProtectionProvider = options.DataProtectionProvider;
if (dataProtectionProvider != null)
{
manager.UserTokenProvider = new DataProtectorTokenProvider<ApplicationUser>(dataProtectionProvider.Create("ASP.NET Identity"));
}
With this
var provider = new MachineKeyProtectionProvider();
manager.UserTokenProvider = new DataProtectorTokenProvider<ApplicationUser>(provider.Create("ResetPasswordPurpose"));
And this has to be configured for both applications if you are not using a common library where this is configured.

Using GitLab API to set external issues tracker settings?

I'm using GitLab with an external issue tracker (JIRA), and it works well.
My problem is when I create a new GitLab project (using API), I have to go the GitLab's project settings and manually select the issue tracker I want to use and manually enter the project's id of my external issue tracker.
This screen will be more eloquent:
(source: bayimg.com)
(The two fields I am talking about are "Issue tracker" and "Project name or id in issues tracker")
So here is my question: is there any way to set up this two fields automatically, using API or other ? Currently, GitLab API does not mention anything about external issues tracker settings.
This code helped me to automatically set the GitLab's external issues-tracker settings, using Apache HttpClient and Jsoup.
This code is absolutely not 100% good, but it shows the main idea, wich is to recreate the corresponding POST request that the web form sends.
// 1 - Prepare the HttpClient object :
BasicCookieStore cookieStore = new BasicCookieStore();
LaxRedirectStrategy redirectStrategy = new LaxRedirectStrategy();
CloseableHttpClient httpclient = HttpClients.custom()
.setDefaultCookieStore(cookieStore)
.setRedirectStrategy(redirectStrategy)
.build();
try {
// 2 - Second you need to get the "CSRF Token", from a <meta> tag in the edit page :
HttpUriRequest getCsrfToken = RequestBuilder.get()
.setUri(new URI("http://localhost/_NAMESPACE_/_PROJECT_NAME_/edit"))
.build();
CloseableHttpResponse responseCsrf = httpclient.execute(getCsrfToken);
try {
HttpEntity entity = responseCsrf.getEntity();
Document doc = Jsoup.parse(EntityUtils.toString(entity));
String csrf_token = doc.getElementsByAttributeValue("name", "csrf-token").get(0).attr("content");
// 3 - Fill and submit the "edit" form with new values :
HttpUriRequest updateIssueTracker = RequestBuilder
.post()
.setUri(new URI("http://localhost/_NAMESPACE_/_PROJECT_NAME_"))
.addParameter("authenticity_token", csrf_token)
.addParameter("private_token", "_MY_PRIVATE_TOKEN_")
.addParameter("_method", "patch")
.addParameter("commit", "Save changes")
.addParameter("utf8", "✓")
.addParameter("project[issues_tracker]", "jira")
.addParameter("project[issues_tracker_id]", "_MY_JIRA_PROJECT_NAME_")
.addParameter("project[name]", "...")
...
.build();
CloseableHttpResponse responseSubmit = httpclient.execute(updateIssueTracker, httpContext);
} finally {
responseCsrf.close();
}
} finally {
httpclient.close();
}
Change _NAMESPACE_/_PROJECT_NAME_ to make it corresponds to your project URL, change _MY_PRIVATE_TOKEN_ with your admin account's token, and change _MY_JIRA_PROJECT_NAME_ with ... your jira project's name.

issue in consuming wcf service in mvc 4

I'm having a class and interface like this in my wcf application IService1.cs
[ServiceContract]
public interface IService1
{
[OperationContract]
string insertValues(empInfo objInfo);
}
[DataContract]
public class empInfo
{
string _organizationName = string.Empty;
string _organizationAddr = string.Empty;
int? _totalemp;
}
And in Service1.svc.cs, i have implemented that interface.
public class Service1 : IService1
{
public string insertValues(empInfo objInfo)
{
.....
}
}
then i have created a empty mvc4 client application to consume this wcf service.
i have added the ServiceReference,Now its appear in the service reference folder as ServiceReference1.Then i did this
1. created a controller named Defalut1controller.
2. In this controller i try to add the following line
ServiceReference1.Service1Client proxy = new ServiceReference1.Service1Client();
inside the ActionResult. But unable to get the ServiceReference1 word.
its (ServiceReference1) appearing when i update my service like this
From - string insertValues(empInfo objInfo); - To - string insertValues(string objInfo);
and now i have build this wcf application, and update the service reference in my client mvc4 application. Now the
ServiceReference1.Service1Client proxy = new ServiceReference1.Service1Client();
line is enabled.
I have tried with the .net web application to consume the same, i can able to do without any problem, what i have missed with mvc4, please help. thanks in advance..
I got the answer, thanks to stackoverflow.
This is the solution:
Right click on Service Reference
Select Configure Service Reference
Select Reuse types in specified referenced assemblies
Just select everything except "Newtonsoft.json"
It worked for me as well.
The question itself and the problem you are facing is a bit unclear for me but have you actually tried exposing any public properties on your empInfo data contract? Cause right now you have only 3 private fields which will not be generated in the proxy code on the client side.
Microsoft has fixed this issue in this update: http://support.microsoft.com/kb/2750149

Facebook OAuth + AppHarbor workaround on random port

I a have a sample app, hosted on AppHarbor and now want to integrate authorization through facebook. So i downloaded nugget Facebook.Web.Mvc package to implement it.
After reading tutorial, in controller i have method:
public ActionResult Login(string returnUrl)
{
var oauthClient = new FacebookOAuthClient(FacebookApplication.Current) { RedirectUri = GetFacebookRedirectUri() };
if (!string.IsNullOrWhiteSpace(returnUrl))
{
returnUrl = Url.Action("Index", "Facebook");
}
dynamic parameters = new ExpandoObject();
parameters.scope = ExtendedPermissions;
var state = new { csrf_token = CalculateMD5Hash(Guid.NewGuid().ToString()), return_url = returnUrl };
parameters.state = Base64UrlEncode(Encoding.UTF8.GetBytes(JsonSerializer.Current.SerializeObject(state)));
SetFacebookCsrfToken(state.csrf_token);
string s = oauthClient.GetLoginUrl(parameters).AbsoluteUri;
ViewBag.FacebookLoginUrl = s;
//new LogEvent(s).Raise();
return View(new AccountModel());
}
View:
<a href="#ViewBag.FacebookLoginUrl" id="lUrl">
<div class="fblogin"></div>
In localhost this works for me.
But when i upload it to appharbor, i see, that generated link indicates to address + port 16013 (as support told always random port). So clicking it shows me facebook login window, than blank page.
I manually configured my app settings in facebook to this port but it did not helped.
Also i tried to access my site through this port - nothing.
Then i changed port number through jquery to 80, its also did not help.
you have had such problems?
I'm not familiar with the Facebook api, but I've had a similar problem.
I suspect that the returnUrl value being passed in is incorrect. It probably contains a port number that AppHarbor uses internally for load balancing.
See this article on how to create a public url for AppHarbor:
http://support.appharbor.com/kb/getting-started/workaround-for-generating-absolute-urls-without-port-number
Then make sure that the value in your returnUrl is publicly available.
You can now set the aspnet:UseHostHeaderForRequestUrl appSetting to true which effectively solves this problem. This can be done by adding a Configuration Variable to your application with the corresponding key and value.
Source on AppHarbor

Resources