I need to split my unity configuration into n different files so i can select it some of those files into the same unity container??
OK. It's too late but I could answer.
You need something like this:
private IUnityContainer ReadContainer()
{
var unityCommon = (UnityConfigurationSection)ConfigurationManager.GetSection("unityCommon");
IUnityContainer returnValue = new UnityContainer();
unityCommon.Configure(returnValue, "Common"); // Unnamed <container> element
var unitySpecific = (UnityConfigurationSection)ConfigurationManager.GetSection("unitySpecific");
unitySpecific.Configure(returnValue, "Specific"); //
return returnValue;
}
And have this in app.config:
<configSections>
<section name="unityCommon" type="Microsoft.Practices.Unity.Configuration.UnityConfigurationSection, Microsoft.Practices.Unity.Configuration"/>
<section name="unitySpecific" type="Microsoft.Practices.Unity.Configuration.UnityConfigurationSection, Microsoft.Practices.Unity.Configuration"/>
</configSections>
<unityCommon configSource="unity.common.config.xml" />
Related
Has anyone used Sage Pay with asp.net Webpages??
I have downloaded the integration kit from Sage Pay but this is made in webforms and i am having trouble converting it the WebPages format.
Sage Pay are no help so i'm hoping someone out there has done this. Or can point me in the right direction.
I have managed to do this using the class from the SagePay template you can download.
Put these files in your bin folder:-
SagePay.IntegrationKit.DotNet.dll
SagePay.IntegrationKit.DotNet.pdb
Put these files in your App_Code folder:-
SagePayConfiguration.cs
SagePayAPIIntegration.cs
SagePayFormIntegration.cs
You also need to add some stuff to your web.config file
<SagePayConfiguration>
<!--Mandatory
Set to TEST for the Test Server and LIVE for the live environment-->
<add key="sagepay.api.env" value="TEST" />
<!--Transaction Settings -->
<add key="sagepay.api.protocolVersion" value="3.00" />
<add key="sagepay.kit.vendorName" value="your Name" />
<add key="sagepay.kit.fullUrl" value="your url" />
<add key="sagepay.kit.currency" value="GBP" />
<!--Optional setting. It's recommended to set the siteFqdn value to the Fully
Qualified Domain Name of your server.
This should start http:// or https:// and should be the name by which our servers can call back to yours
i.e. it MUST be resolvable externally, and have access granted to the Sage Pay servers
examples would be https://yoursite or http://212.111.32.22/
NOTE: Do not include any URI path.
If you leave this value blank the kit will use the current host name-->
<add key="sagepay.kit.siteFqdn.LIVE" value="http://your web address" />
<add key="sagepay.kit.siteFqdn.TEST" value="http://your web address" />
<!--Mandatory. Usually PAYMENT. This can be DEFERRED or AUTHENTICATE if your Sage Pay
account supports those payment types
NB Ideally all DEFERRED transaction should be released within 6 days (according to card scheme rules).
DEFERRED transactions can be ABORTed before a RELEASE if necessary-->
<add key="sagepay.kit.defaultTransactionType" value="PAYMENT" />
<!--0 = If AVS/CV2 enabled then check them. If rules apply, use rules (default).
1 = Force AVS/CV2 checks even if not enabled for the account. If rules apply, use rules.
2 = Force NO AVS/CV2 checks even if enabled on account.
3 = Force AVS/CV2 checks even if not enabled for the account but DON'T apply any rules.-->
<add key="sagepay.kit.applyAvsCv2" value="0" />
<!--0 = If 3D-Secure checks are possible and rules allow, perform the checks and apply the authorisation rules. (default)
1 = Force 3D-Secure checks for this transaction if possible and apply rules for authorisation.
2 = Do not perform 3D-Secure checks for this transaction and always authorise.
3 = Force 3D-Secure checks for this transaction if possible but ALWAYS obtain an auth code, irrespective of rule base.-->
<add key="sagepay.kit.apply3dSecure" value="0" />
<!--FORM Protocol Only Settings
Set this value to the Encryption password assigned to you by Sage Pay -->
<add key="sagepay.kit.form.encryptionPassword.TEST" value="Your password" />
<add key="sagepay.kit.form.encryptionPassword.LIVE" value="Your password" />
<!--The Sage Pay server URLs to which customers will be sent for payment for each environment-->
<add key="sagepay.api.formPaymentUrl.LIVE" value="https://live.sagepay.com/gateway/service/vspform-register.vsp" />
<add key="sagepay.api.formPaymentUrl.TEST" value="https://test.sagepay.com/gateway/service/vspform-register.vsp" />
</SagePayConfiguration>
To make this easier to manage i have but this web.config file in the checkout folder so it is easy to keep updated.
I also created the following class to encrypt and dencrypt the data:-
you can call it what ever you want but it needs to be saved in the App_Code folder.
using System;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.IO;
public static class EncryptionHelper
{
private static byte[] keyAndIvBytes;
static EncryptionHelper()
{
// You'll need a more secure way of storing this, I this isn't
// a real key
keyAndIvBytes = UTF8Encoding.UTF8.GetBytes("123123123123123b");
}
public static string ByteArrayToHexString(byte[] ba)
{
return BitConverter.ToString(ba).Replace("-", "");
}
public static byte[] StringToByteArray(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 DecodeAndDecrypt(string cipherText)
{
string DecodeAndDecrypt = AesDecrypt(StringToByteArray(cipherText));
return (DecodeAndDecrypt);
}
public static string EncryptAndEncode(string plaintext)
{
return ByteArrayToHexString(AesEncrypt(plaintext));
}
public static string AesDecrypt(Byte[] inputBytes)
{
Byte[] outputBytes = inputBytes;
string plaintext = string.Empty;
using (MemoryStream memoryStream = new MemoryStream(outputBytes))
{
using (CryptoStream cryptoStream = new CryptoStream(memoryStream, GetCryptoAlgorithm().CreateDecryptor(keyAndIvBytes, keyAndIvBytes), CryptoStreamMode.Read))
{
using (StreamReader srDecrypt = new StreamReader(cryptoStream))
{
plaintext = srDecrypt.ReadToEnd();
}
}
}
return plaintext;
}
public static byte[] AesEncrypt(string inputText)
{
byte[] inputBytes = UTF8Encoding.UTF8.GetBytes(inputText);//AbHLlc5uLone0D1q
byte[] result = null;
using (MemoryStream memoryStream = new MemoryStream())
{
using (CryptoStream cryptoStream = new CryptoStream(memoryStream, GetCryptoAlgorithm().CreateEncryptor(keyAndIvBytes, keyAndIvBytes), CryptoStreamMode.Write))
{
cryptoStream.Write(inputBytes, 0, inputBytes.Length);
cryptoStream.FlushFinalBlock();
result = memoryStream.ToArray();
}
}
return result;
}
private static RijndaelManaged GetCryptoAlgorithm()
{
RijndaelManaged algorithm = new RijndaelManaged();
//set the mode, padding and block size
algorithm.Padding = PaddingMode.PKCS7;
algorithm.Mode = CipherMode.CBC;
algorithm.KeySize = 128;
algorithm.BlockSize = 128;
return algorithm;
}
}
I call the the class like so:-
string crypt = "blahblahblah";
string EncryptAndEncode = EncryptionHelper.EncryptAndEncode(crypt);
string DecodeAndDecrypt = EncryptionHelper.DecodeAndDecrypt(EncryptAndEncode);
When the transaction is complete i get the crypt with this code:-
IFormPaymentResult PaymentStatusResult = new DataObject();
if (Request.QueryString["crypt"] != null && !string.IsNullOrEmpty(Request.QueryString["crypt"]))
{
SagePayFormIntegration sagePayFormIntegration = new SagePayFormIntegration();
PaymentStatusResult = sagePayFormIntegration.ProcessResult(Request.QueryString["crypt"]);
}
you can then call the needed information from the calss like so
if (PaymentStatusResult.Status == ResponseStatus.NOTAUTHED)
{reason = "You payment was declined by the bank. This could be due to insufficient funds, or incorrect card details.";}
You can see all the fields in the Result.aspx of the SagePay template.
I want to store my reports in another folder other than tests-output with time stamping
so i added a program:
public class Customreporter implements IReporter
{
File fd = new File("");
String date;
DateFormat df = new SimpleDateFormat("yyyy-MM-dd_hh-mm-ss");
String folderNameWithTimeStamp = df.format(new Date());
String currentDir = System.getProperty("user.dir") + "//Reports//";
String finalPath = currentDir + folderNameWithTimeStamp;
#SuppressWarnings("deprecation")
public void generateReport(List<XmlSuite> xmlSuites, List<ISuite> suites, String outputDirectory)
{
TestNG.getDefault().setOutputDirectory(finalPath);
TestNG.getDefault().setXmlSuites(xmlSuites);
}
}
and changed my xml to
<suite name="suitedemo" parallel="false">
<listeners>
<listener class-name="com.validation.Customreporter">
</listeners>
<test name="suitetestdemo">
<suite-files>
<suite-file path="./exceptions.xml" />
<suite-file path="./screenshot.xml" />
</suite-files>
</test>
</suite>
Now it's creating a new folder every time, but it is storing sometimes only emailalablereport. What can I do, I dont want to customise reports I only want to store reports in new folder every time I run the suites. I changed the build file, it's working but we are executing xml files, not build.
Thanks in advance
Smith
I have seen similar behaviour when using setOutputDirectory(). But when i changed the implementation it worked for me. Instead of creating a testng xml during design time, i create one dynamically using the TestNG XmlSuite class. And then setting a different output directory using setOutputDirectory(). Let me know if you need more help on this.
At a high level,
XmlSuite suite = new XmlSuite();
suite.setSuiteFiles(files);
List<XmlSuite> suites = new ArrayList<XmlSuite>();
suites.add(suite);
TestNG tng = new TestNG();
tng.setXmlSuites(suites);
I haven't tested the setSuiteFiles() as i have my testng xml at class level. Also this need not be a listener. You can have this in a main() or your init .......
Can any one let me know how to get a bool result, verifying a value exists in a web.config's key.
Scenario is,
I have this tag in my website...
<add key="isEnabled" value="False"/> for a website,
On this key value I keep my site 'on' and 'off' using
public static bool isEnabled = Convert.ToBoolean(WebConfigurationManager.AppSettings["isEnabled "]);
if(isEnabled)
{
//
}
now the requirement is got 3-4 websites now, want to change the above line to something like
<add key="SitesEnabled" value="1,4,5"/>
because i want to enable only 1st, 4th, 5th site
1 - is the static value for my 1st website, 2 - 2nd.....
But now how do I do on and off...my websites something like
public static bool OneSiteEnabled = Convert.ToBoolean(WebConfigurationManager.AppSettings[SitesEnabled="1"]); // true
public static bool TwoSiteEnabled = Convert.ToBoolean(WebConfigurationManager.AppSettings[SitesEnabled="2"]); //false
Please let me know ...Thanks
I would do it something like this:
using System.Linq;
var sitesEnabled =
ConfigurationManager.AppSettings["SitesEnabled"] != null
? ConfigurationManager.AppSettings["SitesEnabled"].Split(',')
: new string[0];
var oneSiteEnabled = sitesEnabled.Contains("1");
var twoSiteEnabled = sitesEnabled.Contains("2");
<appSettings>
<!-- Settings file for website! -->
<add key="DefaultCookieExpiryMins" value="30" />
</appSettings>
Why do I have to set everything as a string? Why can't I have different datatypes in there like int to help me stop having to cast everything?
This is why I prefer custom configuration sections over just putting key/value pairs in appSettings. See this MSDN article for more information on how to make your own configuration section. Once you have your own configuration section class, you should be able to access your settings as any data type you'd like.
I just use generics for things like this.
public static T GetConfigurationValue<T>(string keyName)
{
if (System.Configuration.ConfigurationManager.AppSettings[keyName] != null)
{
T result;
try
{
result = (T)Convert.ChangeType(System.Configuration.ConfigurationManager.AppSettings[keyName], typeof(T));
}
catch
{
return default(T);
}
return result;
}
throw new ArgumentException("A key with the name " + keyName + " does not exist in the current configuration.", keyName);
}
Usage: GetConfigurationValue<int>("DefaultCookieExpiryMins");
Is there an utility or code sample that can decrypt with the old key, and then encrypt passwords with a new key for ASP.Net membership users?
None of the workarounds mentioned worked for me.
My solution is below. It involves first storing passwords in clear text and then reencrypting them again with new MachineKey.
Machine Key Change
This is my best guess at a solution, but I haven't had a chance to test it. It relies on the following settings for your current provider:
enablePasswordRetrieval="true" requiresQuestionAndAnswer="false" passwordFormat="Encrypted"
It also assumes that the new machinekey is already in the config file.
Create the following class (thanks to mootinator for the jumpstart on this)
using System.Reflection;
using System.Web.Configuration;
using System.Web.Security;
namespace MyNamespace
{
public class MySqlMembershipProvider : SqlMembershipProvider
{
protected override byte[] DecryptPassword(byte[] encodedPassword)
{
MachineKeySection section = (MachineKeySection)WebConfigurationManager.GetSection("system.web/machineKey");
section.DecryptionKey = "oldkey"; // TODO: Set your old key here
MethodInfo method = typeof(MachineKeySection).GetMethod("EncryptOrDecryptData", BindingFlags.Instance | BindingFlags.NonPublic);
return (byte[])method.Invoke(section, new object[] { encodedPassword, null, 0, encodedPassword.Length, 0, false, false });
}
}
}
In your web.config:
<membership defaultProvider="DefaultSqlMembershipProvider">
<providers>
<clear/>
<add name="DefaultSqlMembershipProvider" connectionStringName="MembershipConnectionString" enablePasswordRetrieval="true" requiresQuestionAndAnswer="false" applicationName="TODO" passwordFormat="Encrypted" type="System.Web.Security.SqlMembershipProvider"/>
<add name="MySqlMembershipProvider" connectionStringName="MembershipConnectionString" enablePasswordRetrieval="true" requiresQuestionAndAnswer="false" applicationName="TODO" passwordFormat="Encrypted" type="MyNamespace.MySqlMembershipProvider"/>
</providers>
</membership>
Change the passwords with the following code:
MembershipProvider retrievePasswordProvider = Membership.Providers["MySqlMembershipProvider"];
foreach (MembershipUser user in Membership.GetAllUsers())
{
MembershipUser retrievePassworedUser = retrievePasswordProvider.GetUser(user.UserName, false);
string password = retrievePassworedUser.GetPassword(); // get password using old key
user.ChangePassword(password, password); // change password to same password using new key
}
Let me know if that works for you.
I think you could do this by setting the key on the fly:
You might have to extend the SqlMembershipProvider (or whatever you use) to get access to the protected DecryptPassword method.
MachineKeySection section = (MachineKeySection)WebConfigurationManager.GetSection("system.web/machineKey");
section.DecryptionKey = "old";
// Read old password
section.DecryptionKey = "new";
// Store new password