예제 #1
0
        //ToDo: Add OperatorIdFilter and CountryCodeFilter
        #region ToXML(CustomPullEVSEDataRequestSerializer = null)

        /// <summary>
        /// Return a XML representation of this object.
        /// </summary>
        /// <param name="CustomPullEVSEDataRequestSerializer">A delegate to customize the serialization of PullEVSEData requests.</param>
        public XElement ToXML(CustomXMLSerializerDelegate <PullEVSEDataRequest> CustomPullEVSEDataRequestSerializer = null)
        {
            var XML = new XElement(OICPNS.EVSEData + "eRoamingPullEvseData",

                                   new XElement(OICPNS.EVSEData + "ProviderID", ProviderId.ToString()),

                                   SearchCenter != null && DistanceKM > 0
                                       ? new XElement(OICPNS.EVSEData + "SearchCenter",
                                                      new XElement(OICPNS.CommonTypes + "GeoCoordinates",
                                                                   new XElement(OICPNS.CommonTypes + "DecimalDegree",
                                                                                new XElement(OICPNS.CommonTypes + "Longitude", SearchCenter.Value.Longitude.ToString("{0:0.######}").Replace(",", ".")),
                                                                                new XElement(OICPNS.CommonTypes + "Latitude", SearchCenter.Value.Latitude.ToString("{0:0.######}").Replace(",", "."))
                                                                                )
                                                                   ),
                                                      new XElement(OICPNS.CommonTypes + "Radius", String.Format("{0:0.}", DistanceKM).Replace(",", "."))
                                                      )
                                       : null,

                                   LastCall.HasValue
                                       ? new XElement(OICPNS.EVSEData + "LastCall", LastCall.Value.ToIso8601())
                                       : null,

                                   new XElement(OICPNS.EVSEData + "GeoCoordinatesResponseFormat", "DecimalDegree")

                                   );

            return(CustomPullEVSEDataRequestSerializer != null
                       ? CustomPullEVSEDataRequestSerializer(this, XML)
                       : XML);
        }
예제 #2
0
        public override string ToString()
        {
            StringBuilder sb = new StringBuilder();

            sb.AppendLine("----------- ECM INFO -----------");
            sb.Append("Service ID: 0x");
            sb.AppendLine(ServiceId.ToString("x4"));
            sb.Append("PID:        0x");
            sb.AppendLine(Pid.ToString("x4"));
            sb.Append("Caid:       0x");
            sb.AppendLine(CaId.ToString("x4"));
            sb.Append("ProvId:     0x");
            sb.AppendLine(ProviderId.ToString("x6"));
            sb.Append("Cardsystem: ");
            sb.AppendLine(CardSystem);
            sb.Append("Reader:     ");
            sb.AppendLine(ReaderName);
            sb.Append("Source:     ");
            sb.AppendLine(SourceName);
            sb.Append("Protocol:   ");
            sb.AppendLine(ProtocolName);
            sb.Append("Hops:       ");
            sb.AppendLine(HopsCount.ToString());
            sb.Append("Time:       ");
            sb.Append(EcmTime.ToString());
            sb.AppendLine("ms");
            sb.AppendLine("----------- ECM INFO -----------");

            return(sb.ToString());
        }
예제 #3
0
        /// <summary>
        /// Return a XML representation of this object.
        /// </summary>
        /// <param name="CustomAuthorizeRemoteStartRequestSerializer">A delegate to customize the serialization of AuthorizeRemoteStart requests.</param>
        /// <param name="CustomIdentificationSerializer">A delegate to serialize custom Identification XML elements.</param>
        public XElement ToXML(CustomXMLSerializerDelegate <AuthorizeRemoteStartRequest> CustomAuthorizeRemoteStartRequestSerializer = null,
                              CustomXMLSerializerDelegate <Identification> CustomIdentificationSerializer = null)
        {
            var XML = new XElement(OICPNS.Authorization + "eRoamingAuthorizeRemoteStart",

                                   SessionId.HasValue
                                           ? new XElement(OICPNS.Authorization + "SessionID", SessionId.ToString())
                                           : null,

                                   CPOPartnerSessionId.HasValue
                                           ? new XElement(OICPNS.Authorization + "CPOPartnerSessionID", CPOPartnerSessionId.ToString())
                                           : null,

                                   EMPPartnerSessionId.HasValue
                                           ? new XElement(OICPNS.Authorization + "EMPPartnerSessionID", EMPPartnerSessionId.ToString())
                                           : null,

                                   new XElement(OICPNS.Authorization + "ProviderID", ProviderId.ToString()),
                                   new XElement(OICPNS.Authorization + "EvseID", EVSEId.ToString()),

                                   Identification.ToXML(CustomIdentificationSerializer: CustomIdentificationSerializer),

                                   PartnerProductId.HasValue
                                           ? new XElement(OICPNS.Authorization + "PartnerProductID", PartnerProductId.ToString())
                                           : null

                                   );

            return(CustomAuthorizeRemoteStartRequestSerializer != null
                       ? CustomAuthorizeRemoteStartRequestSerializer(this, XML)
                       : XML);
        }
        /// <summary>
        /// Return a JSON-representation of this object.
        /// </summary>
        /// <param name="CustomAuthorizeRemoteReservationStopRequestSerializer">A delegate to customize the serialization of AuthorizeRemoteReservationStopRequest responses.</param>
        public JObject ToJSON(CustomJObjectSerializerDelegate <AuthorizeRemoteReservationStopRequest> CustomAuthorizeRemoteReservationStopRequestSerializer = null)
        {
            var JSON = JSONObject.Create(

                new JProperty("ProviderID", ProviderId.ToString()),
                new JProperty("EvseID", EVSEId.ToString()),
                new JProperty("SessionID", SessionId.ToString()),

                CPOPartnerSessionId.HasValue
                               ? new JProperty("CPOPartnerSessionID", CPOPartnerSessionId.Value.ToString())
                               : null,

                EMPPartnerSessionId.HasValue
                               ? new JProperty("EMPPartnerSessionID", EMPPartnerSessionId.Value.ToString())
                               : null,

                CustomData != null
                               ? new JProperty("CustomData", CustomData)
                               : null

                );

            return(CustomAuthorizeRemoteReservationStopRequestSerializer != null
                       ? CustomAuthorizeRemoteReservationStopRequestSerializer(this, JSON)
                       : JSON);
        }
예제 #5
0
        /// <summary>
        /// Return a JSON-representation of this object.
        /// </summary>
        /// <param name="CustomGetChargeDetailRecordsRequestSerializer">A delegate to customize the serialization of GetChargeDetailRecordsRequest responses.</param>
        public JObject ToJSON(CustomJObjectSerializerDelegate <GetChargeDetailRecordsRequest> CustomGetChargeDetailRecordsRequestSerializer = null)
        {
            var JSON = JSONObject.Create(

                new JProperty("ProviderID", ProviderId.ToString()),
                new JProperty("From", From.ToIso8601()),
                new JProperty("To", To.ToIso8601()),

                SessionIds.SafeAny()
                               ? new JProperty("SessionID", new JArray(SessionIds.Select(sessionId => sessionId.ToString())))
                               : null,

                OperatorIds.SafeAny()
                               ? new JProperty("OperatorID", new JArray(SessionIds.Select(sessionId => sessionId.ToString())))
                               : null,

                CustomData != null
                               ? new JProperty("CustomData", CustomData)
                               : null

                );

            return(CustomGetChargeDetailRecordsRequestSerializer != null
                       ? CustomGetChargeDetailRecordsRequestSerializer(this, JSON)
                       : JSON);
        }
        /// <summary>
        /// Return a JSON-representation of this object.
        /// </summary>
        /// <param name="CustomPullEVSEStatusRequestSerializer">A delegate to customize the serialization of PullEVSEStatusRequest responses.</param>
        /// <param name="CustomGeoCoordinatesSerializer">A delegate to serialize custom geo coordinates JSON objects.</param>
        public JObject ToJSON(CustomJObjectSerializerDelegate <PullEVSEStatusRequest> CustomPullEVSEStatusRequestSerializer = null,
                              CustomJObjectSerializerDelegate <GeoCoordinates> CustomGeoCoordinatesSerializer = null)
        {
            var JSON = JSONObject.Create(

                new JProperty("ProviderID", ProviderId.ToString()),

                SearchCenter.HasValue && DistanceKM.HasValue
                               ? new JProperty("SearchCenter", new JObject(
                                                   new JProperty("GeoCoordinates", SearchCenter.Value.ToJSON(CustomGeoCoordinatesSerializer)),
                                                   new JProperty("Radius", DistanceKM.Value)
                                                   ))
                               : null,

                EVSEStatusFilter.HasValue
                               ? new JProperty("EvseStatus", EVSEStatusFilter.Value.AsString())
                               : null,

                CustomData != null
                               ? new JProperty("CustomData", CustomData)
                               : null

                );

            return(CustomPullEVSEStatusRequestSerializer != null
                       ? CustomPullEVSEStatusRequestSerializer(this, JSON)
                       : JSON);
        }
        public override Dictionary <string, string> ToDictionary()
        {
            var result = base.ToDictionary();

            result.Add("ProviderId", ProviderId.ToString());

            return(result);
        }
예제 #8
0
        /// <summary>
        /// Return a XML representation of this object.
        /// </summary>
        /// <param name="CustomGetChargeDetailRecordsRequestSerializer">A delegate to customize the serialization of GetChargeDetailRecords requests.</param>
        public XElement ToXML(CustomXMLSerializerDelegate <GetChargeDetailRecordsRequest> CustomGetChargeDetailRecordsRequestSerializer = null)
        {
            var XML = new XElement(OICPNS.Authorization + "eRoamingGetChargeDetailRecords",
                                   new XElement(OICPNS.Authorization + "ProviderID", ProviderId.ToString()),
                                   new XElement(OICPNS.Authorization + "From", From.ToIso8601()),
                                   new XElement(OICPNS.Authorization + "To", To.ToIso8601())
                                   );

            return(CustomGetChargeDetailRecordsRequestSerializer != null
                       ? CustomGetChargeDetailRecordsRequestSerializer(this, XML)
                       : XML);
        }
        /// <summary>
        /// Return a XML representation of this object.
        /// </summary>
        /// <param name="CustomPullEVSEStatusByOperatorIdRequestSerializer">A delegate to serialize custom eRoamingPullEvseStatusByOperatorId XML elements.</param>
        public XElement ToXML(CustomXMLSerializerDelegate <PullEVSEStatusByOperatorIdRequest> CustomPullEVSEStatusByOperatorIdRequestSerializer = null)
        {
            var XML = new XElement(OICPNS.EVSEStatus + "eRoamingPullEvseStatusByOperatorID",

                                   new XElement(OICPNS.EVSEStatus + "ProviderID", ProviderId.ToString()),

                                   OperatorIds.SafeSelect(evseid => new XElement(OICPNS.EVSEStatus + "OperatorID", evseid.ToString()))

                                   );

            return(CustomPullEVSEStatusByOperatorIdRequestSerializer != null
                       ? CustomPullEVSEStatusByOperatorIdRequestSerializer(this, XML)
                       : XML);
        }
예제 #10
0
        public JObject ToJSON()

        => JSONObject.Create(

            new JProperty("@id", Id.ToString()),
            new JProperty("timestamp", Timestamp.ToIso8601()),
            new JProperty("startTime", StartTime.ToIso8601()),
            new JProperty("duration", Duration.TotalMinutes),
            new JProperty("endTime", EndTime.ToIso8601()),

            new JProperty("consumedReservationTime", ConsumedReservationTime.TotalMinutes),
            new JProperty("reservationLevel", ReservationLevel.ToString()),

            ProviderId.HasValue
                       ? new JProperty("providerId", ProviderId.ToString())
                       : null,

            StartAuthentication != null
                       ? new JProperty("authentication", EndTime.ToIso8601())
                       : null,

            RoamingNetworkId.HasValue
                       ? new JProperty("roamingNetworkId", RoamingNetworkId.ToString())
                       : null,

            ChargingPoolId.HasValue
                       ? new JProperty("chargingPoolId", ChargingPoolId.ToString())
                       : null,

            ChargingStationId.HasValue
                       ? new JProperty("chargingStationId", ChargingStationId.ToString())
                       : null,

            EVSEId.HasValue
                       ? new JProperty("EVSEId", EVSEId.ToString())
                       : null,

            ChargingProduct != null
                       ? new JProperty("chargingProduct", ChargingProduct.ToJSON())
                       : null,

            ChargingSession != null
                       ? new JProperty("chargingSessionId", ChargingSession.Id.ToString())
                       : null

            );
예제 #11
0
        /// <summary>
        /// Return a JSON-representation of this object.
        /// </summary>
        /// <param name="CustomPullEVSEStatusByIdRequestSerializer">A delegate to customize the serialization of PullEVSEStatusByIdRequest responses.</param>
        public JObject ToJSON(CustomJObjectSerializerDelegate <PullEVSEStatusByIdRequest> CustomPullEVSEStatusByIdRequestSerializer = null)
        {
            var JSON = JSONObject.Create(

                new JProperty("ProviderID", ProviderId.ToString()),

                new JProperty("EvseID", new JArray(EVSEIds.Select(evseId => evseId.ToString()))),

                CustomData != null
                               ? new JProperty("CustomData", CustomData)
                               : null

                );

            return(CustomPullEVSEStatusByIdRequestSerializer != null
                       ? CustomPullEVSEStatusByIdRequestSerializer(this, JSON)
                       : JSON);
        }
        public async Task Toggle_WithOrderNotFound_ShouldFail(bool isEnabled)
        {
            // Arrange
            const int ProviderId = 1;
            var       mockRepo = new Mock <IRepository <PaymentProvider> >();
            var       mockPaymentQueryable = new PaymentProvider[] { }.AsQueryable().BuildMock();

            mockRepo.Setup(repo => repo.Query()).Returns(mockPaymentQueryable.Object).Verifiable();

            // Action
            var service = new PaymentProviderService(mockRepo.Object);

            var(ok, message) = await service.ToggleAsync(ProviderId, isEnabled);

            // Assert
            mockRepo.Verify();
            Assert.False(ok);
            Assert.Contains(ProviderId.ToString(), message);
        }
        /// <summary>
        /// Return a JSON-representation of this object.
        /// </summary>
        /// <param name="CustomAuthorizeRemoteReservationStartRequestSerializer">A delegate to customize the serialization of AuthorizeRemoteReservationStartRequest responses.</param>
        /// <param name="CustomIdentificationSerializer">A delegate to serialize custom Identification JSON objects.</param>
        public JObject ToJSON(CustomJObjectSerializerDelegate <AuthorizeRemoteReservationStartRequest> CustomAuthorizeRemoteReservationStartRequestSerializer = null,
                              CustomJObjectSerializerDelegate <Identification> CustomIdentificationSerializer = null)
        {
            var JSON = JSONObject.Create(

                new JProperty("ProviderID", ProviderId.ToString()),
                new JProperty("EvseID", EVSEId.ToString()),
                new JProperty("Identification", Identification.ToJSON(CustomIdentificationSerializer)),

                SessionId.HasValue
                               ? new JProperty("SessionID", SessionId.Value.ToString())
                               : null,

                CPOPartnerSessionId.HasValue
                               ? new JProperty("CPOPartnerSessionID", CPOPartnerSessionId.Value.ToString())
                               : null,

                EMPPartnerSessionId.HasValue
                               ? new JProperty("EMPPartnerSessionID", EMPPartnerSessionId.Value.ToString())
                               : null,

                PartnerProductId.HasValue
                               ? new JProperty("PartnerProductID", PartnerProductId.Value.ToString())
                               : null,

                Duration.HasValue
                               ? new JProperty("Duration", (Int32)Duration.Value.TotalMinutes)
                               : null,

                CustomData != null
                               ? new JProperty("CustomData", CustomData)
                               : null

                );

            return(CustomAuthorizeRemoteReservationStartRequestSerializer != null
                       ? CustomAuthorizeRemoteReservationStartRequestSerializer(this, JSON)
                       : JSON);
        }
        /// <summary>
        /// Return a XML representation of this object.
        /// </summary>
        /// <param name="CustomAuthorizeRemoteReservationStartRequestSerializer">A delegate to customize the serialization of AuthorizeRemoteReservationStart requests.</param>
        /// <param name="CustomIdentificationSerializer">A delegate to serialize custom Identification XML elements.</param>
        public XElement ToXML(CustomXMLSerializerDelegate <AuthorizeRemoteReservationStartRequest> CustomAuthorizeRemoteReservationStartRequestSerializer = null,
                              CustomXMLSerializerDelegate <Identification> CustomIdentificationSerializer = null)

        {
            var XML = new XElement(OICPNS.Reservation + "eRoamingAuthorizeRemoteReservationStart",

                                   SessionId.HasValue
                                           ? new XElement(OICPNS.Reservation + "SessionID", SessionId.ToString())
                                           : null,

                                   CPOPartnerSessionId.HasValue
                                           ? new XElement(OICPNS.Reservation + "CPOPartnerSessionID", CPOPartnerSessionId.ToString())
                                           : null,

                                   EMPPartnerSessionId.HasValue
                                           ? new XElement(OICPNS.Reservation + "EMPPartnerSessionID", EMPPartnerSessionId.ToString())
                                           : null,

                                   new XElement(OICPNS.Reservation + "ProviderID", ProviderId.ToString()),
                                   new XElement(OICPNS.Reservation + "EVSEID", EVSEId.ToString()),

                                   Identification.ToXML(OICPNS.Reservation + "Identification",
                                                        CustomIdentificationSerializer),

                                   PartnerProductId.HasValue
                                           ? new XElement(OICPNS.Reservation + "PartnerProductID", PartnerProductId.ToString())
                                           : null,

                                   Duration.HasValue
                                           ? new XElement(OICPNS.Reservation + "Duration", Convert.ToInt32(Math.Round(Duration.Value.TotalMinutes, 0)))
                                           : null

                                   );

            return(CustomAuthorizeRemoteReservationStartRequestSerializer != null
                       ? CustomAuthorizeRemoteReservationStartRequestSerializer(this, XML)
                       : XML);
        }
        /// <summary>
        /// Return a XML representation of this object.
        /// </summary>
        /// <param name="CustomAuthorizeRemoteReservationStopRequestSerializer">A delegate to customize the serialization of AuthorizeRemoteReservationStop requests.</param>
        public XElement ToXML(CustomXMLSerializerDelegate <AuthorizeRemoteReservationStopRequest> CustomAuthorizeRemoteReservationStopRequestSerializer = null)
        {
            var XML = new XElement(OICPNS.Reservation + "eRoamingAuthorizeRemoteReservationStop",

                                   new XElement(OICPNS.Reservation + "SessionID", SessionId.ToString()),

                                   CPOPartnerSessionId.HasValue
                                           ? new XElement(OICPNS.Reservation + "CPOPartnerSessionID", CPOPartnerSessionId.ToString())
                                           : null,

                                   EMPPartnerSessionId.HasValue
                                           ? new XElement(OICPNS.Reservation + "EMPPartnerSessionID", EMPPartnerSessionId.ToString())
                                           : null,

                                   new XElement(OICPNS.Reservation + "ProviderID", ProviderId.ToString()),
                                   new XElement(OICPNS.Reservation + "EVSEID", EVSEId.ToString())

                                   );

            return(CustomAuthorizeRemoteReservationStopRequestSerializer != null
                       ? CustomAuthorizeRemoteReservationStopRequestSerializer(this, XML)
                       : XML);
        }
예제 #16
0
 public void WhenIAcknowledgeARuleAsBeingRead()
 {
     MarkRuleAsRead(ProviderId.ToString());
 }
예제 #17
0
        /// <summary>
        /// Return a JSON-representation of this object.
        /// </summary>
        /// <param name="CustomPullEVSEDataRequestSerializer">A delegate to customize the serialization of PullEVSEDataRequest responses.</param>
        /// <param name="CustomGeoCoordinatesSerializer">A delegate to serialize custom geo coordinates JSON objects.</param>
        public JObject ToJSON(CustomJObjectSerializerDelegate <PullEVSEDataRequest> CustomPullEVSEDataRequestSerializer = null,
                              CustomJObjectSerializerDelegate <GeoCoordinates> CustomGeoCoordinatesSerializer           = null)
        {
            var JSON = JSONObject.Create(

                new JProperty("ProviderID", ProviderId.ToString()),
                new JProperty("GeoCoordinatesResponseFormat", GeoCoordinatesResponseFormat.AsString()),

                LastCall.HasValue
                               ? new JProperty("LastCall", LastCall.Value.ToIso8601())
                               : null,

                OperatorIdFilter.SafeAny()
                               ? new JProperty("OperatorIds", new JArray(OperatorIdFilter.Select(operatorId => operatorId.ToString())))
                               : null,

                CountryCodeFilter.SafeAny()
                               ? new JProperty("CountryCodes", new JArray(CountryCodeFilter.Select(countryCode => countryCode.Alpha3Code)))
                               : null,

                AccessibilityFilter.SafeAny()
                               ? new JProperty("Accessibility", new JArray(AccessibilityFilter.Select(accessibility => accessibility.AsString())))
                               : null,

                AuthenticationModeFilter.SafeAny()
                               ? new JProperty("AuthenticationModes", new JArray(AuthenticationModeFilter.Select(authenticationMode => authenticationMode.AsString())))
                               : null,

                CalibrationLawDataAvailabilityFilter.SafeAny()
                               ? new JProperty("CalibrationLawDataAvailability", new JArray(CalibrationLawDataAvailabilityFilter.Select(calibrationLawDataAvailability => calibrationLawDataAvailability.AsString())))
                               : null,

                IsHubjectCompatibleFilter.HasValue
                               ? new JProperty("IsHubjectCompatible", IsHubjectCompatibleFilter.Value)
                               : null,

                IsOpen24HoursFilter.HasValue
                               ? new JProperty("IsOpen24Hours", IsOpen24HoursFilter.Value)
                               : null,

                RenewableEnergyFilter.HasValue
                               ? new JProperty("RenewableEnergy", RenewableEnergyFilter.Value)
                               : null,

                SearchCenter.HasValue && DistanceKM.HasValue
                               ? new JProperty("SearchCenter", new JObject(
                                                   new JProperty("GeoCoordinates", SearchCenter.Value.ToJSON(CustomGeoCoordinatesSerializer)),
                                                   new JProperty("Radius", DistanceKM.Value)
                                                   ))
                               : null,

                CustomData != null
                               ? new JProperty("CustomData", CustomData)
                               : null

                );

            return(CustomPullEVSEDataRequestSerializer != null
                       ? CustomPullEVSEDataRequestSerializer(this, JSON)
                       : JSON);
        }
예제 #18
0
 /// <summary>
 /// Creates a Uri describing this users "claimed identifier".
 /// </summary>
 public Uri GetClaimedIdentifier()
 {
     return(new Uri(Current.AppRootUri, "/user/" + ProviderId.ToString()));
 }
예제 #19
0
        //---------------------------------------------------------------------------------------------------------------------

        /// <summary>Processes a request regarding OpenIDs.</summary>

        /*!
         */
        public bool ProcessRequest()
        {
            string operationName = context.GetParamValue(IfyWebContext.OperationParameterName);

            openIdAuth = webContext.AllowOpenId;
            if (openIdAuth == 0)
            {
                context.ReturnError("OpenID authentication not permitted");
            }

            switch (operationName)
            {
            /*case "list" :
             *  if (context.AuthenticatedUser) {
             *      WriteProviderList(false);
             *      return true;
             *  } else {
             *      return false;
             *  }*/

            case "signin":
                // Sign-in modes:
                // (1) (Positive) OpenID authentication assertion
                // (2) Request for OpenID authentication
                // (3) Username/password login
                // (4) Display sign-in form

                try {
                    ServicePointManager.ServerCertificateValidationCallback = delegate(object sender, X509Certificate certificate, X509Chain chain, System.Net.Security.SslPolicyErrors sslPolicyErrors) {
                        return(true);
                    };

                    //ServicePointManager.CertificatePolicy = new CertificateAcceptor();

                    int providerId;
                    Int32.TryParse(context.GetParamValue("provider"), out providerId);
                    ProviderId = providerId;

                    if (context.GetParamValue("openid.mode") != null)       // (1)
                    {
                        OpenIdRelyingParty openId = null;
                        openId = OpenIdRelyingParty.RecoverFromAssociation();
                        openId.ResponseNonceStorage = webContext;
                        if (!openId.VerifyAuthenticationAssertion())
                        {
                            context.AddWarning("OpenID authentication was canceled", "openIdCanceled");
                            return(false);
                        }
                        webContext.AuthenticateWithOpenId(openId);
                        webContext.CheckAvailability(false);
                        context.WriteInfo("You are now logged in", "openIdAuthenticated");
                    }
                    else if ((UserInput = context.GetParamValue("openid")) != null || ProviderId != 0)         // (2)
                    {
                        if (ProviderId != 0)
                        {
                            provider = OpenIdProvider.FromId(context, ProviderId);
                        }

                        if (UserInput == null && !provider.UseOpenIdProviderIdentifier)
                        {
                            MissingIdentifier = true;
                            break;
                        }

                        // Get a OpenIdRelyingParty instance, either the generic one or the one corresponding to the requested OpenID provider
                        OpenIdRelyingParty openId = (provider == null ? OpenIdProvider.GetGenericRelyingParty(UserInput) : provider.GetRelyingParty(UserInput));

                        // Get an OpenID association
                        openId.ReturnToUrl = String.Format("{0}?{1}=signin{2}",
                                                           webContext.ScriptUrl,
                                                           IfyWebContext.OperationParameterName,
                                                           webContext.Format == null ? String.Empty : "&" + IfyWebContext.FormatParameterName + "=" + webContext.Format
                                                           );
                        openId.RealmPattern = webContext.HostUrl;
                        openId.GetAssociation();

                        if (context.GetParamValue("_debug") == "3")
                        {
                            context.WriteInfo("openid.op_endpoint:" + openId.EndpointUrl);
                            context.WriteInfo("openid.assoc_type:" + openId.AssociationType);
                            context.WriteInfo("openid.assoc_handle:" + openId.AssociationHandle);
                            context.WriteInfo("openid.mac_key:" + openId.Mac);
                            context.WriteInfo("openid.expires_in:" + openId.ExpiresIn.ToString());
                            context.WriteInfo(openId.AuthenticationUrl);
                        }
                        else
                        {
                            openId.RequestAuthentication();
                        }
                    }
                    else
                    {
                        if (openIdAuth != 2)
                        {
                            context.AddError("Invalid request");
                            return(false);
                        }
                    }
                } catch (Exception e) {
                    if (!context.ErrorHandled)
                    {
                        context.AddError(e.Message, null);
                    }
                }

                break;

            case "assign":
                try {
                    ServicePointManager.ServerCertificateValidationCallback = delegate(object sender, X509Certificate certificate, X509Chain chain, System.Net.Security.SslPolicyErrors sslPolicyErrors) {
                        return(true);
                    };

                    //ServicePointManager.CertificatePolicy = new CertificateAcceptor();

                    if (!context.IsUserAuthenticated)
                    {
                        webContext.RejectUnauthenticatedRequest();
                    }
                    bool success = false;

                    if (context.GetParamValue("openid.mode") == null)
                    {
                        UserInput = context.GetParamValue("openid");
                        int providerId;
                        Int32.TryParse(context.GetParamValue("provider"), out providerId);
                        ProviderId = providerId;

                        if (UserInput != null || ProviderId != 0)
                        {
                            // Store current OpenID's database ID in session (to remember it after the returning redirect from the OpenID provider)

                            if (ProviderId != 0)
                            {
                                provider = OpenIdProvider.FromId(context, ProviderId);
                            }

                            if (UserInput == null && !provider.UseOpenIdProviderIdentifier)
                            {
                                WriteSignInForm(true);
                                return(true);
                                //context.ReturnError("Missing identifier");
                            }

                            context.Execute(String.Format("INSERT INTO usropenid (id_usr, id_provider, user_input) VALUES ({0}, {1}, {2});",
                                                          context.UserId,
                                                          ProviderId == 0 ? "NULL" : ProviderId.ToString(),
                                                          StringUtils.EscapeSql(UserInput)
                                                          ));
                            sessionOpenIdId = context.GetInsertId();
                            HttpContext.Current.Session["openid.id"] = sessionOpenIdId;

                            try {
                                // Get a OpenIdRelyingParty instance, either the generic one or the one corresponding to the requested OpenID provider
                                OpenIdRelyingParty openId = (provider == null ? OpenIdProvider.GetGenericRelyingParty(UserInput) : provider.GetRelyingParty(UserInput));
                                openId.ReturnToUrl = String.Format("{0}?id={1}&{2}=assign{3}",
                                                                   webContext.ScriptUrl,
                                                                   sessionOpenIdId,
                                                                   IfyWebContext.OperationParameterName,
                                                                   webContext.Format == null ? String.Empty : "&" + IfyWebContext.FormatParameterName + "=" + webContext.Format
                                                                   );
                                openId.RealmPattern = webContext.HostUrl;
                                openId.GetAssociation();

                                if (context.GetParamValue("_debug") == "3")
                                {
                                    context.WriteInfo("openid.op_endpoint:" + openId.EndpointUrl);
                                    context.WriteInfo("openid.assoc_type:" + openId.AssociationType);
                                    context.WriteInfo("openid.assoc_handle:" + openId.AssociationHandle);
                                    context.WriteInfo("openid.mac_key:" + openId.Mac);
                                    context.WriteInfo("openid.expires_in:" + openId.ExpiresIn.ToString());
                                    context.WriteInfo(openId.AuthenticationUrl);
                                }
                                else
                                {
                                    openId.RequestAuthentication();
                                }
                            } catch (Exception e) {
                                if (!context.ErrorHandled)
                                {
                                    context.AddError(e.Message, null);
                                }
                            }
                            if (!success && sessionOpenIdId != 0)
                            {
                                context.Execute(String.Format("DELETE FROM usropenid WHERE id={0};", sessionOpenIdId));
                            }
                        }
                        else
                        {
                            MissingIdentifier = true;
                            if (openIdAuth == 2)
                            {
                                WriteSignInForm(true);
                            }
                        }
                    }
                    else
                    {
                        try {
                            success = Verify();
                        } catch (Exception e) {
                            if (!context.ErrorHandled)
                            {
                                context.AddError(e.Message, null);
                            }
                        }

                        // In case of failure, delete concerned user OpenID record, but only if not yet verified
                        if (!success && sessionOpenIdId != 0 && context.GetQueryBooleanValue(String.Format("SELECT claimed_id IS NULL FROM usropenid WHERE id={0};", sessionOpenIdId)))
                        {
                            context.Execute(String.Format("DELETE FROM usropenid WHERE id={0};", sessionOpenIdId));
                        }
                    }
                } catch (Exception e) {
                    if (!context.ErrorHandled)
                    {
                        context.AddError(e.Message, null);
                    }
                }

                break;

            case "delete":
                GetIdsFromRequest("id");
                if (Ids.Length != 0)
                {
                    DeleteItems(Ids);
                }
                break;
            }

            //if (MissingIdentifier) context.AddError("You must specify an OpenID", "missingInput");

            return(false);

            //if (context.AuthenticatedUser) userOpenId.WriteItemList();
            //return context.AuthenticatedUser;
        }
예제 #20
0
        private Dictionary <string, BasicQuotation> BuildProviderResultsIndex(Reply reply)
        {
            // build the provider result set
            DateTime dtNow = DateTime.Now;
            //InformationSource informationSource = ;
            // key = provider instrument id / field name
            var results = new Dictionary <string, BasicQuotation>();
            SecuritiesDataCollection securityColl = reply.GetSecurityDataItems();

            foreach (SecurityDataItem security in securityColl)
            {
                string instrName = security.Security.Name;
                //int fieldCount = security.FieldsData.Count;
                //BasicAssetValuation quote = new BasicAssetValuation() { objectReference = new AnyAssetReference() { href = instrName } };
                //quote.quote = new BasicQuotation[fieldCount];
                int fieldNum = 0;
                foreach (FieldDataItem dataNodeList in security.FieldsData)
                {
                    string fieldName        = dataNodeList.Field.Mnemonic;
                    string providerQuoteKey = FormatProviderQuoteKey(instrName, fieldName);
                    var    providerQuote    = new BasicQuotation();
                    // field value
                    object value = null;
                    string measureTypeAsString = AssetMeasureEnum.Undefined.ToString();
                    string quoteUnitsAsString  = PriceQuoteUnitsEnum.Undefined.ToString();
                    try
                    {
                        DataPoint point = dataNodeList.DataPoints[0];
                        value = point.Value;
                        if (point.IsError)
                        {
                            // bloomberg error
                            ReplyError replyError = point.ReplyError;
                            Logger.LogDebug("ReplyError: {0}/{1}={2}/{3}/{4}",
                                            instrName, fieldName, replyError.Code, replyError.DisplayName, replyError.Description);
                            quoteUnitsAsString = String.Format("{0}:{1}", replyError.Code, replyError.DisplayName);
                        }
                        else if (value == null)
                        {
                            // value mia
                            Logger.LogDebug("DataNullMissing: {0}/{1}='{2}'", instrName, fieldName);
                            quoteUnitsAsString = "DataNullMissing";
                        }
                        else if (value.GetType() == typeof(ReplyError))
                        {
                            // bloomberg error
                            var replyError = (ReplyError)value;
                            Logger.LogDebug("ReplyError: {0}/{1}={2}/{3}/{4}",
                                            instrName, fieldName, replyError.Code, replyError.DisplayName, replyError.Description);
                            quoteUnitsAsString = $"{replyError.Code}:{replyError.DisplayName}";
                        }
                        else if ((value is string) && (value.ToString().ToLower() == "n.a."))
                        {
                            // not available?
                            Logger.LogDebug("DataNotAvailable: {0}/{1}='{2}'", instrName, fieldName, value.ToString());
                            quoteUnitsAsString = "DataNotAvailable";
                        }
                        else
                        {
                            providerQuote.value          = Convert.ToDecimal(value);
                            providerQuote.valueSpecified = true;
                            // When the quote was computed (FpML definition) i.e. when the provider published it
                            providerQuote.valuationDateSpecified = true;
                            providerQuote.valuationDate          = point.Time;
                        }
                    }
                    catch (Exception e)
                    {
                        Logger.LogDebug("Exception: {0}/{1}='{2}' {3}", instrName, fieldName, value, e);
                        quoteUnitsAsString = $"{e.GetType().Name}:{e.Message}";
                    }
                    providerQuote.measureType = new AssetMeasureType {
                        Value = measureTypeAsString
                    };
                    providerQuote.quoteUnits = new PriceQuoteUnits {
                        Value = quoteUnitsAsString
                    };
                    providerQuote.informationSource = new[]
                    {
                        new InformationSource
                        {
                            rateSource = new InformationProvider {
                                Value = ProviderId.ToString()
                            },
                            rateSourcePage = new RateSourcePage {
                                Value = instrName + "/" + fieldName
                            }
                        }
                    };
                    // When the quote was observed or derived (FpML definition) i.e. now.
                    providerQuote.timeSpecified = true;
                    providerQuote.time          = dtNow;
                    results[providerQuoteKey]   = providerQuote;
                    // next field
                    fieldNum++;
                } // foreach field
            }     // foreach instr
            return(results);
        }
        /// <summary>
        /// Return a XML representation of this object.
        /// </summary>
        /// <param name="CustomIdentificationSerializer">A delegate to serialize custom ProviderAuthenticationData XML elements.</param>
        /// <param name="CustomIdentificationSerializer">A delegate to serialize custom Identification XML elements.</param>
        public XElement ToXML(CustomXMLSerializerDelegate <ProviderAuthenticationData> CustomProviderAuthenticationDataSerializer = null,
                              CustomXMLSerializerDelegate <Identification> CustomIdentificationSerializer = null)
        {
            var XML = new XElement(OICPNS.AuthenticationData + "ProviderAuthenticationData",

                                   new XElement(OICPNS.AuthenticationData + "ProviderID", ProviderId.ToString()),

                                   AuthorizationIdentifications.
                                   SafeSelect(AuthorizationIdentification => new XElement(
                                                  OICPNS.AuthenticationData + "AuthenticationDataRecord",
                                                  AuthorizationIdentification.ToXML(OICPNS.AuthenticationData + "Identification",
                                                                                    CustomIdentificationSerializer))
                                              )

                                   );

            return(CustomProviderAuthenticationDataSerializer != null
                       ? CustomProviderAuthenticationDataSerializer(this, XML)
                       : XML);
        }