Beispiel #1
0
        public void TestConnectorSerialization()
        {
            var obj = new SampleConnector
                          {
                              Id = Guid.NewGuid(),
                              Name = "name",
                              DataType = NodeDataType.Int
                          };

            var tw = new StringWriter();
            using (var xw = XmlWriter.Create(tw))
            {
                xw.WriteStartElement("Node");
                obj.Serialize(xw);
                xw.WriteEndElement();
            }

            var sr = new StringReader(tw.ToString());
            using (var wr = XmlReader.Create(sr))
            {
                wr.ReadToFollowing("Node");
                var result = new SampleConnector();
                result.Deserialize(wr);

                Assert.AreEqual(obj.Id, result.Id);
                Assert.AreEqual(obj.Name, result.Name);
                Assert.AreEqual(obj.DataType, result.DataType);
            }
        }
Beispiel #2
0
        public void SetConnectedToWithNullShouldClearOldConnectorConnectee()
        {
            var connector1 = new SampleConnector();
            var connector2 = new SampleConnector();

            connector1.ConnectedTo = connector2;
            Assert.AreSame(connector1, connector2.ConnectedTo);

            connector1.ConnectedTo = null;
            Assert.IsNull(connector2.ConnectedTo);
        }
Beispiel #3
0
        public void TestAttributes()
        {
            var baseLocation = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);

            SampleConnector connector = new SampleConnector();

            connector.Initialize(baseLocation, null);

            var attributes = connector.GetAttributes();

            Assert.IsTrue(attributes.Any(), "Failed to get attributes list from SPO connector");
        }
Beispiel #4
0
        public void TestIdentifiersProvided()
        {
            var baseLocation = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);

            SampleConnector connector = new SampleConnector();

            connector.Initialize(baseLocation, null);

            var identifierTypes = connector.IdentifierTypesProvided;

            Assert.IsTrue(identifierTypes.Any(), "Expected identifiers provided.");
        }
        static void RunConnector()
        {
            var settings = ServerSettings.DefaultSettings();

            settings.Port = 7080;

            var server = new HTTPServer(settings, ConsoleLogger.Write);

            Console.WriteLine("Starting Phantasma Sample connector at port " + settings.Port);

            /*
             * server.Get("/authorize/{dapp}", (request) =>
             * {
             *  return link.Execute(request.url);
             * });
             *
             * server.Get("/getAccount/{dapp}/{token}", (request) =>
             * {
             *  return link.Execute(request.url);
             * });
             *
             * server.Get("/invokeScript/{script}/{dapp}/{token}", (request) =>
             * {
             *  return link.Execute(request.url);
             * });*/

            var api  = new PhantasmaAPI("http://localhost:7078");
            var link = new SampleConnector(api);

            server.WebSocket("/phantasma", (socket) =>
            {
                while (socket.IsOpen)
                {
                    var msg = socket.Receive();

                    if (msg.CloseStatus == WebSocketCloseStatus.None)
                    {
                        var str = Encoding.UTF8.GetString(msg.Bytes);

                        link.Execute(str, (id, root, success) =>
                        {
                            root.AddField("id", id);
                            root.AddField("success", success);

                            var json = JSONWriter.WriteToString(root);
                            socket.Send(json);
                        });
                    }
                }
            });

            server.Run();
        }
Beispiel #6
0
        public void CloneTest()
        {
            var source = new SampleConnector {Name = "source"};

            var cloneTo = new SampleConnector();
            cloneTo = (SampleConnector) source.Clone(cloneTo);

            Assert.AreEqual(source.Name, cloneTo.Name);

            cloneTo = (SampleConnector) source.Clone();
            Assert.AreEqual(source.Name, cloneTo.Name);
        }
Beispiel #7
0
        public void TestGetAttribute()
        {
            var baseLocation = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);

            SampleConnector connector = new SampleConnector();

            connector.Initialize(baseLocation, null);

            var attribute = connector.GetAttribute("emergencycontact");

            Assert.IsNotNull(attribute is SampleAttribute, "Attribute type didnt match expected.");
            Assert.IsNotNull(attribute.Name == "emergencycontact", "Attribute name didnt match expected.");
        }
Beispiel #8
0
        public void TestAudit()
        {
            var baseLocation = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);

            SampleConnector connector = new SampleConnector();

            connector.Initialize(baseLocation, null);

            var store = new MemoryAuditStore();

            // do the audit
            connector.Audit(false, GetAudienceCollection(), store);

            Assert.IsTrue(store.Results.Any(), "Didn't get audit results");
            Assert.IsTrue(store.Results.SelectMany(r => r.Errors).Any(), "Didn't get audit errors");
        }
Beispiel #9
0
        public void TestIdentifiersRequired()
        {
            var baseLocation = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);

            SampleConnector connector = new SampleConnector();

            connector.Initialize(baseLocation, null);

            var identifiersRequired = connector.IdentifierTypesRequired;

            var upn        = identifiersRequired.FirstOrDefault(i => i.Type == CommonIdentifierTypes.Upn.ToString());
            var employeeId = identifiersRequired.FirstOrDefault(i => i.Type == CommonIdentifierTypes.EmployeeId.ToString());

            Assert.IsNotNull(upn, "Didn't get a upn identifier required, should have");
            Assert.IsNotNull(employeeId, "Didn't get an employeeid identifier required, should have");
        }
Beispiel #10
0
        public void TestGetUser()
        {
            var baseLocation = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);

            SampleConnector connector = new SampleConnector();

            connector.Initialize(baseLocation, null);

            var identifiers = new IdentifierCollection();

            identifiers.Add(new UpnIdentifier("*****@*****.**"));

            var attributes = new List <IAttribute>();

            var profile = connector.GetUser(identifiers, attributes);

            Assert.IsTrue(profile.Properties.Any(), "Failed to get attributes");
            Assert.IsTrue(profile.Identifiers.Identifiers.Any(), "Failed to get identifiers");
        }
Beispiel #11
0
        public void TestUpdate()
        {
            var baseLocation = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);

            SampleConnector connector = new SampleConnector();

            connector.Initialize(baseLocation, null);

            var identifiers = new IdentifierCollection();

            identifiers.Add(new UpnIdentifier("*****@*****.**"));

            var emergencyContactValue = "You need a " + Guid.NewGuid().ToString("D") + " emergency contact";

            // set the value
            connector.UpdateAttribute(identifiers, new SampleAttribute("emergencycontact"), emergencyContactValue);

            var attributes = new List <IAttribute>();
            var profile    = connector.GetUser(identifiers, attributes);

            Assert.IsTrue(profile.Properties["emergencycontact"].ToString() == emergencyContactValue, "Expected attibute value to be the new one. It wasn't.");
        }
Beispiel #12
0
        /// <summary>
        /// Validates the merchant account.
        /// </summary>
        /// <param name="request">The request.</param>
        /// <param name="errors">The error list to add any validation errors.</param>
        private static void ValidateMerchantAccount(Request request, List <PaymentError> errors)
        {
            var processor = new SampleConnector();

            // Prepare a request for validating merchant account
            var validateMerchantAccountRequest = new Request();

            validateMerchantAccountRequest.Locale = request.Locale;
            var validateMerchantAccountRequestPropertyList = new List <PaymentProperty>();

            foreach (var paymentProperty in request.Properties)
            {
                if (paymentProperty.Namespace == GenericNamespace.MerchantAccount)
                {
                    validateMerchantAccountRequestPropertyList.Add(paymentProperty);
                }
            }

            validateMerchantAccountRequest.Properties = validateMerchantAccountRequestPropertyList.ToArray();

            // Validates the merchant account by calling the payment processor
            Response validateMerchantAccountResponse = processor.ValidateMerchantAccount(validateMerchantAccountRequest);

            if (validateMerchantAccountResponse != null)
            {
                if (validateMerchantAccountResponse.Errors != null)
                {
                    errors.AddRange(validateMerchantAccountResponse.Errors);
                }
            }
            else
            {
                var error = new PaymentError(ErrorCode.InvalidMerchantConfiguration, "Merchant configuraiton is invalid.");
                errors.Add(error);
            }
        }
        /// <summary>
        /// Process the card payment, e.g. Tokenize, Authorize, Capture.
        /// </summary>
        /// <param name="paymentEntry">The card payment entry.</param>
        /// <returns>The payment result.</returns>
        private CardPaymentResult ProcessPayment(CardPaymentEntry paymentEntry)
        {
            // Get payment processor
            var processor = new SampleConnector();

            // Prepare payment request
            var paymentRequest = new Request();

            paymentRequest.Locale = paymentEntry.EntryLocale;

            // Get payment properties from payment entry which contains the merchant information.
            Request entryData = JsonConvert.DeserializeObject <Request>(paymentEntry.EntryData);

            PaymentProperty[] entryPaymentProperties = entryData.Properties;
            var requestProperties = new List <PaymentProperty>();

            // Filter payment card properties (they are default card data, not final card data)
            foreach (var entryPaymentProperty in entryPaymentProperties)
            {
                if (entryPaymentProperty.Namespace != GenericNamespace.PaymentCard)
                {
                    requestProperties.Add(entryPaymentProperty);
                }
            }

            // Add final card data
            PaymentProperty property;

            if (this.isSwipe)
            {
                property = new PaymentProperty(
                    GenericNamespace.PaymentCard,
                    PaymentCardProperties.CardEntryType,
                    CardEntryTypes.MagneticStripeRead.ToString());
                requestProperties.Add(property);

                if (!string.IsNullOrWhiteSpace(this.track1))
                {
                    property = new PaymentProperty(
                        GenericNamespace.PaymentCard,
                        PaymentCardProperties.Track1,
                        this.track1);
                    requestProperties.Add(property);
                }

                if (!string.IsNullOrWhiteSpace(this.track2))
                {
                    property = new PaymentProperty(
                        GenericNamespace.PaymentCard,
                        PaymentCardProperties.Track2,
                        this.track2);
                    requestProperties.Add(property);
                }
            }
            else
            {
                property = new PaymentProperty(
                    GenericNamespace.PaymentCard,
                    PaymentCardProperties.CardEntryType,
                    CardEntryTypes.ManuallyEntered.ToString());
                requestProperties.Add(property);
            }

            property = new PaymentProperty(
                GenericNamespace.PaymentCard,
                PaymentCardProperties.CardType,
                this.cardType);
            requestProperties.Add(property);

            property = new PaymentProperty(
                GenericNamespace.PaymentCard,
                PaymentCardProperties.CardNumber,
                this.cardNumber);
            requestProperties.Add(property);

            property = new PaymentProperty(
                GenericNamespace.PaymentCard,
                PaymentCardProperties.ExpirationMonth,
                this.cardExpirationMonth);
            requestProperties.Add(property);

            property = new PaymentProperty(
                GenericNamespace.PaymentCard,
                PaymentCardProperties.ExpirationYear,
                this.cardExpirationYear);
            requestProperties.Add(property);

            if (!string.IsNullOrWhiteSpace(this.cardSecurityCode))
            {
                property = new PaymentProperty(
                    GenericNamespace.PaymentCard,
                    PaymentCardProperties.AdditionalSecurityData,
                    this.cardSecurityCode);
                requestProperties.Add(property);
            }

            property = new PaymentProperty(
                GenericNamespace.PaymentCard,
                PaymentCardProperties.Name,
                this.cardHolderName);
            requestProperties.Add(property);

            property = new PaymentProperty(
                GenericNamespace.PaymentCard,
                PaymentCardProperties.StreetAddress,
                this.cardStreet1);
            requestProperties.Add(property);

            property = new PaymentProperty(
                GenericNamespace.PaymentCard,
                PaymentCardProperties.City,
                this.cardCity);
            requestProperties.Add(property);

            property = new PaymentProperty(
                GenericNamespace.PaymentCard,
                PaymentCardProperties.State,
                this.cardStateOrProvince);
            requestProperties.Add(property);

            property = new PaymentProperty(
                GenericNamespace.PaymentCard,
                PaymentCardProperties.PostalCode,
                this.cardPostalCode);
            requestProperties.Add(property);

            property = new PaymentProperty(
                GenericNamespace.PaymentCard,
                PaymentCardProperties.Country,
                this.cardCountryOrRegion);
            requestProperties.Add(property);

            // Tokenize the card if requested
            Response tokenizeResponse = null;

            if (paymentEntry.SupportCardTokenization)
            {
                paymentRequest.Properties = requestProperties.ToArray();
                tokenizeResponse          = processor.GenerateCardToken(paymentRequest, null);
                if (tokenizeResponse.Errors != null && tokenizeResponse.Errors.Any())
                {
                    // Tokenization failure, Throw an exception and stop the payment.
                    throw new CardPaymentException("Tokenization failure.", tokenizeResponse.Errors);
                }
            }

            // Authorize and Capture if requested
            // Do not authorize if tokenization failed.
            Response        authorizeResponse = null;
            Response        captureResponse   = null;
            Response        voidResponse      = null;
            TransactionType transactionType   = (TransactionType)Enum.Parse(typeof(TransactionType), paymentEntry.TransactionType, true);

            if (transactionType == TransactionType.Authorize || transactionType == TransactionType.Capture)
            {
                // Add request properties for Authorize and Capture
                if (!string.IsNullOrWhiteSpace(this.voiceAuthorizationCode))
                {
                    property = new PaymentProperty(
                        GenericNamespace.PaymentCard,
                        PaymentCardProperties.VoiceAuthorizationCode,
                        this.voiceAuthorizationCode);
                    requestProperties.Add(property);
                }

                property = new PaymentProperty(
                    GenericNamespace.TransactionData,
                    TransactionDataProperties.Amount,
                    this.paymentAmount);
                requestProperties.Add(property);

                // Authorize payment
                paymentRequest.Properties = requestProperties.ToArray();
                authorizeResponse         = processor.Authorize(paymentRequest, null);
                if (authorizeResponse.Errors != null && authorizeResponse.Errors.Any())
                {
                    // Authorization failure, Throw an exception and stop the payment.
                    throw new CardPaymentException("Authorization failure.", authorizeResponse.Errors);
                }

                if (transactionType == TransactionType.Capture)
                {
                    // Check authorization result
                    var             authorizeResponseProperties    = PaymentProperty.ConvertToHashtable(authorizeResponse.Properties);
                    PaymentProperty innerAuthorizeResponseProperty = PaymentProperty.GetPropertyFromHashtable(
                        authorizeResponseProperties,
                        GenericNamespace.AuthorizationResponse,
                        AuthorizationResponseProperties.Properties);

                    var innerAuthorizeResponseProperties = PaymentProperty.ConvertToHashtable(innerAuthorizeResponseProperty.PropertyList);

                    string authorizationResult = null;
                    PaymentProperty.GetPropertyValue(
                        innerAuthorizeResponseProperties,
                        GenericNamespace.AuthorizationResponse,
                        AuthorizationResponseProperties.AuthorizationResult,
                        out authorizationResult);

                    // TO DO: In this sample, we only check the authorization results. CVV2 result and AVS result are ignored.
                    if (AuthorizationResult.Success.ToString().Equals(authorizationResult, StringComparison.OrdinalIgnoreCase))
                    {
                        // Authorize success...
                        // Get authorized amount
                        decimal authorizedAmount = 0m;
                        PaymentProperty.GetPropertyValue(
                            innerAuthorizeResponseProperties,
                            GenericNamespace.AuthorizationResponse,
                            AuthorizationResponseProperties.ApprovedAmount,
                            out authorizedAmount);

                        // Update capture amount for partial authorization
                        if (this.paymentAmount != authorizedAmount)
                        {
                            foreach (var requestProperty in requestProperties)
                            {
                                if (GenericNamespace.TransactionData.Equals(requestProperty.Namespace) &&
                                    TransactionDataProperties.Amount.Equals(requestProperty.Name))
                                {
                                    requestProperty.DecimalValue = authorizedAmount;
                                    break;
                                }
                            }
                        }

                        // Capture payment
                        property = new PaymentProperty(
                            GenericNamespace.AuthorizationResponse,
                            AuthorizationResponseProperties.Properties,
                            innerAuthorizeResponseProperty.PropertyList);
                        requestProperties.Add(property);

                        paymentRequest.Properties = requestProperties.ToArray();
                        captureResponse           = processor.Capture(paymentRequest);

                        // Check capture result
                        var             captureResponseProperties    = PaymentProperty.ConvertToHashtable(captureResponse.Properties);
                        PaymentProperty innerCaptureResponseProperty = PaymentProperty.GetPropertyFromHashtable(
                            captureResponseProperties,
                            GenericNamespace.CaptureResponse,
                            CaptureResponseProperties.Properties);

                        var innerCaptureResponseProperties = PaymentProperty.ConvertToHashtable(innerCaptureResponseProperty.PropertyList);

                        string captureResult = null;
                        PaymentProperty.GetPropertyValue(
                            innerCaptureResponseProperties,
                            GenericNamespace.CaptureResponse,
                            CaptureResponseProperties.CaptureResult,
                            out captureResult);

                        if (!CaptureResult.Success.ToString().Equals(captureResult, StringComparison.OrdinalIgnoreCase))
                        {
                            // Capture failure, we have to void authorization and return the payment result.
                            voidResponse = processor.Void(paymentRequest);
                        }
                    }
                    else
                    {
                        // Authorization failure, Throw an exception and stop the payment.
                        var errors = new List <PaymentError>();
                        errors.Add(new PaymentError(ErrorCode.AuthorizationFailure, "Authorization failure."));
                        throw new CardPaymentException("Authorization failure.", errors);
                    }
                }
            }

            // Combine responses into one.
            Response paymentResponse = this.CombineResponses(tokenizeResponse, authorizeResponse, captureResponse, voidResponse);

            // Save payment result
            CardPaymentResult result = null;

            if (paymentResponse != null)
            {
                // Success
                paymentResponse.Properties = PaymentProperty.RemoveDataEncryption(paymentResponse.Properties);

                result                  = new CardPaymentResult();
                result.EntryId          = paymentEntry.EntryId;
                result.ResultAccessCode = CommonUtility.NewGuid().ToString();
                result.ResultData       = JsonConvert.SerializeObject(paymentResponse);
                result.Retrieved        = false;
                result.ServiceAccountId = paymentEntry.ServiceAccountId;
            }
            else
            {
                this.InputErrorsHiddenField.Value = WebResources.CardPage_Error_InvalidCard;
            }

            return(result);
        }