public virtual void ShouldEncodeDecodeAddressString()
 {
     AddressType addressType = new AddressType();
     var result2 = addressType.Encode("0034567890abcdef1234567890abcdef12345678").ToHex();
     var result3 = addressType.Decode(result2, typeof(string));
     Assert.Equal("0x0034567890abcdef1234567890abcdef12345678", result3);
 }
Example #2
0
 public Address(string address1,string address2,string postCode,AddressType addressType)
 {
     this._address1 = address1;
     this._address2 = address2;
     this._postCode = postCode;
     this._addressType = addressType;
 }
Example #3
0
 public static string GetAddress(string Host, AddressType AddressFormat)
 {
     string IPAddress = string.Empty;
     AddressFamily addrFamily = AddressFamily.InterNetwork;
     switch (AddressFormat)
     {
         case AddressType.IPv4:
             addrFamily = AddressFamily.InterNetwork;
             break;
         case AddressType.IPv6:
             addrFamily = AddressFamily.InterNetworkV6;
             break;
     }
     IPHostEntry IPE = Dns.GetHostEntry(Host);
     if (Host != IPE.HostName)
     {
         IPE = Dns.GetHostEntry(IPE.HostName);
     }
     foreach (IPAddress IPA in IPE.AddressList)
     {
         if (IPA.AddressFamily == addrFamily)
         {
             return IPA.ToString();
         }
     }
     return string.Empty;
 }
Example #4
0
 /// <summary>
 /// Initializes a new instance of the <see cref="BaseAddress"/> class.
 /// </summary>
 /// <param name="region">The region.</param>
 /// <param name="address">The address.</param>
 /// <param name="size">The size.</param>
 /// <param name="prefetchable">if set to <c>true</c> [prefetchable].</param>
 public BaseAddress(AddressType region, uint address, uint size, bool prefetchable)
 {
     this.region = region;
     this.address = address;
     this.size = size;
     this.prefetchable = prefetchable;
 }
Example #5
0
 public AddressRange(AddressType desc, Byte id, UInt32 low, UInt32 high)
 {
     this.PId = id;
     this.PDesc = desc;
     this.PLow = low;
     this.PHigh = high;
 }
Example #6
0
 public SocksRequest(StreamTypes type, AddressType addrtype, string address, int port)
 {
     Type = addrtype;
     StreamType = type;
     Address = address;
     Port = port;
 }
Example #7
0
 public EmployeeAddress(AddressType type, string streetAddress, string city, string state, string zip)
 {
     _type = type;
     _streetAddress = streetAddress;
     _city = city;
     _zip = zip;
 }
Example #8
0
 public void AddAddressType(AddressType type)
 {
     if (!this.IsAddressType(type))
     {
         this.addressTypes.Add(type);
     }
 }
        internal Option(string displayName, int? addressId, AddressType? addressType, string postcode, OptionType optionType, Model.Link[] links)
        {
            if (string.IsNullOrWhiteSpace(displayName)) throw new ArgumentNullException("displayName");
            if (links == null) throw new ArgumentNullException("links");

            DisplayName = displayName;
            AddressId = addressId;
            AddressType = addressType;
            Postcode = postcode;
            OptionType = optionType;

            var newLinks = new List<Model.Link>();

            foreach (Model.Link link in links)
            {
                Model.Link newLink;

                switch (link.Rel)
                {
                    case "next":
                        newLink = new Link(link.Rel, link.Href);
                        break;
                    default:
                        newLink = link;
                        break;
                }

                newLinks.Add(newLink);
            }

            Links = newLinks.ToArray();
        }
        internal Response(ReturnCode result,
                          string postcode,
                          int? addressId,
                          AddressType? addressType,
                          MatchLevel matchLevel,
                          string[] postalAddress,
                          AddressElement[] postalAddressElements,
                          string[] geographicAddress,
                          AddressElement[] geographicAddressElements,
                          string[] vanityAddress,
                          AddressElement[] vanityAddressElements,
                          ReformattedAddressResult? reformattedAddressResult,
                          string[] reformattedAddress,
                          int totalOptions,
                          Option[] options,
                          Request input,
                          Model.Link[] links
            )
        {
            if (links == null) throw new ArgumentNullException("links");

            Result = result;
            Postcode = postcode;
            AddressId = addressId;
            AddressType = addressType;
            MatchLevel = matchLevel;
            PostalAddress = postalAddress;
            PostalAddressElements = postalAddressElements;
            GeographicAddress = geographicAddress;
            GeographicAddressElements = geographicAddressElements;
            VanityAddress = vanityAddress;
            VanityAddressElements = vanityAddressElements;
            ReformattedAddressResult = reformattedAddressResult;
            ReformattedAddress = reformattedAddress;
            TotalOptions = totalOptions;
            Options = options;
            Input = input;

            var newLinks = new List<Model.Link>();

            foreach (Model.Link link in links)
            {
                Model.Link newLink;

                switch (link.Rel)
                {
                    case "self":
                        newLink = new Model.PostcodeLookup.Link(link.Rel, link.Href);
                        break;
                    default:
                        newLink = link;
                        break;
                }

                newLinks.Add(newLink);
            }

            Links = newLinks.ToArray();
        }
        public void ParseAddressType_ReturnsCorrectString(AddressType addressType, string expected)
        {
            //act
            var result = EnumFactory.ParseAddressType(addressType);

            //assert
            result.Should().Be(expected);
        }
        public void EnumHelper_Parse_ReturnsCorrectEnum(string value, AddressType addressType)
        {
            //act
            var result = EnumHelper<AddressType>.Parse(value);

            //assert
            result.Should().Be(addressType);
        }
Example #13
0
 public SocksRequest(StreamTypes type, AddressType addrtype, string address, int port)
 {
     Type = addrtype;
     StreamType = type;
     Address = address;
     Port = port;
     Error = SocksError.Granted;
     IPAddress p = this.IP; //get Error on the stack.
 }
Example #14
0
 internal SmsMessage(int index, SmsMessageStatus status, string senderPhoneNumber, 
     AddressType addrType, DateTime timestamp, string body)
 {
     this.Index = index;
     this.Status = status;
     this.Number = senderPhoneNumber;
     this.Timestamp = timestamp;
     this.AddressType = addrType;
     this.Body = body;
 }
Example #15
0
 public Address(byte[] data, AddressType type, Network network = null)
 {
     if (data.Length != ADDRESS_SIZE)
     {
         throw new ArgumentException("Invalid Address");
     }
     Data = data;
     Type = type;
     Network = (network ?? Network.Default);
 }
 public static IAddressType MapCustomerAddressTypeToAddressType(this AuthorizeNet.APICore.customerAddressType response)
 {
     var result = new AddressType();
     result.AddressLine1 = response.address;
     result.City = response.city;
     result.Company = response.company;
     result.Country = response.country;
     result.PhoneNumber = response.phoneNumber;
     result.PostalCode = response.zip;
     result.State = response.state;
     return result;
 }
 // constructor for loading an EXISTING Address - This constructor DOES NOT create a new GUID
 public Address(Guid addressId, Guid personId, int streetNumber, string streetName, string addressCity, string addressState, string addressZip,
                AddressType addressType)
 {
     _addressId = addressId;
     _personId = personId;
     _streetNumber = streetNumber;
     _streetName = streetName;
     _addressCity = addressCity;
     _addressState = addressState;
     _addressZip = addressZip;
     _addressType = addressType;
 }
        public virtual void SetAddress(Address address, AddressType type)
        {
            if (address == null) return;

            Addresses = Addresses ?? new HashSet<ClientAddress>();
            var customerAddress = Addresses.FirstOrDefault(x => Equals(x.Address, address));
            if (customerAddress == null)
            {
                customerAddress = new ClientAddress(this, address, type);
                Addresses.Add(customerAddress);
            }
            customerAddress.Address = address;
        }
 /// <summary>
 /// Converts a braintree address to a <see cref="IAddress"/>.
 /// </summary>
 /// <param name="address">
 /// The address.
 /// </param>
 /// <param name="addressType">
 /// The address type.
 /// </param>
 /// <returns>
 /// The <see cref="IAddress"/>.
 /// </returns>
 public static IAddress ToAddress(this global::Braintree.Address address, AddressType addressType)
 {
     return new Core.Models.Address()
                {
                    Name = string.Format("{0} {1}", address.FirstName, address.LastName),
                    Address1 = address.StreetAddress,
                    Locality = address.Locality,
                    Region = address.Region,
                    PostalCode = address.PostalCode,
                    CountryCode = address.CountryCodeAlpha2,
                    AddressType = addressType
                };
 }
 private Address GetAddress(int userId, AddressType type)
 {
     var address = _db.Addresses.FirstOrDefault(a => a.UserId == userId && a.AddressType == type);
     if (address == null)
     {
         address = new Address
         {
             AddressType = type,
             AddressId = 0,
             UserId = userId,
         };
     }
     return address;
 }
Example #21
0
		/// <summary>
		/// Converts the address to a string using the specified address type. The address type will become the prefix,
		/// eg using a brefix of AddressType.Billing will generate strings containing BillingSurname, BillingFirstnames etc
		/// </summary>
		/// <param name="type"></param>
		/// <returns></returns>
		public string ToString(AddressType type) {
			string prefix = type.ToString();
			var builder = new StringBuilder();
			builder.Append(BuildPropertyString(prefix, x => x.Surname, Surname));
			builder.Append(BuildPropertyString(prefix, x => x.Firstnames, Firstnames));
			builder.Append(BuildPropertyString(prefix, x => x.Address1, Address1));
			builder.Append(BuildPropertyString(prefix, x => x.Address2, Address2, true));
			builder.Append(BuildPropertyString(prefix, x => x.City, City));
			builder.Append(BuildPropertyString(prefix, x => x.PostCode, PostCode));
			builder.Append(BuildPropertyString(prefix, x => x.Country, Country));
			builder.Append(BuildPropertyString(prefix, x => x.State, State, true));
			builder.Append(BuildPropertyString(prefix, x => x.Phone, Phone, true));

			return builder.ToString();
		}
Example #22
0
 public Address(Guid memberId, AddressType type, Guid addressGuid, string address, string suburbCity, string state, int postcode, string firstName, string lastName, string email, string phoneNumber = null, string companyName = null)
 {
     this.MemberGuid = memberId;
     this.Type = type;
     this.Guid = addressGuid;
     this.Line1 = address;
     this.SuburbCity = suburbCity;
     this.State = state;
     this.Postcode = postcode;
     this.FirstName = firstName;
     this.LastName = lastName;
     this.Email = email;
     this.PhoneNumber = phoneNumber;
     this.CompanyName = companyName;
 }
		AzureServiceBusEndpointAddressImpl([NotNull] Data data,
			AddressType addressType)
		{
			if (data == null)
				throw new ArgumentNullException("data");

			_data = data;

			_tp = TokenProvider.CreateSharedSecretTokenProvider(_data.UsernameIssuer,
			                                                    _data.PasswordSharedSecret);

			var sbUri = ServiceBusEnvironment.CreateServiceUri("sb", _data.Namespace, string.Empty);

			var mfs = new MessagingFactorySettings
				{
					TokenProvider = _tp,
					NetMessagingTransportSettings =
						{
							// todo: configuration setting
							BatchFlushInterval = 50.Milliseconds()
						},
					OperationTimeout = 3.Seconds()
				};
			_mff = () => MessagingFactory.Create(sbUri, mfs);

			_nm = new NamespaceManager(sbUri, _tp);

			string suffix = "";
			if (addressType == AddressType.Queue)
				_queueDescription = new QueueDescriptionImpl(data.QueueOrTopicName);
			else
			{
				_topicDescription = new TopicDescriptionImpl(data.QueueOrTopicName);
				suffix = "?topic=true";
			}

			_rebuiltUri = new Uri(string.Format("azure-sb://{0}:{1}@{2}/{3}{4}", 
				data.UsernameIssuer,
				data.PasswordSharedSecret,
				data.Namespace,
				data.QueueOrTopicName,
				suffix));

			_friendlyUri = new Uri(string.Format("azure-sb://{0}/{1}{2}",
				data.Namespace,
				data.QueueOrTopicName,
				suffix));
		}
        internal static CustomerAddress GetPrimaryCustomerAddress(IQueryable<CustomerAddress> customerAddresses, AddressType addressType)
        {
            if (!customerAddresses.Any())
            {
                return null;
            }

            CustomerAddress customerBillingAddress = customerAddresses.FirstOrDefault(ca => ca.AddressType == addressType && ca.IsPrimary);
            if (customerBillingAddress == null)
            {
                // There is no primary address. Get the most recent address.
                customerBillingAddress = customerAddresses.Where(ca => ca.AddressType == AddressType.Billing).OrderByDescending(ca => ca.LastModified).First();
            }

            return customerBillingAddress;
        }
Example #25
0
 /// <summary>
 /// Maps a <see cref="IAddress"/> to a <see cref="ICustomerAddress"/>
 /// </summary>
 /// <param name="address">
 /// The address.
 /// </param>
 /// <param name="customer">
 /// The customer.
 /// </param>
 /// <param name="addressType">The type of address to be saved</param>
 /// <returns>
 /// The <see cref="ICustomerAddress"/>.
 /// </returns>
 internal static ICustomerAddress ToCustomerAddress(this IAddress address, ICustomer customer, AddressType addressType)
 {
     return new CustomerAddress(customer.Key)
     {
         Address1 = address.Address1,
         Address2 = address.Address2,
         Locality = address.Locality,
         Region = address.Region,
         PostalCode = address.PostalCode,
         CountryCode = address.CountryCode,
         Phone = address.Phone,
         Label = string.IsNullOrEmpty(address.Name) ? "Address" : address.Name,
         Company = address.Organization,
         AddressType = addressType
     };
 }
Example #26
0
 public static string ParseAddressType(AddressType addressType)
 {
     switch (addressType)
     {
         case AddressType.Unknown:
             return "Unknown";
         case AddressType.Personal:
             return "Personal";
         case AddressType.Company:
             return "Company";
         case AddressType.ThirdParty:
             return "Third Party";
         default:
             return string.Empty;
     }
 }
        public void GetGeocodingForAddress1()
        {
            // expectations
            var expectedStatus = ServiceResponseStatus.Ok;
            var expectedResultCount = 1;
            var expectedType = AddressType.StreetAddress;
            var expectedFormattedAddress = "1600 Amphitheatre Parkway, Mountain View, CA 94043, USA";
            var expectedComponentTypes = new AddressType[] {
                AddressType.StreetNumber,
                AddressType.Route,
                AddressType.Locality,
                AddressType.AdministrativeAreaLevel1,
                AddressType.AdministrativeAreaLevel2,
                AddressType.AdministrativeAreaLevel3,
                AddressType.Country,
                AddressType.PostalCode,
                AddressType.Political
            };
            var expectedLocation = new LatLng(37.42219410, -122.08459320);
            var expectedLocationType = LocationType.Rooftop;
            Viewport expectedViewport = new Viewport(
                southWest: new LatLng(37.42084511970850, -122.0859421802915),
                northEast: new LatLng(37.42354308029149, -122.0832442197085)
            );

            // test
            var request = new GeocodingRequest();
            request.Address = "1600 Amphitheatre Parkway Mountain View CA";
            request.Sensor = false;
            var response = new GeocodingService().GetResponse(request);

            // asserts
            Assert.AreEqual(expectedStatus, response.Status, "Status");
            Assert.AreEqual(expectedResultCount, response.Results.Length, "ResultCount");
            Assert.AreEqual(expectedType, response.Results.Single().Types.First(), "Type");
            Assert.AreEqual(expectedFormattedAddress, response.Results.Single().FormattedAddress, "FormattedAddress");
            //Assert.IsTrue(
            //    expectedComponentTypes.OrderBy(x => x).SequenceEqual(
            //        response.Results.Single().AddressComponents.SelectMany(y => y.Types).Distinct().OrderBy(z => z)), "Types");
            //Assert.AreEqual(expectedLatitude, response.Results.Single().Geometry.Location.Latitude, "Latitude");
            Assert.That(expectedLocation, Is.EqualTo(response.Results[0].Geometry.Location).Using(LatLngComparer.Within(0.000001f)), "Longitude");
            Assert.AreEqual(expectedLocationType, response.Results.Single().Geometry.LocationType, "LocationType");
            //Assert.AreEqual(expectedSouthwestLatitude, response.Results.Single().Geometry.Viewport.Southwest.Latitude, "Southwest.Latitude");
            //Assert.AreEqual(expectedSouthwestLongitude, response.Results.Single().Geometry.Viewport.Southwest.Longitude, "Southwest.Longitude");
            //Assert.AreEqual(expectedNortheastLatitude, response.Results.Single().Geometry.Viewport.Northeast.Latitude, "Northeast.Latitude");
            //Assert.AreEqual(expectedNortheastLongitude, response.Results.Single().Geometry.Viewport.Northeast.Longitude, "Northeast.Longitude");
        }
Example #28
0
        public static void DeleteCustomerAddress(int customerID, AddressType type)
        {
            var deleteAddress = false;
            var request = new UpdateCustomerRequest();
            request.CustomerID = customerID;

            // Main address
            if (type == AddressType.Main)
            {
                deleteAddress        = true;
                request.MainAddress1 = string.Empty;
                request.MainAddress2 = string.Empty;
                request.MainCity     = string.Empty;
                request.MainState    = string.Empty;
                request.MainZip      = string.Empty;
                request.MainCountry  = string.Empty;
            }

            // Mailing address
            else if (type == AddressType.Mailing)
            {
                deleteAddress        = true;
                request.MailAddress1 = string.Empty;
                request.MailAddress2 = string.Empty;
                request.MailCity     = string.Empty;
                request.MailState    = string.Empty;
                request.MailZip      = string.Empty;
                request.MailCountry  = string.Empty;
            }

            // Other address
            else if (type == AddressType.Other)
            {
                deleteAddress         = true;
                request.OtherAddress1 = string.Empty;
                request.OtherAddress2 = string.Empty;
                request.OtherCity     = string.Empty;
                request.OtherState    = string.Empty;
                request.OtherZip      = string.Empty;
                request.OtherCountry  = string.Empty;
            }

            if (deleteAddress)
            {
                Exigo.WebService().UpdateCustomer(request);
            }
        }
        public void SetDefault(string userName, string defaultAddressId, AddressType addressType)
        {
            var userAddresses = _addressesDictionary[userName];
            
            //Clear old default addresses
            var oldDefaults = userAddresses.Where(a => a.IsDefault && a.AddressType == addressType);
            foreach (var oldDefault in oldDefaults)
            {
                oldDefault.IsDefault = false;
            }

            var defaultAddress = userAddresses.Find(a => a.Id == defaultAddressId);
            if (defaultAddress != null)
            {
                defaultAddress.IsDefault = true;
            }
        }
        /// <summary>
        /// The create customer address.
        /// </summary>
        /// <param name="customer">
        /// The customer.
        /// </param>
        /// <param name="merchelloContext">
        /// The merchello context.
        /// </param>
        /// <param name="address">
        /// The address.
        /// </param>
        /// <param name="label">
        /// The customer label
        /// </param>
        /// <param name="addressType">
        /// The address type.
        /// </param>
        /// <returns>
        /// The <see cref="ICustomerAddress"/>.
        /// </returns>
        internal static ICustomerAddress CreateCustomerAddress(this ICustomer customer, IMerchelloContext merchelloContext, IAddress address, string label, AddressType addressType)
        {
            var customerAddress = address.ToCustomerAddress(customer, label, addressType);

            return(customer.SaveCustomerAddress(merchelloContext, customerAddress));
        }
Example #31
0
 public ICustomerAddress GetDefaultCustomerAddress(Guid customerKey, AddressType addressType)
 {
     return(_customerAddressService.GetDefaultCustomerAddress(customerKey, addressType));
 }
 /// <summary>
 /// The default customer address associated with a customer of a given type
 /// </summary>
 /// <param name="customer">
 /// The customer.
 /// </param>
 /// <param name="addressType">
 /// The address type.
 /// </param>
 /// <returns>
 /// The collection of <see cref="ICustomerAddress"/>
 /// </returns>
 public static ICustomerAddress DefaultCustomerAddress(this ICustomer customer, AddressType addressType)
 {
     return(customer.DefaultCustomerAddress(MerchelloContext.Current, addressType));
 }
 /// <summary>
 /// Creates a <see cref="ICustomerAddress"/> based off an <see cref="IAddress"/>
 /// </summary>
 /// <param name="customer">
 /// The customer associated with the address
 /// </param>
 /// <param name="address">
 /// The address.
 /// </param>
 /// <param name="label">
 /// The address label
 /// </param>
 /// <param name="addressType">
 /// The <see cref="AddressType"/>
 /// </param>
 /// <returns>
 /// The <see cref="ICustomerAddress"/>.
 /// </returns>
 public static ICustomerAddress CreateCustomerAddress(this ICustomer customer, IAddress address, string label, AddressType addressType)
 {
     return(customer.CreateCustomerAddress(MerchelloContext.Current, address, label, addressType));
 }
        private static byte[] GetRealAddress(string Address, AddressType type, out bool IsExAddr)
        {
            string result = Regex.Replace(Address, @"[^0-9]+", "");

            ushort offset    = Convert.ToUInt16(result);
            ushort StartAddr = 0x00;

            #region Bit

            if (Address.StartsWith("k"))
            {
                StartAddr = 0x0020;
            }
            else if (Address.StartsWith("v"))
            {
                StartAddr = 0x0050;
            }
            else if (Address.StartsWith("t") || Address.StartsWith("c"))
            {
                StartAddr = 0x0060;
            }
            else if (Address.StartsWith("l"))
            {
                StartAddr = 0x0080;
            }
            else if (Address.StartsWith("x") || Address.StartsWith("y"))
            {
                StartAddr = 0x0100;
            }
            else if (Address.StartsWith("m"))
            {
                StartAddr = 0x0180;
            }
            #endregion
            #region Char

            else if (Address.StartsWith("s"))
            {
                StartAddr = 0x0200;
            }
            else if (Address.StartsWith("n"))
            {
                StartAddr = 0x0600;
            }
            else if (Address.StartsWith("r"))
            {
                StartAddr = 0x0800;
            }
            else if (Address.StartsWith("d"))
            {
                StartAddr = 0x1000;
            }
            else if (Address.StartsWith("b"))
            {
                StartAddr = 0x6000;
            }

            #endregion
            #region Ex Bit

            else if (Address.StartsWith("ek"))
            {
                StartAddr = 0x0100;
            }
            else if (Address.StartsWith("ev"))
            {
                StartAddr = 0x0200;
            }
            else if (Address.StartsWith("et") || Address.StartsWith("ec"))
            {
                StartAddr = 0x0300;
            }
            else if (Address.StartsWith("el"))
            {
                StartAddr = 0x0380;
            }
            else if (Address.StartsWith("ex") || Address.StartsWith("ey"))
            {
                StartAddr = 0x0580;
            }
            else if (Address.StartsWith("em"))
            {
                StartAddr = 0x0600;
            }
            #endregion
            #region Ex Char
            else if (Address.StartsWith("es"))
            {
                StartAddr = 0x0800;
            }
            else if (Address.StartsWith("en"))
            {
                StartAddr = 0x1000;
            }
            else if (Address.StartsWith("h"))
            {
                StartAddr = 0x1800;
            }
            else if (Address.StartsWith("u"))
            {
                StartAddr = 0x0000;
            }
            #endregion

            switch (Address[0])
            {
            case 'e':
            case 'h':
            case 'u':
                IsExAddr = true;
                break;

            default:
                IsExAddr = false;
                break;
            }

            switch (type)
            {
            case AddressType.Char:
                return(BitConverter.GetBytes((ushort)(StartAddr + offset)));

            case AddressType.Byte:
                return(BitConverter.GetBytes((ushort)(StartAddr + offset * 2)));

            case AddressType.Bit:
                return(BitConverter.GetBytes((ushort)(StartAddr + offset * 16)));

            default:
                return(null);
            }
        }
Example #35
0
        private Socket Connect(Socket socket, NetworkCredential credential, Encoding credentialEncoding, AddressType addressType, IEnumerable <byte> addressBytes, int port)
        {
            byte[] responseBuffer = Handshake(socket, credential, credentialEncoding);

            byte[] requestBuffer = Enumerable.Empty <byte>()
                                   .Concat(new[] { SocksVersion, (byte)CommandType.Connect, (byte)0x00, (byte)addressType })
                                   .Concat(addressBytes)
                                   .Concat(BitConverter.GetBytes(IPAddress.HostToNetworkOrder((short)port)))
                                   .ToArray();
            socket.Send(requestBuffer);

            int read = socket.Receive(responseBuffer);

            if (read < 7)
            {
                socket.Close();
                string message = string.Format(
                    "The SOCKS5 proxy responded with {0} bytes to the connect request. At least 7 bytes are expected.",
                    read);
                throw new Exception(message);
            }

            ValidateSocksVersion(socket, responseBuffer[0]);

            if (responseBuffer[1] != (byte)ReplyType.Succeeded)
            {
                socket.Close();
                string message = string.Format(
                    "The SOCKS5 proxy responded with a unsuccessful reply type '{0}' (0x{1:x2}).",
                    responseBuffer[1] >= (byte)ReplyType.Unassigned ? ReplyType.Unassigned : (ReplyType)responseBuffer[1],
                    responseBuffer[1]);
                throw new Exception(message);
            }

            if (responseBuffer[2] != 0x00)
            {
                socket.Close();
                string message = string.Format(
                    "The SOCKS5 proxy responded with an unexpected reserved field value 0x{0:x2}. 0x00 was expected.",
                    responseBuffer[2]);
                throw new Exception(message);
            }

            if (!Enum.GetValues(typeof(AddressType)).Cast <byte>().Contains(responseBuffer[3]))
            {
                socket.Close();
                string message = string.Format(
                    "The SOCKS5 proxy responded with an unexpected address type 0x{0:x2}.",
                    responseBuffer[3]);
                throw new Exception(message);
            }

            object bindAddress;
            object bindPort;
            var    bindAddressType = (AddressType)responseBuffer[3];

            switch (bindAddressType)
            {
            case AddressType.IpV4:
                if (read != 10)
                {
                    socket.Close();
                    string message = string.Format(
                        "The SOCKS5 proxy responded with an unexpected number of bytes ({0} bytes) when the address is an IPv4 address. 10 bytes were expected.",
                        read);
                    throw new Exception(message);
                }
                bindAddress = new IPAddress(responseBuffer.Skip(4).Take(4).ToArray());
                bindPort    = IPAddress.NetworkToHostOrder(BitConverter.ToInt16(responseBuffer, 8));
                break;

            case AddressType.DomainName:
                byte bindAddressLength = responseBuffer[4];
                bindAddress = Encoding.ASCII.GetString(responseBuffer, 5, bindAddressLength);
                bindPort    = IPAddress.NetworkToHostOrder(BitConverter.ToInt16(responseBuffer, 5 + bindAddressLength));
                break;

            case AddressType.IpV6:
                if (read != 22)
                {
                    socket.Close();
                    string message = string.Format(
                        "The SOCKS5 proxy responded with an unexpected number of bytes ({0} bytes) when the address is an IPv6 address. 22 bytes were expected.",
                        read);
                    throw new Exception(message);
                }
                bindAddress = new IPAddress(responseBuffer.Skip(4).Take(16).ToArray());
                bindPort    = IPAddress.NetworkToHostOrder(BitConverter.ToInt16(responseBuffer, 20));
                break;

            default:
                socket.Close();
                string addressTypeNotImplementedMessage = string.Format(
                    "The provided address type '{0}' is not yet implemented.",
                    bindAddressType);
                throw new NotImplementedException(addressTypeNotImplementedMessage);
            }

            return(socket);
        }
        private void CreateAccount(HttpContext context)
        {
            // #CreateAccount API
            // The CreateAccount API operation enables you to create a PayPal account on behalf of a third party.
            NameValueCollection parameters = context.Request.Params;

            // The name of the person for whom the PayPal account is
            // created, which
            // contains
            //
            // * `FirstName` - First name of the account or payment card
            // holder.
            // * `LastName` - Last name of the account or payment card
            // holder.
            NameType name = new NameType(parameters["firstName"], parameters["lastName"]);

            //(Optional) A salutation for the account or payment card holder.
            if (parameters["salutation"] != string.Empty)
            {
                name.salutation = parameters["salutation"];
            }

            //Optional) Middle name of the account or payment card holder.
            if (parameters["middleName"] != string.Empty)
            {
                name.middleName = parameters["middleName"];
            }

            //(Optional) A suffix for the account or payment card holder.
            if (parameters["suffix"] != string.Empty)
            {
                name.suffix = parameters["suffix"];
            }

            // Address of the person for whom the PayPal account is created
            AddressType address = new AddressType(parameters["line1"], parameters["countryCode"]);

            //(Optional) Second line of the address.
            // Note: This field is required for Brazilian addresses.
            if (parameters["line2"] != string.Empty)
            {
                address.line2 = parameters["line2"];
            }

            //(Required) City name
            if (parameters["city"] != string.Empty)
            {
                address.city = parameters["city"];
            }

            //(Optional) State code.
            if (parameters["state"] != string.Empty)
            {
                address.state = parameters["state"];
            }

            //(Optional) Zip or postal code.
            if (parameters["postalCode"] != string.Empty)
            {
                address.postalCode = parameters["postalCode"];
            }

            // Instantiating createAccountRequest with mandatory arguments:
            //
            // * `requestenvelope` - Information common to each API
            // operation, such
            // as the language in which an error message is returned.
            // * `name` - The name of the person for whom the PayPal account
            // is
            // created.
            // * `address` - The address to be associated with the PayPal
            // account.
            // * `preferredlanguagecode`- The code indicating the language
            // to be
            // associated with the account.
            // What value is allowed depends on the country code passed in
            // the
            // countryCode parameter for the address.
            // For Example: United States (US) - en_US
            CreateAccountRequest req = new CreateAccountRequest(new RequestEnvelope(), name, address,
                                                                parameters["preferredLanguageCode"]);

            // The type of account to create. Allowed values:
            //
            // *Personal – Personal account
            // *Premier – Premier account
            // *Business – Business account
            if (parameters["accountType"] != string.Empty)
            {
                req.accountType = parameters["accountType"];
            }
            // Phone Number to be associated with the account.
            if (parameters["contactPhoneNumber"] != string.Empty)
            {
                req.contactPhoneNumber = parameters["contactPhoneNumber"];
            }
            if (parameters["homePhoneNumber"] != string.Empty)
            {
                req.homePhoneNumber = parameters["homePhoneNumber"];
            }
            if (parameters["mobilePhoneNumber"] != string.Empty)
            {
                req.mobilePhoneNumber = parameters["mobilePhoneNumber"];
            }

            // Email address of person for whom the PayPal account is
            // created.
            if (parameters["emailAddress"] != string.Empty)
            {
                req.emailAddress = parameters["emailAddress"];
            }

            // The three letter code for the currency to be associated with
            // the account
            if (parameters["currencyCode"] != string.Empty)
            {
                req.currencyCode = parameters["currencyCode"];
            }

            // The code of the country to be associated with the account.
            req.citizenshipCountryCode = parameters["citizenshipCountryCode"];

            // This attribute determines whether a key or a URL is returned
            // for the redirect URL. Allowable value(s) currently
            // supported:`Web` - Returns a URL
            req.registrationType = parameters["registrationType"];

            // The URL to post instant payment notification (IPN) messages
            // to
            // regarding account creation. This URL supersedes the IPN
            // notification
            // URL set in the merchant profile.
            if (parameters["notificationUrl"] != string.Empty)
            {
                req.notificationURL = parameters["notificationUrl"];
            }

            if (parameters["returnUrl"] != string.Empty || parameters["returnUrlDescription"] != string.Empty ||
                parameters["showAddCreditCard"] != string.Empty || parameters["showMobileConfirm"] != string.Empty ||
                parameters["useMiniBrowser"] != string.Empty)
            {
                // Used for configuration settings for the web flow
                CreateAccountWebOptionsType webOptions = new CreateAccountWebOptionsType();
                req.createAccountWebOptions = webOptions;

                // (Required) The URL to which you want the account holder to return when he or she finishes account registration.
                // This URL appears as a link on the final page of the PayPal account registration flow.
                // The text of this link is the text passed in the returnUrlDescription request parameter (below).
                if (parameters["returnUrl"] != string.Empty)
                {
                    webOptions.returnUrl = parameters["returnUrl"];
                }
                //(Optional) A description of the return URL.
                if (parameters["returnUrlDescription"] != string.Empty)
                {
                    webOptions.returnUrlDescription = parameters["returnUrlDescription"];
                }
                // (Optional) Defines whether the "add credit card" option is included in the PayPal account registration flow.
                //    true - Show the option (default)
                //    false - Do not show the option
                if (parameters["showAddCreditCard"] != string.Empty)
                {
                    webOptions.showAddCreditCard = Convert.ToBoolean(parameters["showAddCreditCard"]);
                }

                // (Optional) Defines whether the "mobile confirmation" option is included in the PayPal account registration flow.
                //	    true - Show the option
                //	    false - Do not show the option (default)
                if (parameters["showMobileConfirm"] != string.Empty)
                {
                    webOptions.showMobileConfirm = Convert.ToBoolean(parameters["showMobileConfirm"]);
                }

                // (Optional) Defines whether to use the minibrowser account registration flow or the traditional account registration flow.
                //    true - Use the minibrowser flow
                //    false - Use the traditional flow (default)
                if (parameters["useMiniBrowser"] != string.Empty)
                {
                    webOptions.useMiniBrowser = Convert.ToBoolean(parameters["useMiniBrowser"]);
                }
            }


            // Create the AdaptiveAccounts service object to make the API call
            AdaptiveAccountsService service = null;
            CreateAccountResponse   resp    = null;

            try
            {
                // Configuration map containing signature credentials and other required configuration.
                // For a full list of configuration parameters refer in wiki page
                // (https://github.com/paypal/sdk-core-dotnet/wiki/SDK-Configuration-Parameters)
                Dictionary <string, string> configurationMap = Configuration.GetAcctAndConfig();

                // Creating service wrapper object to make an API call and loading
                // configuration map for your credentials and endpoint
                service = new AdaptiveAccountsService(configurationMap);

                // # API call
                // Invoke the CreateAccount method in service wrapper object
                resp = service.CreateAccount(req);
            }
            catch (System.Exception e)
            {
                context.Response.Write(e.Message);
                return;
            }

            // Display response values.
            Dictionary <string, string> keyResponseParams = new Dictionary <string, string>();
            string redirectUrl = null;

            if (!(resp.responseEnvelope.ack == AckCode.FAILURE) &&
                !(resp.responseEnvelope.ack == AckCode.FAILUREWITHWARNING))
            {
                redirectUrl = resp.redirectURL;
                keyResponseParams.Add("Account Id", resp.accountId);
                keyResponseParams.Add("Create account key", resp.createAccountKey);
                keyResponseParams.Add("Execution status", resp.execStatus.ToString());

                //Selenium Test Case
                keyResponseParams.Add("Acknowledgement", resp.responseEnvelope.ack.ToString());
                keyResponseParams.Add("Redirect To PayPal", resp.redirectURL);
            }
            displayResponse(context, "CreateAccount", keyResponseParams, service.getLastRequest(), service.getLastResponse(),
                            resp.error, redirectUrl);
        }
 /// <summary>
 /// The addresses.
 /// </summary>
 /// <param name="customer">
 /// The customer.
 /// </param>
 /// <param name="merchelloContext">
 /// The merchello Context.
 /// </param>
 /// <param name="addressType">
 /// The address Type.
 /// </param>
 /// <returns>
 /// The collection of <see cref="ICustomerAddress"/> associated with the customer of a given type
 /// </returns>
 internal static IEnumerable <ICustomerAddress> CustomerAddresses(this ICustomer customer, IMerchelloContext merchelloContext, AddressType addressType)
 {
     return(((ServiceContext)merchelloContext.Services).CustomerAddressService.GetByCustomerKey(customer.Key, addressType));
 }
Example #38
0
 public AddressRange(AddressType desc, uint low, uint high)
     : this(desc, (Byte)(low >> 24), low, high)
 {
 }
 /// <summary>
 /// Adds an <see cref="IAddress"/> to extended data.  This is intended for shipment addresses
 /// </summary>
 /// <param name="extendedData">
 /// The extended Data.
 /// </param>
 /// <param name="address">
 /// The address.
 /// </param>
 /// <param name="addressType">
 /// The Origin or Destination addresses
 /// </param>
 public static void AddAddress(this ExtendedDataCollection extendedData, IAddress address, AddressType addressType)
 {
     extendedData.AddAddress(address, addressType == AddressType.Shipping
                     ? Constants.ExtendedDataKeys.ShippingDestinationAddress : Constants.ExtendedDataKeys.BillingAddress);
 }
 public Address ToAddress(AddressType type) => Address.From(Host.Of(_host), _port, type);
Example #41
0
        public ServiceBusEndpointAddress(Uri hostAddress, string name, TimeSpan?autoDelete = default, AddressType type = AddressType.Queue)
        {
            ParseLeft(hostAddress, out Scheme, out Host, out Scope);

            Name = name;

            AutoDelete = autoDelete;
            Type       = type;
        }
 public GeocoderMetaDataType()
 {
     Address = new AddressType();
 }
Example #43
0
 /// <summary>
 ///     Creates this object and sets all it's needed properties
 /// </summary>
 /// <param name="email">The full E-mail address</param>
 /// <param name="displayName">The displayname for the <paramref name="email" /></param>
 /// <param name="addressType">The <see cref="Address.AddressType" /></param>
 public ReceivingRepresenting(string email, string displayName, AddressType addressType = AddressType.Smtp)
     : base(email, displayName, addressType)
 {
 }
 /// <summary>
 /// The default customer address.
 /// </summary>
 /// <param name="customer">
 /// The customer.
 /// </param>
 /// <param name="merchelloContext">
 /// The merchello context.
 /// </param>
 /// <param name="addressType">
 /// The address type.
 /// </param>
 /// <returns>
 /// The default <see cref="ICustomerAddress"/> of a given type
 /// </returns>
 internal static ICustomerAddress DefaultCustomerAddress(this ICustomer customer, IMerchelloContext merchelloContext, AddressType addressType)
 {
     return(((ServiceContext)merchelloContext.Services).CustomerAddressService.GetDefaultCustomerAddress(customer.Key, addressType));
 }
Example #45
0
        private Contact(string name, string zipCode, string city, string country, string streetOrAddressline1, string houseNumberOrAddressline2, AddressType addressType)
        {
            twoLetterCodes = ValidTwoLetterCodes();
            MyRes res      = new MyRes("Messages,Swiss");
            MyRes resForms = new MyRes("Forms,BarcodeEditor,Swiss");
            //Pattern extracted from https://qr-validation.iso-payments.ch as explained in https://github.com/codebude/QRCoder/issues/97
            string charsetPattern = @"^([a-zA-Z0-9\.,;:'\ \+\-/\(\)?\*\[\]\{\}\\`´~ ]|[!""#%&<>÷=@_$£]|[àáâäçèéêëìíîïñòóôöùúûüýßÀÁÂÄÇÈÉÊËÌÍÎÏÒÓÔÖÙÚÛÜÑ])*$";

            this.adrType = addressType;

            if (string.IsNullOrEmpty(name))
            {
                throw new SwissQrCodeContactException(String.Format(res.Get("SwissEmptyProperty"), resForms.Get("Name")));
            }
            if (name.Length > 70)
            {
                throw new SwissQrCodeContactException(String.Format(res.Get("SwissLengthMore"), resForms.Get("Name"), 71));
            }
            if (!Regex.IsMatch(name, charsetPattern))
            {
                throw new SwissQrCodeContactException(String.Format(res.Get("SwissPatternError"), resForms.Get("Name")) + charsetPattern);
            }
            this.name = name;

            if (AddressType.StructuredAddress == this.adrType)
            {
                if (!string.IsNullOrEmpty(streetOrAddressline1) && (streetOrAddressline1.Length > 70))
                {
                    throw new SwissQrCodeContactException(String.Format(res.Get("SwissLengthMore"), resForms.Get("Street"), 71));
                }
                if (!string.IsNullOrEmpty(streetOrAddressline1) && !Regex.IsMatch(streetOrAddressline1, charsetPattern))
                {
                    throw new SwissQrCodeContactException(String.Format(res.Get("SwissPatternError"), resForms.Get("Street")) + charsetPattern);
                }
                this.streetOrAddressline1 = streetOrAddressline1;

                if (!string.IsNullOrEmpty(houseNumberOrAddressline2) && houseNumberOrAddressline2.Length > 16)
                {
                    throw new SwissQrCodeContactException(String.Format(res.Get("SwissLengthMore"), resForms.Get("HouseNumber"), 71));
                }
                this.houseNumberOrAddressline2 = houseNumberOrAddressline2;
            }
            else
            {
                if (!string.IsNullOrEmpty(streetOrAddressline1) && (streetOrAddressline1.Length > 70))
                {
                    throw new SwissQrCodeContactException(String.Format(res.Get("SwissLengthMore"), "Address line 1", 71));
                }
                if (!string.IsNullOrEmpty(streetOrAddressline1) && !Regex.IsMatch(streetOrAddressline1, charsetPattern))
                {
                    throw new SwissQrCodeContactException(String.Format(res.Get("SwissPatternError"), "Address line 1") + charsetPattern);
                }
                this.streetOrAddressline1 = streetOrAddressline1;

                if (string.IsNullOrEmpty(houseNumberOrAddressline2))
                {
                    throw new SwissQrCodeContactException(res.Get("SwissAddressLine2Error"));
                }
                if (!string.IsNullOrEmpty(houseNumberOrAddressline2) && (houseNumberOrAddressline2.Length > 70))
                {
                    throw new SwissQrCodeContactException(String.Format(res.Get("SwissLengthMore"), "Address line 2", 71));
                }
                if (!string.IsNullOrEmpty(houseNumberOrAddressline2) && !Regex.IsMatch(houseNumberOrAddressline2, charsetPattern))
                {
                    throw new SwissQrCodeContactException(String.Format(res.Get("SwissPatternError"), "Address line 2") + charsetPattern);
                }
                this.houseNumberOrAddressline2 = houseNumberOrAddressline2;
            }

            if (AddressType.StructuredAddress == this.adrType)
            {
                if (string.IsNullOrEmpty(zipCode))
                {
                    throw new SwissQrCodeContactException(String.Format(res.Get("SwissEmptyProperty"), resForms.Get("ZipCode")));
                }
                if (zipCode.Length > 16)
                {
                    throw new SwissQrCodeContactException(String.Format(res.Get("SwissLengthMore"), resForms.Get("ZipCode"), 17));
                }
                if (!Regex.IsMatch(zipCode, charsetPattern))
                {
                    throw new SwissQrCodeContactException(String.Format(res.Get("SwissPatternError"), resForms.Get("ZipCode")) + charsetPattern);
                }
                this.zipCode = zipCode;

                if (string.IsNullOrEmpty(city))
                {
                    throw new SwissQrCodeContactException(String.Format(res.Get("SwissEmptyProperty"), resForms.Get("City")));
                }
                if (city.Length > 35)
                {
                    throw new SwissQrCodeContactException(String.Format(res.Get("SwissLengthMore"), resForms.Get("City"), 36));
                }
                if (!Regex.IsMatch(city, charsetPattern))
                {
                    throw new SwissQrCodeContactException(String.Format(res.Get("SwissPatternError"), resForms.Get("City")) + charsetPattern);
                }
                this.city = city;
            }
            else
            {
                this.zipCode = this.city = string.Empty;
            }

            if (!IsValidTwoLetterCode(country))
            {
                throw new SwissQrCodeContactException(res.Get("SwissCountryTwoLetters"));
            }

            this.country = country;
        }
Example #46
0
 public IEnumerable <ICustomerAddress> GetByCustomerKey(Guid customerKey, AddressType addressType)
 {
     return(_customerAddressService.GetByCustomerKey(customerKey, addressType));
 }
Example #47
0
        /// <summary>
        ///     Creates this object and sets all it's properties
        /// </summary>
        /// <param name="binaryReader">The <see cref="BinaryReader" /></param>
        /// <param name="addressType">The <see cref="AddressType" /></param>
        /// <param name="supportsRtf">
        ///     Set to <c>true</c> when the recipient in the <see cref="RecipientRow" />
        ///     supports RTF
        /// </param>
        /// <param name="displayNameIncluded">If this flag is b'1', the DisplayName (section 2.8.3.2) field is included</param>
        /// <param name="emailAddressIncluded">If this flag is b'1', the EmailAddress (section 2.8.3.2) field is included.</param>
        /// <param name="addressTypeIncluded">
        ///     If this flag is b'1', this recipient (1) has a non-standard address type and the
        ///     AddressType field is included.
        /// </param>
        /// <param name="simpleDisplayNameIncluded">If this flag is b'1', the SimpleDisplayName field is included.</param>
        /// <param name="transmittableDisplayNameSameAsDisplayName">
        ///     If this flag is b'1', the value of the TransmittableDisplayName
        ///     field is the same as the value of the DisplayName field.
        /// </param>
        /// <param name="transmittableDisplayNameIncluded">
        ///     If this flag is b'1', the TransmittableDisplayName (section 2.8.3.2)
        ///     field is included.
        /// </param>
        /// <param name="stringsInUnicode">
        ///     If this flag is b'1', the associated string properties are in Unicode with a 2-
        ///     byte terminating null character; if this flag is b'0', string properties are MBCS with a single
        ///     terminating null character, in the code page sent to the server in the EcDoConnectEx method,
        ///     as specified in [MS-OXCRPC] section 3.1.4.1, or the Connect request type 6, as specified in
        ///     [MS-OXCMAPIHTTP] section 2.2.4.1.
        /// </param>
        internal RecipientRow(BinaryReader binaryReader,
                              AddressType addressType,
                              bool supportsRtf,
                              bool displayNameIncluded,
                              bool emailAddressIncluded,
                              bool addressTypeIncluded,
                              bool simpleDisplayNameIncluded,
                              bool transmittableDisplayNameSameAsDisplayName,
                              bool transmittableDisplayNameIncluded,
                              bool stringsInUnicode)
        {
            AddressType = addressType;
            SupportsRtf = supportsRtf;

            switch (AddressType)
            {
            case AddressType.X500Dn:
                AddressPrefixUsed = binaryReader.ReadByte();
                DisplayType       = (DisplayType)binaryReader.ReadByte();
                X500Dn            = Strings.ReadNullTerminatedAsciiString(binaryReader);
                break;

            case AddressType.PersonalDistributionList1:
            case AddressType.PersonalDistributionList2:
                EntryIdSize   = binaryReader.ReadUInt16();
                EntryId       = new AddressBookEntryId(binaryReader);
                SearchKeySize = binaryReader.ReadUInt16();
                if (SearchKeySize > 0)
                {
                    SearchKey = binaryReader.ReadBytes((int)SearchKeySize);
                }
                break;

            case AddressType.NoType:
                if (addressTypeIncluded)
                {
                    AddresType = Strings.ReadNullTerminatedAsciiString(binaryReader);
                }
                break;
            }

            // MUST be specified in Unicode characters if the U flag of the RecipientsFlags field is set
            if (emailAddressIncluded)
            {
                EmailAddress = Strings.ReadNullTerminatedString(binaryReader, stringsInUnicode);
            }
            if (displayNameIncluded)
            {
                DisplayName = Strings.ReadNullTerminatedString(binaryReader, stringsInUnicode);
            }
            if (simpleDisplayNameIncluded)
            {
                SimpleDisplayName = Strings.ReadNullTerminatedString(binaryReader, stringsInUnicode);
            }
            if (transmittableDisplayNameSameAsDisplayName)
            {
                TransmittableDisplayName = DisplayName;
            }
            else if (transmittableDisplayNameIncluded)
            {
                TransmittableDisplayName = Strings.ReadNullTerminatedString(binaryReader, stringsInUnicode);
            }

            // This value specifies the number of columns from the RecipientColumns field that are included in
            // the RecipientProperties field.
            var columns = binaryReader.ReadInt16();

            // Skip the next 6 bytes
            binaryReader.ReadBytes(6);

            RecipientProperties = new List <Property>();
            for (var column = 0; column < columns; column++)
            {
                var    type = (PropertyType)binaryReader.ReadUInt16();
                var    id   = binaryReader.ReadUInt16();
                byte[] data;

                switch (type)
                {
                case PropertyType.PT_NULL:
                {
                    data = new byte[0];
                    RecipientProperties.Add(new Property(id, type, data));
                    break;
                }

                case PropertyType.PT_BOOLEAN:
                {
                    data = binaryReader.ReadBytes(1);
                    binaryReader.ReadByte();
                    RecipientProperties.Add(new Property(id, type, data));
                    break;
                }

                case PropertyType.PT_SHORT:
                {
                    data = binaryReader.ReadBytes(2);
                    RecipientProperties.Add(new Property(id, type, data));
                    break;
                }

                case PropertyType.PT_LONG:
                case PropertyType.PT_FLOAT:
                case PropertyType.PT_ERROR:
                {
                    data = binaryReader.ReadBytes(4);
                    RecipientProperties.Add(new Property(id, type, data));
                    break;
                }

                case PropertyType.PT_DOUBLE:
                case PropertyType.PT_APPTIME:
                case PropertyType.PT_I8:
                case PropertyType.PT_SYSTIME:
                {
                    data = binaryReader.ReadBytes(8);
                    RecipientProperties.Add(new Property(id, type, data));
                    break;
                }

                case PropertyType.PT_CLSID:
                {
                    data = binaryReader.ReadBytes(16);
                    RecipientProperties.Add(new Property(id, type, data));
                    break;
                }

                case PropertyType.PT_OBJECT:
                    throw new NotSupportedException("The PT_OBJECT type is not supported");

                case PropertyType.PT_STRING8:
                case PropertyType.PT_UNICODE:
                case PropertyType.PT_BINARY:
                {
                    var length = binaryReader.ReadInt16();
                    data = binaryReader.ReadBytes(length);
                    RecipientProperties.Add(new Property(id, type, data));
                    break;
                }

                case PropertyType.PT_MV_SHORT:
                {
                    var count = binaryReader.ReadInt16();
                    for (var j = 0; j < count; j++)
                    {
                        data = binaryReader.ReadBytes(2);
                        RecipientProperties.Add(new Property(id, type, data, true));
                    }
                    break;
                }

                case PropertyType.PT_MV_LONG:
                case PropertyType.PT_MV_FLOAT:
                {
                    var count = binaryReader.ReadInt16();
                    for (var j = 0; j < count; j++)
                    {
                        data = binaryReader.ReadBytes(4);
                        RecipientProperties.Add(new Property(id, type, data, true));
                    }
                    break;
                }

                case PropertyType.PT_MV_DOUBLE:
                case PropertyType.PT_MV_APPTIME:
                case PropertyType.PT_MV_LONGLONG:
                case PropertyType.PT_MV_SYSTIME:
                {
                    var count = binaryReader.ReadInt16();
                    for (var j = 0; j < count; j++)
                    {
                        data = binaryReader.ReadBytes(8);
                        RecipientProperties.Add(new Property(id, type, data, true));
                    }
                    break;
                }

                case PropertyType.PT_MV_TSTRING:
                case PropertyType.PT_MV_STRING8:
                case PropertyType.PT_MV_BINARY:
                {
                    var count = binaryReader.ReadInt16();
                    for (var j = 0; j < count; j++)
                    {
                        var length = binaryReader.ReadInt16();
                        data = binaryReader.ReadBytes(length);
                        RecipientProperties.Add(new Property(id, type, data, true));
                    }
                    break;
                }

                case PropertyType.PT_MV_CLSID:
                {
                    var count = binaryReader.ReadInt16();
                    for (var j = 0; j < count; j++)
                    {
                        data = binaryReader.ReadBytes(16);
                        RecipientProperties.Add(new Property(id, type, data));
                    }
                    break;
                }

                default:
                    throw new ArgumentOutOfRangeException();
                }
            }

            if (string.IsNullOrWhiteSpace(EmailAddress))
            {
                var addressTypeProperty  = RecipientProperties.Find(m => m.ShortName == MapiTags.PR_ADDRTYPE);
                var emailAddressProperty = RecipientProperties.Find(m => m.ShortName == MapiTags.PR_EMAIL_ADDRESS);
                var smtpAddressProperty  = RecipientProperties.Find(m => m.ShortName == MapiTags.PR_SMTP_ADDRESS);

                if (addressTypeProperty != null &&
                    addressTypeProperty.ToString == "EX" &&
                    smtpAddressProperty != null)
                {
                    EmailAddress = Helpers.EmailAddress.RemoveSingleQuotes(smtpAddressProperty.ToString);
                }
                else if (emailAddressProperty != null)
                {
                    EmailAddress = Helpers.EmailAddress.RemoveSingleQuotes(emailAddressProperty.ToString);
                }
            }

            if (string.IsNullOrWhiteSpace(DisplayName))
            {
                var value = RecipientProperties.Find(m => m.ShortName == MapiTags.PR_DISPLAY_NAME);
                if (value != null)
                {
                    DisplayName = value.ToString;
                }
            }

            if (string.IsNullOrWhiteSpace(SimpleDisplayName))
            {
                var value = RecipientProperties.Find(m => m.ShortName == MapiTags.PR_7BIT_DISPLAY_NAME);
                if (value != null)
                {
                    SimpleDisplayName = value.ToString;
                }
            }

            if (string.IsNullOrWhiteSpace(TransmittableDisplayName))
            {
                var value = RecipientProperties.Find(m => m.ShortName == MapiTags.PR_TRANSMITABLE_DISPLAY_NAME);
                if (value != null)
                {
                    TransmittableDisplayName = value.ToString;
                }
            }

            if (transmittableDisplayNameSameAsDisplayName)
            {
                TransmittableDisplayName = DisplayName;
            }

            var recipientTypeProperty = RecipientProperties.Find(m => m.ShortName == MapiTags.PR_RECIPIENT_TYPE);

            if (recipientTypeProperty != null)
            {
                RecipientType = (RecipientType)recipientTypeProperty.ToInt;
            }

            var displayTypeProperty = RecipientProperties.Find(m => m.ShortName == MapiTags.PR_DISPLAY_TYPE);

            if (displayTypeProperty != null)
            {
                DisplayType = (DisplayType)displayTypeProperty.ToInt;
            }
        }
        /// <summary>
        /// Handle AddPaymentCard API call
        /// </summary>
        /// <param name="context"></param>
        private void AddPaymentCard(HttpContext context)
        {
            // #AddPaymentCard API
            // The AddPaymentCard API operation lets your application set up payment cards as funding sources for PayPal accounts.
            NameValueCollection parameters = context.Request.Params;

            // (Required) Name (as it appears on the card) of the payment card holder.
            // (Required) First name of the account or payment card holder. (Required) Last name of the account or payment card holder.
            NameType nameOnCard = new NameType(parameters["firstName"], parameters["lastName"]);

            // (Optional) A salutation for the account or payment card holder.
            if (parameters["salutation"] != string.Empty)
            {
                nameOnCard.salutation = parameters["salutation"];
            }

            //(Optional) Middle name of the account or payment card holder.
            if (parameters["middleName"] != string.Empty)
            {
                nameOnCard.middleName = parameters["middleName"];
            }

            // (Optional) A suffix for the account or payment card holder.
            if (parameters["suffix"] != string.Empty)
            {
                nameOnCard.suffix = parameters["suffix"];
            }

            // (Optional) Billing address of the payment card holder. See
            // AddressType Fields for details.
            AddressType billingAddress = new AddressType(parameters["line1"], parameters["countryCode"]);

            // (Optional) The second line of the address. Note: This field
            // is required for Brazilian addresses.
            if (parameters["line2"] != string.Empty)
            {
                billingAddress.line2 = parameters["line2"];
            }

            // (Required) The city.
            if (parameters["city"] != string.Empty)
            {
                billingAddress.city = parameters["city"];
            }

            // (Optional) The state code.
            if (parameters["state"] != string.Empty)
            {
                billingAddress.state = parameters["state"];
            }

            // (Optional) The zip or postal code.
            if (parameters["postalCode"] != string.Empty)
            {
                billingAddress.postalCode = parameters["postalCode"];
            }

            // (Required) The type of payment card to add.
            CardTypeType cardType =
                (CardTypeType)Enum.Parse(typeof(CardTypeType), parameters["cardType"]);
            ConfirmationType confirmationType =
                (ConfirmationType)Enum.Parse(typeof(ConfirmationType), parameters["confirmationType"]);

            // (Required) The payment card number.
            AddPaymentCardRequest req = new AddPaymentCardRequest(new RequestEnvelope(), nameOnCard, billingAddress,
                                                                  parameters["cardNumber"], cardType, confirmationType);

            // Optional) Unique identification number of the PayPal account
            // to which to add the payment card. You must pass either an
            // accountId or an emailAddress in this request. You can't leave
            // both fields out of the message.
            if (parameters["accountId"] != string.Empty)
            {
                req.accountId = parameters["accountId"];
            }

            // (Optional) Email address that uniquely identifies the PayPal
            // account to which to add the payment card.
            if (parameters["emailAddress"] != string.Empty)
            {
                req.emailAddress = parameters["emailAddress"];
            }

            // (Required if confirmationType is NONE) Unique identifier of
            //  the account to which to add a payment card. Use in cases
            //  where the payment card is being added without the account
            //  holder's explicit confirmation. The value to pass is returned
            //  in the createAccountKey field of a CreateAccount response. A
            //  create account key response expires after 60 minutes. If you
            //  pass an expired key to an Adaptive Accounts API, an error is
            //  returned
            if (parameters["createAccountKey"] != string.Empty)
            {
                req.createAccountKey = parameters["createAccountKey"];
            }

            // (Optional) Date of birth of the payment card holder.
            if (parameters["cardOwnerDateOfBirth"] != string.Empty)
            {
                req.cardOwnerDateOfBirth = parameters["cardOwnerDateOfBirth"];
            }

            // (Optional) Expiration date of the payment card.
            if (parameters["expirationMonth"] != string.Empty && parameters["expirationYear"] != string.Empty)
            {
                req.expirationDate = new CardDateType(
                    Convert.ToInt32(parameters["expirationMonth"]),
                    Convert.ToInt32(parameters["expirationYear"]));
            }

            // The verification code of the payment card. This parameter is
            // generally required for calls in which confirmationType is
            // NONE. With the appropriate account review, this parameter can
            // be optional.
            if (parameters["cardVerificationNumber"] != string.Empty)
            {
                req.cardVerificationNumber = parameters["cardVerificationNumber"];
            }

            // (Optional) Start date of the payment card.
            if (parameters["startMonth"] != string.Empty && parameters["startYear"] != string.Empty)
            {
                req.startDate = new CardDateType(
                    Convert.ToInt32(parameters["startMonth"]),
                    Convert.ToInt32(parameters["startYear"]));
            }

            // (Optional) 2-digit issue number of the payment card (for
            // Maestro cards only).
            if (parameters["issueNumber"] != string.Empty)
            {
                req.issueNumber = parameters["issueNumber"];
            }

            // (Optional) Structure in which to pass the URLs for the return
            // and cancelation web flows
            if (confirmationType == ConfirmationType.WEB &&
                (parameters["returnURL"] != string.Empty || parameters["returnURLDescription"] != string.Empty ||
                 parameters["cancelURL"] != string.Empty || parameters["cancelURLDescription"] != string.Empty))
            {
                req.webOptions = new WebOptionsType();

                // (Optional) The URL to which PayPal returns the account holder
                // once he or she completes confirmation of the payment card
                // addition
                if (parameters["returnURL"] != string.Empty)
                {
                    req.webOptions.returnUrl = parameters["returnURL"];
                }
                if (parameters["returnURLDescription"] != string.Empty)
                {
                    req.webOptions.returnUrlDescription = parameters["returnURLDescription"];
                }

                // (Optional) The URL to which PayPal returns the account holder
                // if he or she cancels confirmation of the payment card
                // addition.
                if (parameters["cancelURL"] != string.Empty)
                {
                    req.webOptions.cancelUrl = parameters["cancelURL"];
                }
                if (parameters["cancelURLDescription"] != string.Empty)
                {
                    req.webOptions.cancelUrlDescription = parameters["cancelURLDescription"];
                }
            }

            // Create the AdaptiveAccounts service object to make the API call
            AdaptiveAccountsService service = null;
            AddPaymentCardResponse  resp    = null;

            try
            {
                // Configuration map containing signature credentials and other required configuration.
                // For a full list of configuration parameters refer in wiki page
                // (https://github.com/paypal/sdk-core-dotnet/wiki/SDK-Configuration-Parameters)
                Dictionary <string, string> configurationMap = Configuration.GetAcctAndConfig();

                // Creating service wrapper object to make an API call and loading
                // configuration map for your credentials and endpoint
                service = new AdaptiveAccountsService(configurationMap);

                // # API call
                // Invoke the CreateAccount method in service wrapper object
                resp = service.AddPaymentCard(req);
            }
            catch (System.Exception e)
            {
                context.Response.Write(e.Message);
                return;
            }

            // Display response values.
            Dictionary <string, string> keyResponseParams = new Dictionary <string, string>();
            string redirectUrl = null;

            if (!(resp.responseEnvelope.ack == AckCode.FAILURE) &&
                !(resp.responseEnvelope.ack == AckCode.FAILUREWITHWARNING))
            {
                redirectUrl = resp.redirectURL;
                keyResponseParams.Add("Execution status", resp.execStatus.ToString());
                keyResponseParams.Add("Funding source key", resp.fundingSourceKey);

                //Selenium Test Case
                keyResponseParams.Add("Acknowledgement", resp.responseEnvelope.ack.ToString());
                keyResponseParams.Add("Redirect To PayPal", resp.redirectURL);
            }
            displayResponse(context, "AddPaymentCard", keyResponseParams, service.getLastRequest(), service.getLastResponse(),
                            resp.error, redirectUrl);
        }
Example #49
0
 public string GetNetworkAddress(AddressType addressType)
 {
     return(((AddressGenerator)base.AddressGenerator).GenerateAddress(base.PublicKey, addressType));
 }
Example #50
0
        static async Task Task(string[] args)
        {
            var context               = new Dab2_2RdbContext();
            var uow                   = new UnitOfWork(context);
            var personRepo            = new Repository <Person>(context);
            var telephoneCompanyRepo  = new Repository <TelephoneCompany>(context);
            var addressRepo           = new Repository <Address>(context);
            var personAddressRepo     = new UnionRepository <PersonAddress>(context);
            var addressTypeRepo       = new Repository <AddressType>(context);
            var personAddressTypeRepo = new UnionRepository <PersonAddressType>(context);
            var cityRepo              = new Repository <City>(context);
            var countryCodeRepo       = new Repository <CountryCode>(context);

            var person = new Person
            {
                FirstName    = "Kasper",
                LastName     = "Hermansen",
                Email        = "*****@*****.**",
                Context      = "Myself",
                PhoneNumbers = new List <PhoneNumber>()
                {
                    new PhoneNumber()
                    {
                        Number = "+45 28 99 02 58",
                        Usage  = "Work",
                    },
                    new PhoneNumber()
                    {
                        Number = "+45 61 66 20 25",
                        Usage  = "School",
                    }
                },
            };

            var telephoneCompany = new TelephoneCompany()
            {
                CompanyName = "Telmore"
            };

            var address = new Address()
            {
                AddressName = new AddressName()
                {
                    HouseNumber = "4",
                    StreetName  = "Grankrogen"
                }
            };

            var personAddress = new PersonAddress()
            {
                Address = address,
                Person  = person
            };

            var addressType = new AddressType()
            {
                Type    = "Home",
                Address = address
            };

            var personAddressType = new PersonAddressType()
            {
                Person      = person,
                AddressType = addressType
            };

            var city = new City()
            {
                Name    = "Skødstrup",
                ZipCode = "8541",
            };

            city.Addresses.Add(address);

            var countryCode = new CountryCode()
            {
                City = city,
                Code = "Dk"
            };


            Console.WriteLine("Creating classes");
            Console.WriteLine();

            // Create
            // Person
            await personRepo.CreateAsync(person);

            // Telephonecompany
            await telephoneCompanyRepo.CreateAsync(telephoneCompany);

            await personAddressRepo.CreateAsync(personAddress);

            await personAddressTypeRepo.CreateAsync(personAddressType);

            await cityRepo.CreateAsync(city);

            await countryCodeRepo.CreateAsync(countryCode);

            await uow.SaveAsync();

            Console.WriteLine("Unit Of Work - Saving...");

            Console.WriteLine("Reading info");
            Console.WriteLine();

            // Read
            person = personRepo.ReadAsync(person.Id).Result;
            PrintPerson(telephoneCompanyRepo, person, telephoneCompany);

            Console.WriteLine("Updating info");
            Console.WriteLine();

            // Update
            person.FirstName = "Karsten";
            person.PhoneNumbers.Add(new PhoneNumber()
            {
                Number = "Blabla 22 22",
                Usage  = "Misc"
            });

            foreach (var personPhoneNumber in person.PhoneNumbers)
            {
                personPhoneNumber.TelephoneCompany = telephoneCompany;
            }
            await telephoneCompanyRepo.UpdateAsync(telephoneCompany.Id, telephoneCompany);


            await personRepo.UpdateAsync(person.Id, person);

            await uow.SaveAsync();

            Console.WriteLine("Unit Of Work - Saving...");

            PrintPerson(telephoneCompanyRepo, person, telephoneCompany);

            Console.WriteLine("Deleting Info");
            Console.WriteLine();

            // Delete
            personRepo.Delete(person);
            telephoneCompanyRepo.Delete(telephoneCompany);
            addressRepo.Delete(address);
            cityRepo.Delete(city);
            countryCodeRepo.Delete(countryCode);

            await uow.SaveAsync();

            Console.WriteLine("Unit Of Work - Saving...");


            try
            {
                person = null;
                person = personRepo.ReadAsync(person.Id).Result;
            }
            catch (Exception)
            {
                Console.WriteLine("Person not found...");
            }
        }
Example #51
0
        /// <summary>Adds a recipient RFC 822 formatted email address to the MailMessage</summary>
        /// <param name="address">RFC 822 formatted email address that you want to add to the MailMessage</param>
        /// <param name="type">AddressType of the email address</param>
        /// <example>
        /// <code>
        ///     MailMessage msg = new MailMessage("*****@*****.**", "*****@*****.**");
        ///		msg.AddRecipient("*****@*****.**", AddressType.Cc);
        /// </code>
        /// </example>
        public void AddRecipient(string address, AddressType type)
        {
            EmailAddress email = new EmailAddress(address);

            AddRecipient(email, type);
        }
Example #52
0
 /// <summary>
 /// Allows for overriding the creation of <see cref="ICustomerAddress"/> from <see cref="ICheckoutAddressModel"/>.
 /// </summary>
 /// <param name="model">
 /// The <see cref="ICustomerAddress"/>.
 /// </param>
 /// <param name="adr">
 /// The <see cref="ICheckoutAddressModel"/>.
 /// </param>
 /// <param name="customer">
 /// The <see cref="ICustomer"/>.
 /// </param>
 /// <param name="label">
 /// The customer address label (e.g. My House).
 /// </param>
 /// <param name="addressType">
 /// The <see cref="AddressType"/>.
 /// </param>
 /// <returns>
 /// The modified <see cref="ICustomerAddress"/>.
 /// </returns>
 protected virtual ICustomerAddress OnCreate(ICustomerAddress model, TAddress adr, ICustomer customer, string label, AddressType addressType)
 {
     return(model);
 }
Example #53
0
 public InstructionByte(byte @byte, int lineNumber)
 {
     _byte        = @byte;
     _addressType = AddressType.DirectValue;
     _lineNumber  = lineNumber;
 }
Example #54
0
                private Contact(string name, string zipCode, string city, string country, string streetOrAddressline1, string houseNumberOrAddressline2, AddressType addressType)
                {
                    //Pattern extracted from https://qr-validation.iso-payments.ch as explained in https://github.com/codebude/QRCoder/issues/97
                    var charsetPattern = @"^([a-zA-Z0-9\.,;:'\ \+\-/\(\)?\*\[\]\{\}\\`´~ ]|[!""#%&<>÷=@_$£]|[àáâäçèéêëìíîïñòóôöùúûüýßÀÁÂÄÇÈÉÊËÌÍÎÏÒÓÔÖÙÚÛÜÑ])*$";

                    adrType = addressType;

                    if (string.IsNullOrEmpty(name))
                    {
                        throw new SwissQrCodeContactException("Name must not be empty.");
                    }
                    if (name.Length > 70)
                    {
                        throw new SwissQrCodeContactException("Name must be shorter than 71 chars.");
                    }
                    if (!Regex.IsMatch(name, charsetPattern))
                    {
                        throw new SwissQrCodeContactException($"Name must match the following pattern as defined in pain.001: {charsetPattern}");
                    }
                    this.name = name;

                    if (AddressType.StructuredAddress == adrType)
                    {
                        if (!string.IsNullOrEmpty(streetOrAddressline1) && streetOrAddressline1.Length > 70)
                        {
                            throw new SwissQrCodeContactException("Street must be shorter than 71 chars.");
                        }
                        if (!string.IsNullOrEmpty(streetOrAddressline1) && !Regex.IsMatch(streetOrAddressline1, charsetPattern))
                        {
                            throw new SwissQrCodeContactException($"Street must match the following pattern as defined in pain.001: {charsetPattern}");
                        }
                        this.streetOrAddressline1 = streetOrAddressline1;

                        if (!string.IsNullOrEmpty(houseNumberOrAddressline2) && houseNumberOrAddressline2.Length > 16)
                        {
                            throw new SwissQrCodeContactException("House number must be shorter than 17 chars.");
                        }
                        this.houseNumberOrAddressline2 = houseNumberOrAddressline2;
                    }
                    else
                    {
                        if (!string.IsNullOrEmpty(streetOrAddressline1) && streetOrAddressline1.Length > 70)
                        {
                            throw new SwissQrCodeContactException("Address line 1 must be shorter than 71 chars.");
                        }
                        if (!string.IsNullOrEmpty(streetOrAddressline1) && !Regex.IsMatch(streetOrAddressline1, charsetPattern))
                        {
                            throw new SwissQrCodeContactException($"Address line 1 must match the following pattern as defined in pain.001: {charsetPattern}");
                        }
                        this.streetOrAddressline1 = streetOrAddressline1;

                        if (string.IsNullOrEmpty(houseNumberOrAddressline2))
                        {
                            throw new SwissQrCodeContactException("Address line 2 must be provided for combined addresses (address line-based addresses).");
                        }
                        if (!string.IsNullOrEmpty(houseNumberOrAddressline2) && houseNumberOrAddressline2.Length > 70)
                        {
                            throw new SwissQrCodeContactException("Address line 2 must be shorter than 71 chars.");
                        }
                        if (!string.IsNullOrEmpty(houseNumberOrAddressline2) && !Regex.IsMatch(houseNumberOrAddressline2, charsetPattern))
                        {
                            throw new SwissQrCodeContactException($"Address line 2 must match the following pattern as defined in pain.001: {charsetPattern}");
                        }
                        this.houseNumberOrAddressline2 = houseNumberOrAddressline2;
                    }

                    if (AddressType.StructuredAddress == adrType)
                    {
                        if (string.IsNullOrEmpty(zipCode))
                        {
                            throw new SwissQrCodeContactException("Zip code must not be empty.");
                        }
                        if (zipCode.Length > 16)
                        {
                            throw new SwissQrCodeContactException("Zip code must be shorter than 17 chars.");
                        }
                        if (!Regex.IsMatch(zipCode, charsetPattern))
                        {
                            throw new SwissQrCodeContactException($"Zip code must match the following pattern as defined in pain.001: {charsetPattern}");
                        }
                        this.zipCode = zipCode;

                        if (string.IsNullOrEmpty(city))
                        {
                            throw new SwissQrCodeContactException("City must not be empty.");
                        }
                        if (city.Length > 35)
                        {
                            throw new SwissQrCodeContactException("City name must be shorter than 36 chars.");
                        }
                        if (!Regex.IsMatch(city, charsetPattern))
                        {
                            throw new SwissQrCodeContactException($"City name must match the following pattern as defined in pain.001: {charsetPattern}");
                        }
                        this.city = city;
                    }
                    else
                    {
                        this.zipCode = this.city = string.Empty;
                    }

                    if (!IsValidTwoLetterCode(country))
                    {
                        throw new SwissQrCodeContactException("Country must be a valid \"two letter\" country code as defined by  ISO 3166-1, but it isn't.");
                    }

                    this.country = country;
                }
Example #55
0
        protected ProcessPaymentResult AuthorizeOrSale(ProcessPaymentRequest processPaymentRequest, bool authorizeOnly)
        {
            var result = new ProcessPaymentResult();

            var customer = _customerService.GetCustomerById(processPaymentRequest.CustomerId);

            if (customer == null)
            {
                throw new Exception("Customer cannot be loaded");
            }

            var req = new DoDirectPaymentReq();

            req.DoDirectPaymentRequest         = new DoDirectPaymentRequestType();
            req.DoDirectPaymentRequest.Version = GetApiVersion();
            var details = new DoDirectPaymentRequestDetailsType();

            req.DoDirectPaymentRequest.DoDirectPaymentRequestDetails = details;
            details.IPAddress = _webHelper.GetCurrentIpAddress() ?? "";
            if (authorizeOnly)
            {
                details.PaymentAction = PaymentActionCodeType.AUTHORIZATION;
            }
            else
            {
                details.PaymentAction = PaymentActionCodeType.SALE;
            }
            //credit card
            details.CreditCard = new CreditCardDetailsType();
            details.CreditCard.CreditCardNumber = processPaymentRequest.CreditCardNumber;
            details.CreditCard.CreditCardType   = GetPaypalCreditCardType(processPaymentRequest.CreditCardType);
            details.CreditCard.ExpMonth         = processPaymentRequest.CreditCardExpireMonth;
            details.CreditCard.ExpYear          = processPaymentRequest.CreditCardExpireYear;
            details.CreditCard.CVV2             = processPaymentRequest.CreditCardCvv2;
            details.CreditCard.CardOwner        = new PayerInfoType();
            var country = EngineContext.Current.Resolve <ICountryService>().GetCountryById(customer.BillingAddress.CountryId);

            details.CreditCard.CardOwner.PayerCountry = GetPaypalCountryCodeType(country);
            //billing address
            details.CreditCard.CardOwner.Address          = new AddressType();
            details.CreditCard.CardOwner.Address.Street1  = customer.BillingAddress.Address1;
            details.CreditCard.CardOwner.Address.Street2  = customer.BillingAddress.Address2;
            details.CreditCard.CardOwner.Address.CityName = customer.BillingAddress.City;
            if (!String.IsNullOrEmpty(customer.BillingAddress.StateProvinceId))
            {
                var state = EngineContext.Current.Resolve <IStateProvinceService>().GetStateProvinceById(customer.BillingAddress.StateProvinceId);
                details.CreditCard.CardOwner.Address.StateOrProvince = state.Abbreviation;
            }
            else
            {
                details.CreditCard.CardOwner.Address.StateOrProvince = "CA";
            }
            details.CreditCard.CardOwner.Address.Country    = GetPaypalCountryCodeType(country);
            details.CreditCard.CardOwner.Address.PostalCode = customer.BillingAddress.ZipPostalCode;
            details.CreditCard.CardOwner.Payer               = customer.BillingAddress.Email;
            details.CreditCard.CardOwner.PayerName           = new PersonNameType();
            details.CreditCard.CardOwner.PayerName.FirstName = customer.BillingAddress.FirstName;
            details.CreditCard.CardOwner.PayerName.LastName  = customer.BillingAddress.LastName;
            //order totals
            var payPalCurrency = PaypalHelper.GetPaypalCurrency(_currencyService.GetCurrencyById(_currencySettings.PrimaryStoreCurrencyId));

            details.PaymentDetails                       = new PaymentDetailsType();
            details.PaymentDetails.OrderTotal            = new BasicAmountType();
            details.PaymentDetails.OrderTotal.value      = Math.Round(processPaymentRequest.OrderTotal, 2).ToString("N", new CultureInfo("en-us"));
            details.PaymentDetails.OrderTotal.currencyID = payPalCurrency;
            details.PaymentDetails.Custom                = processPaymentRequest.OrderGuid.ToString();
            details.PaymentDetails.ButtonSource          = "nopCommerceCart";
            //shipping
            if (customer.ShippingAddress != null)
            {
                if (!String.IsNullOrEmpty(customer.ShippingAddress.StateProvinceId) && !String.IsNullOrEmpty(customer.ShippingAddress.CountryId))
                {
                    var state           = EngineContext.Current.Resolve <IStateProvinceService>().GetStateProvinceById(customer.ShippingAddress.StateProvinceId);
                    var countryshipping = EngineContext.Current.Resolve <ICountryService>().GetCountryById(customer.ShippingAddress.CountryId);

                    var shippingAddress = new AddressType();
                    shippingAddress.Name                 = customer.ShippingAddress.FirstName + " " + customer.ShippingAddress.LastName;
                    shippingAddress.Street1              = customer.ShippingAddress.Address1;
                    shippingAddress.Street2              = customer.ShippingAddress.Address2;
                    shippingAddress.CityName             = customer.ShippingAddress.City;
                    shippingAddress.StateOrProvince      = state.Abbreviation;
                    shippingAddress.PostalCode           = customer.ShippingAddress.ZipPostalCode;
                    shippingAddress.Country              = (CountryCodeType)Enum.Parse(typeof(CountryCodeType), countryshipping.TwoLetterIsoCode, true);
                    details.PaymentDetails.ShipToAddress = shippingAddress;
                }
            }

            //send request
            var service = GetService();
            DoDirectPaymentResponseType response = service.DoDirectPayment(req);

            string error;
            bool   success = PaypalHelper.CheckSuccess(response, out error);

            if (success)
            {
                result.AvsResult = response.AVSCode;
                result.AuthorizationTransactionCode = response.CVV2Code;
                if (authorizeOnly)
                {
                    result.AuthorizationTransactionId     = response.TransactionID;
                    result.AuthorizationTransactionResult = response.Ack.ToString();

                    result.NewPaymentStatus = PaymentStatus.Authorized;
                }
                else
                {
                    result.CaptureTransactionId     = response.TransactionID;
                    result.CaptureTransactionResult = response.Ack.ToString();

                    result.NewPaymentStatus = PaymentStatus.Paid;
                }
            }
            else
            {
                result.AddError(error);
            }
            return(result);
        }
Example #56
0
 public MiniMap(MemoryReader _memRead, MemoryScanner _memScan, AddressType _type)
 {
     this.memRead = _memRead;
     this.memScan = _memScan;
     this.Type    = _type;
 }
Example #57
0
        public void GetAddressTypeTest(string address, NetworkType nt, AddressType expected)
        {
            AddressType actual = Address.GetAddressType(address, nt);

            Assert.Equal(expected, actual);
        }
Example #58
0
 public ContainerPointer(MemoryReader _memRead, MemoryScanner _memScan, AddressType _type)
 {
     this.memRead = _memRead;
     this.memScan = _memScan;
     this.Type    = _type;
 }
Example #59
0
 ///<summary>Sets the value of the <c>&lt;Address&gt;</c> element.</summary>
 /// <param name="Type">Code that defines the location of the address. Note: A subset of specific valid values for each instance in a data object may be listed in that object.</param>
 /// <param name="Role">A facet of Address</param>
 /// <param name="Street">A Street</param>
 /// <param name="City">The city part of the address.</param>
 /// <param name="PostalCode">The ZIP/postal code.</param>
 ///<remarks>
 /// <para>This form of <c>setAddress</c> is provided as a convenience method
 /// that is functionally equivalent to the <c>Address</c></para>
 /// <para>Version: 2.6</para>
 /// <para>Since: 2.6</para>
 /// </remarks>
 public void SetAddress(AddressType Type, AddressRoleType Role, Street Street, string City, string PostalCode)
 {
     RemoveChild(Sif3assessmentDTD.SIF3ASSESSMENTSTUDENTSNAPSHOT_ADDRESS);
     AddChild(Sif3assessmentDTD.SIF3ASSESSMENTSTUDENTSNAPSHOT_ADDRESS, new Address(Type, Role, Street, City, PostalCode));
 }
 public async Task SetDefault(string defaultAddressId, AddressType addressType)
 {
     using (var client = new HttpClient())
     {
         var response = await client.PutAsync(new Uri(_clientBaseUrl + "/?defaultAddressId=" + defaultAddressId + "&addressType=" + addressType), null);
         await response.EnsureSuccessWithValidationSupportAsync();
     }
 }