Ejemplo n.º 1
0
        private void AddClaimInfo(FetchResponse claim, string identifier)
        {
            Email = claim.Attributes[WellKnownAttributes.Contact.Email].Values.FirstOrDefault();

            if (claim.Attributes.Contains(WellKnownAttributes.Name.FullName))
            {
                FullName = claim.Attributes[WellKnownAttributes.Name.FullName].Values.First();
            }
            else
            {
                if (claim.Attributes.Contains(WellKnownAttributes.Name.First))
                {
                    FullName = claim.Attributes[WellKnownAttributes.Name.First].Values.FirstOrDefault();
                }

                if (claim.Attributes.Contains(WellKnownAttributes.Name.Last))
                {
                    FullName += " ";
                    FullName += claim.Attributes[WellKnownAttributes.Name.Last].Values.FirstOrDefault();
                }
            }

            Nickname           = FullName ?? Email;
            IsSignedByProvider = claim.IsSignedByProvider;
            ClaimedIdentifier  = identifier;
        }
Ejemplo n.º 2
0
 public async Task <FetchResponse[]> FetchDataAsync(params FetchRequest[] requests)
 {
     FetchResponse[] res = new FetchResponse[requests.Length];
     for (int i = 0; i < requests.Length; i++)
     {
         if (requests[i].Domain.SpatialRegionType == SpatialRegionSpecification.Points || requests[i].Domain.SpatialRegionType == SpatialRegionSpecification.Cells)
         {
             double[] elevations = new double[requests[i].Domain.Lats.Length];
             for (int j = 0; j < elevations.Length; j++)
             {
                 elevations[j] = requests[i].Domain.Lats[j] > 1 ? 1 / 0.00649 : 0.0;
             }
             res[i] = new FetchResponse(requests[i], elevations, Enumerable.Repeat(1.0, elevations.Length).ToArray());
         }
         else if (requests[i].Domain.SpatialRegionType == SpatialRegionSpecification.PointGrid || requests[i].Domain.SpatialRegionType == SpatialRegionSpecification.CellGrid)
         {
             double[,] elevations = new double[requests[i].Domain.Lons.Length, requests[i].Domain.Lats.Length];
             for (int j = 0; j < elevations.GetLength(0); j++)
             {
                 for (int k = 0; k < elevations.GetLength(1); k++)
                 {
                     elevations[j, k] = requests[i].Domain.Lats[k] > 1 ? 1 / 0.00649 : 0.0;
                 }
             }
             res[i] = new FetchResponse(requests[i], elevations, new double[requests[i].Domain.Lons.Length, requests[i].Domain.Lats.Length]);
         }
         else
         {
             throw new NotSupportedException("only points and point grid is supported");
         }
     }
     return(res);
 }
Ejemplo n.º 3
0
        public void AddTwoAttributes()
        {
            var response = new FetchResponse();

            response.Attributes.Add(new AttributeValues("http://someattribute", "Value1"));
            response.Attributes.Add(new AttributeValues("http://someOtherAttribute", "Value2"));
        }
Ejemplo n.º 4
0
        public void FetchResponse(
            [Values(0, 1, 2, 3)] short version,
            [Values(0, 1234)] int throttleTime,
            [Values("testTopic")] string topicName,
            [Values(1, 10)] int topicsPerRequest,
            [Values(1, 5)] int totalPartitions,
            [Values(MessageCodec.None, MessageCodec.Gzip, MessageCodec.Snappy)] MessageCodec codec,
            [Values(
                 ErrorCode.NONE,
                 ErrorCode.OFFSET_OUT_OF_RANGE
                 )] ErrorCode errorCode,
            [Values(3)] int messagesPerSet
            )
        {
#if !DOTNETSTANDARD
            if (codec == MessageCodec.Snappy)
            {
                Assert.Inconclusive($"{codec} is only available in .net core");
            }
#endif
            var topics = new List <FetchResponse.Topic>();
            for (var t = 0; t < topicsPerRequest; t++)
            {
                var partitionId = t % totalPartitions;
                var messages    = GenerateMessages(messagesPerSet, (byte)(version >= 2 ? 1 : 0), codec);
                topics.Add(new FetchResponse.Topic(topicName + t, partitionId, _randomizer.Next(), errorCode, messages));
            }
            var response = new FetchResponse(topics, version >= 1 ? TimeSpan.FromMilliseconds(throttleTime) : (TimeSpan?)null);
            var responseWithUpdatedAttribute = new FetchResponse(response.responses.Select(t => new FetchResponse.Topic(t.topic, t.partition_id, t.high_watermark, t.error_code,
                                                                                                                        t.Messages.Select(m => m.Attribute == 0 ? m : new Message(m.Value, m.Key, 0, m.Offset, m.MessageVersion, m.Timestamp)))),
                                                                 response.throttle_time_ms);

            response.AssertCanEncodeDecodeResponse(version, forComparison: responseWithUpdatedAttribute);
        }
Ejemplo n.º 5
0
        public void AddAttributeTwice()
        {
            var response = new FetchResponse();

            response.Attributes.Add(new AttributeValues("http://someattribute", "Value1"));
            response.Attributes.Add(new AttributeValues("http://someattribute", "Value1"));
        }
Ejemplo n.º 6
0
        /// <summary>
        /// FetchResponse => [TopicName [Partition ErrorCode HighwaterMarkOffset MessageSetSize MessageSet]]
        ///  TopicName => string
        ///  Partition => int32
        ///  ErrorCode => int16
        ///  HighwaterMarkOffset => int64
        ///  MessageSetSize => int32
        /// </summary>
        /// <param name="buff"></param>
        /// <returns></returns>
        public static FetchResponse DeserializeFetchResponse(byte[] buff)
        {
            var stream = new MemoryStream(buff);

            stream.Position += 4; // skip body
            var response = new FetchResponse();

            var len = BigEndianConverter.ReadInt32(stream);

            response.Topics = new FetchResponse.TopicFetchData[len];
            for (int t = 0; t < len; t++)
            {
                var topic = new FetchResponse.TopicFetchData();
                response.Topics[t] = topic;
                topic.Topic        = ReadString(stream);
                var len2 = BigEndianConverter.ReadInt32(stream);
                topic.Partitions = new FetchResponse.PartitionFetchData[len2];
                for (int i = 0; i < len2; i++)
                {
                    topic.Partitions[i] = new FetchResponse.PartitionFetchData
                    {
                        Partition           = BigEndianConverter.ReadInt32(stream),
                        ErrorCode           = (ErrorCode)BigEndianConverter.ReadInt16(stream),
                        HighWatermarkOffset = BigEndianConverter.ReadInt64(stream),
                        Messages            = ReadMessageSet(stream).ToArray()
                    }
                }
                ;
            }

            return(response);
        }
        /// <summary>
        /// MANIFOLD use
        /// </summary>
        public FetchResponseWrapper FetchAndGetDetail(string clientId, string topic, int correlationId, int partitionId, long fetchOffset, int fetchSize
                                                      , int maxWaitTime, int minWaitSize)
        {
            FetchResponse response = this.Fetch(clientId,
                                                topic,
                                                correlationId,
                                                partitionId,
                                                fetchOffset,
                                                fetchSize,
                                                maxWaitTime,
                                                minWaitSize);

            if (response == null)
            {
                throw new KafkaConsumeException(string.Format("FetchRequest returned null FetchResponse,fetchOffset={0},leader={1},topic={2},partition={3}",
                                                              fetchOffset, this.Config.Broker, topic, partitionId));
            }
            PartitionData partitionData = response.PartitionData(topic, partitionId);

            if (partitionData == null)
            {
                throw new KafkaConsumeException(string.Format("PartitionData int FetchResponse is null,fetchOffset={0},leader={1},topic={2},partition={3}",
                                                              fetchOffset, this.Config.Broker, topic, partitionId));
            }
            if (partitionData.Error != ErrorMapping.NoError)
            {
                string s = string.Format("Partition data in FetchResponse has error. {0}  {1} fetchOffset={2},leader={3},topic={4},partition={5}"
                                         , partitionData.Error, KafkaException.GetMessage(partitionData.Error)
                                         , fetchOffset, this.Config.Broker, topic, partitionId);
                Logger.Error(s);
                throw new KafkaConsumeException(s, partitionData.Error);
            }
            return(new FetchResponseWrapper(partitionData.GetMessageAndOffsets(), response.Size, response.CorrelationId, topic, partitionId));
        }
Ejemplo n.º 8
0
        private void Store(StoreCommand cmd, List <MailMessage> mails)
        {
            using (var ctx = new MSGorillaMailEntities())
            {
                foreach (var mail in mails)
                {
                    var curMail = ctx.MailMessages.Find(mail.ID);
                    if (cmd.Action == StoreCommand.ActionType.AddFlag)
                    {
                        AddFlags(curMail, cmd.Flags);
                    }
                    else if (cmd.Action == StoreCommand.ActionType.RemoveFlag)
                    {
                        RemoveFlags(curMail, cmd.Flags);
                    }
                    else
                    {
                        SetFlags(curMail, cmd.Flags);
                    }

                    if (cmd.IsSilent == false)
                    {
                        FetchResponse response = new FetchResponse(curMail.SequenceNumber);
                        response.Items.Add(new FetchDataItem(FetchDataItemType.Flags, CreateFlaggedString(curMail)));
                        this.Session.AppendResponse(response);
                    }
                }

                ctx.SaveChanges();
            }
        }
Ejemplo n.º 9
0
        private void HandleResponseErrors(Fetch request, FetchResponse response)
        {
            switch ((ErrorResponseCode)response.Error)
            {
            case ErrorResponseCode.NoError:
                return;

            case ErrorResponseCode.OffsetOutOfRange:
                throw new OffsetOutOfRangeException("FetchResponse indicated we requested an offset that is out of range.  Requested Offset:{0}", request.Offset)
                      {
                          FetchRequest = request
                      };

            case ErrorResponseCode.BrokerNotAvailable:
            case ErrorResponseCode.ConsumerCoordinatorNotAvailableCode:
            case ErrorResponseCode.LeaderNotAvailable:
            case ErrorResponseCode.NotLeaderForPartition:
                throw new InvalidMetadataException("FetchResponse indicated we may have mismatched metadata.  ErrorCode:{0}", response.Error)
                      {
                          ErrorCode = response.Error
                      };

            default:
                throw new KafkaApplicationException("FetchResponse returned error condition.  ErrorCode:{0}", response.Error)
                      {
                          ErrorCode = response.Error
                      };
            }
        }
Ejemplo n.º 10
0
        /// <summary>
        /// Gets the extra data obtained from the response message when authentication is successful.
        /// </summary>
        /// <param name="response">
        /// The response message.
        /// </param>
        /// <returns>A dictionary of profile data; or null if no data is available.</returns>
        protected override Dictionary <string, string> GetExtraData(IAuthenticationResponse response)
        {
            FetchResponse fetchResponse = response.GetExtension <FetchResponse>();

            if (fetchResponse != null)
            {
                var extraData = new Dictionary <string, string>();
                extraData.Add("email", fetchResponse.GetAttributeValue(WellKnownAttributes.Contact.Email));
                extraData.Add("country", fetchResponse.GetAttributeValue(WellKnownAttributes.Contact.HomeAddress.Country));
                extraData.Add("firstName", fetchResponse.GetAttributeValue(WellKnownAttributes.Name.First));
                extraData.Add("lastName", fetchResponse.GetAttributeValue(WellKnownAttributes.Name.Last));
                //extraData.Add("city", fetchResponse.GetAttributeValue(WellKnownAttributes.Contact.HomeAddress.City));
                //extraData.Add("postalcode", fetchResponse.GetAttributeValue(WellKnownAttributes.Contact.HomeAddress.PostalCode));
                //extraData.Add("state", fetchResponse.GetAttributeValue(WellKnownAttributes.Contact.HomeAddress.State));
                //extraData.Add("addressone", fetchResponse.GetAttributeValue(WellKnownAttributes.Contact.HomeAddress.StreetAddressLine1));
                //extraData.Add("addresstwo", fetchResponse.GetAttributeValue(WellKnownAttributes.Contact.HomeAddress.StreetAddressLine2));
                //extraData.Add("birthdate", fetchResponse.GetAttributeValue(WellKnownAttributes.BirthDate.WholeBirthDate));
                //extraData.Add("companyname", fetchResponse.GetAttributeValue(WellKnownAttributes.Company.CompanyName));
                //extraData.Add("jobtitle", fetchResponse.GetAttributeValue(WellKnownAttributes.Company.JobTitle));
                //extraData.Add("gender", fetchResponse.GetAttributeValue(WellKnownAttributes.Person.Gender));
                //extraData.Add("fullname", fetchResponse.GetAttributeValue(WellKnownAttributes.Name.FullName));
                //extraData.Add("mobile", fetchResponse.GetAttributeValue(WellKnownAttributes.Contact.Phone.Mobile));
                //extraData.Add("homepage", fetchResponse.GetAttributeValue(WellKnownAttributes.Contact.Web.Homepage));
                return(extraData);
            }
            return(null);
        }
Ejemplo n.º 11
0
        public void WhenProviderRespondsAuthenticatedAndSuppliesMetdata_ThenMetadataSavedToRepository()
        {
            var fetchResponse = new FetchResponse();

            var createUser = new Mock <CreateUser>(null);
            var getUser    = new Mock <GetUserByClaimId>(null);

            getUser.Setup(ur => ur.Execute(It.IsAny <string>()))
            .Returns <User>(null);

            createUser.Setup(c => c.Execute(It.IsAny <string>()))
            .Returns(new User {
            })
            .Verifiable();

            TestableAuthController authController = GetTestableAuthController(
                OpenIdRelyingPartyBuilder.DefaultParty()
                .ReturnFriendlyName("BillyBaroo")
                .ReturnFetchResponse(fetchResponse)
                .Object,
                new Mock <IFormsAuthentication>().Object,
                createUser.Object,
                getUser.Object);

            authController.SignInResponse();

            createUser.VerifyAll();
        }
Ejemplo n.º 12
0
        private async Task Handle(
            bool withGarden,
            IObserver <FetchResponse> observer,
            CancellationToken cancellationToken,
            int page       = 1,
            int totalPages = 1)
        {
            if (page > totalPages)
            {
                return;
            }

            _logger.LogInformation("Fetching page {0} of {1}", page, totalPages);
            try
            {
                HouseOfferResponse houseOffer = await _httpRetryPolicy.ExecuteAsync(() =>
                                                                                    _houseOfferProvider.GetOffers(cancellationToken, withGarden, page: page)
                                                                                    );

                await _houseOfferRepository.SaveHouseOffer(houseOffer.Offers);

                FetchResponse response = new FetchResponse((int)houseOffer.Paging.ProgressPercentage(),
                                                           FetchStatus.APIRetrieve);
                observer.OnNext(response);
                await Handle(withGarden, observer, cancellationToken, page + 1, (int)houseOffer.Paging.TotalPages);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Skipping page {0} of {1}", page, totalPages);
                FetchResponse response = new FetchResponse(0, FetchStatus.Skipped);
                observer.OnNext(response);
                await Handle(withGarden, observer, cancellationToken, page + 1, totalPages);
            }
        }
Ejemplo n.º 13
0
        internal static UniversalProfile ProfileFromOpenId(ClaimsResponse spprofile, FetchResponse fetchprofile, string claimedId)
        {
            var profile = new UniversalProfile
            {
                Link     = claimedId,
                Id       = claimedId,
                Provider = "openid",
            };

            if (spprofile != null)
            {
                //Fill
                profile.BirthDay    = spprofile.BirthDateRaw;
                profile.DisplayName = spprofile.FullName;
                profile.EMail       = spprofile.Email;
                profile.Name        = spprofile.Nickname;
                profile.Gender      = spprofile.Gender.HasValue ? spprofile.Gender.Value.ToString() : "";
                profile.TimeZone    = spprofile.TimeZone;
                profile.Locale      = spprofile.Language;
            }
            if (fetchprofile != null)
            {
                profile.Name        = fetchprofile.GetAttributeValue(WellKnownAttributes.Name.Alias);
                profile.LastName    = fetchprofile.GetAttributeValue(WellKnownAttributes.Name.Last);
                profile.FirstName   = fetchprofile.GetAttributeValue(WellKnownAttributes.Name.First);
                profile.DisplayName = fetchprofile.GetAttributeValue(WellKnownAttributes.Name.FullName);
                profile.MiddleName  = fetchprofile.GetAttributeValue(WellKnownAttributes.Name.Middle);
                profile.Salutation  = fetchprofile.GetAttributeValue(WellKnownAttributes.Name.Prefix);
                profile.Avatar      = fetchprofile.GetAttributeValue(WellKnownAttributes.Media.Images.Default);
                profile.EMail       = fetchprofile.GetAttributeValue(WellKnownAttributes.Contact.Email);
                profile.Gender      = fetchprofile.GetAttributeValue(WellKnownAttributes.Person.Gender);
                profile.BirthDay    = fetchprofile.GetAttributeValue(WellKnownAttributes.BirthDate.WholeBirthDate);
            }
            return(profile);
        }
Ejemplo n.º 14
0
        public void FetchResponse(
            [Values(0, 1, 2, 3)] short version,
            [Values(0, 1234)] int throttleTime,
            [Values("test", "a really long name, with spaces and punctuation!")] string topicName,
            [Values(1, 10)] int topicsPerRequest,
            [Values(1, 5)] int totalPartitions,
            [Values(
                 ErrorResponseCode.None,
                 ErrorResponseCode.OffsetOutOfRange
                 )] ErrorResponseCode errorCode,
            [Values(3)] int messagesPerSet
            )
        {
            var topics = new List <FetchResponse.Topic>();

            for (var t = 0; t < topicsPerRequest; t++)
            {
                var partitionId = t % totalPartitions;
                var messages    = GenerateMessages(messagesPerSet, (byte)(version >= 2 ? 1 : 0), partitionId);
                topics.Add(new FetchResponse.Topic(topicName + t, partitionId, _randomizer.Next(), errorCode, messages));
            }
            var response = new FetchResponse(topics, version >= 1 ? TimeSpan.FromMilliseconds(throttleTime) : (TimeSpan?)null);

            response.AssertCanEncodeDecodeResponse(version);
        }
Ejemplo n.º 15
0
        public async Task <ServiceResponse <FetchResponse> > getData()
        {
            var path         = _settings.Path;
            var facebookJson = await _ISocialDataService.Read <FacebookRequest>(path + "facebook.txt");

            var instagramJson = await _ISocialDataService.Read <InstagramRequest>(path + "instagram.txt");

            var youtubeJson = await _ISocialDataService.Read <YouTubeRequest>(path + "youtube.txt");

            var r = new FetchResponse();

            r.facebook = new FacebookData()
            {
                Comments = facebookJson.CommentsCount, Likes = facebookJson.LikesCount
            };

            r.instagram = new InstagramData()
            {
                Follows = instagramJson.NumberOfFollowers
            };
            r.youtube = new YouTubeData()
            {
                Views = youtubeJson.NumberOfViews
            };

            var res = new ServiceResponse <FetchResponse>()
            {
                Data = r, Message = "Success", Success = true
            };

            return(res);
        }
Ejemplo n.º 16
0
        public void UnifyExtensionsAsSregWithBothSregAndAX()
        {
            var sregInjected = new ClaimsRequest(DotNetOpenAuth.OpenId.Extensions.SimpleRegistration.Constants.TypeUris.Standard)
            {
                Nickname = DemandLevel.Request,
            };

            this.extensions.Add(sregInjected);
            var axInjected = new FetchRequest();

            axInjected.Attributes.AddOptional(WellKnownAttributes.Contact.Email);
            this.extensions.Add(axInjected);
            var sreg = ExtensionsInteropHelper.UnifyExtensionsAsSreg(this.request);

            Assert.AreSame(sregInjected, sreg);
            Assert.AreEqual(DemandLevel.Request, sreg.Nickname);
            Assert.AreEqual(DemandLevel.NoRequest, sreg.Email);

            var sregResponseInjected = sreg.CreateResponse();

            sregResponseInjected.Nickname = "andy";
            this.request.AddResponseExtension(sregResponseInjected);
            var axResponseInjected = new FetchResponse();

            axResponseInjected.Attributes.Add(WellKnownAttributes.Contact.Email, "*****@*****.**");
            this.request.AddResponseExtension(axResponseInjected);
            ExtensionsInteropHelper.ConvertSregToMatchRequest(this.request);
            var extensions   = this.GetResponseExtensions();
            var sregResponse = extensions.OfType <ClaimsResponse>().Single();

            Assert.AreEqual("andy", sregResponse.Nickname);
            var axResponse = extensions.OfType <FetchResponse>().Single();

            Assert.AreEqual("*****@*****.**", axResponse.GetAttributeValue(WellKnownAttributes.Contact.Email));
        }
Ejemplo n.º 17
0
        /// <summary>
        /// Action Results for Index, uses DotNetOpenAuth for creating OpenId Request with Intuit
        /// and handling response recieved.
        /// </summary>
        /// <returns></returns>
        public RedirectResult Index()
        {
            var openid_identifier = ConfigurationManager.AppSettings["openid_identifier"].ToString();;
            var response          = openid.GetResponse();

            if (response == null)
            {
                // Stage 2: user submitting Identifier
                Identifier id;
                if (Identifier.TryParse(openid_identifier, out id))
                {
                    try
                    {
                        IAuthenticationRequest request = openid.CreateRequest(openid_identifier);
                        FetchRequest           fetch   = new FetchRequest();
                        fetch.Attributes.Add(new AttributeRequest(WellKnownAttributes.Contact.Email));
                        fetch.Attributes.Add(new AttributeRequest(WellKnownAttributes.Name.FullName));
                        request.AddExtension(fetch);
                        request.RedirectToProvider();
                    }
                    catch (ProtocolException ex)
                    {
                        throw ex;
                    }
                }
            }
            else
            {
                if (response.FriendlyIdentifierForDisplay == null)
                {
                    Response.Redirect("/OpenId");
                }

                // Stage 3: OpenID Provider sending assertion response, storing the response in Session object is only for demonstration purpose
                Session["FriendlyIdentifier"] = response.FriendlyIdentifierForDisplay;
                FetchResponse fetch = response.GetExtension <FetchResponse>();
                if (fetch != null)
                {
                    Session["OpenIdResponse"] = "True";
                    Session["FriendlyEmail"]  = fetch.GetAttributeValue(WellKnownAttributes.Contact.Email); // emailAddresses.Count > 0 ? emailAddresses[0] : null;
                    Session["FriendlyName"]   = fetch.GetAttributeValue(WellKnownAttributes.Name.FullName); //fullNames.Count > 0 ? fullNames[0] : null;

                    //get the Oauth Access token for the user from OauthAccessTokenStorage.xml
                    OauthAccessTokenStorageHelper.GetOauthAccessTokenForUser(Session["FriendlyEmail"].ToString(), this);
                }
            }

            string query = Request.Url.Query;

            if (!string.IsNullOrWhiteSpace(query) && query.ToLower().Contains("disconnect=true"))
            {
                Session["accessToken"]       = "dummyAccessToken";
                Session["accessTokenSecret"] = "dummyAccessTokenSecret";
                Session["Flag"] = true;
                return(Redirect("/CleanupOnDisconnect/Index"));
            }

            return(Redirect("/Home/index"));
        }
        string GetFetchValue(FetchResponse fetch, string key)
        {
            string         schema  = "http://schema.openid.net/";
            IList <string> results = fetch.GetAttribute(schema + key).Values;
            string         result  = results.Count > 0 ? results[0] : "";

            return(result);
        }
Ejemplo n.º 19
0
    protected void GetUserDetails(FetchResponse response)
    {
        string fname    = response.GetAttributeValue(WellKnownAttributes.Name.First) ?? "";
        string mname    = response.GetAttributeValue(WellKnownAttributes.Name.Middle) ?? "";
        string lname    = response.GetAttributeValue(WellKnownAttributes.Name.Last) ?? "";
        string Email    = response.GetAttributeValue(WellKnownAttributes.Contact.Email) ?? "";
        string password = string.Empty;
        DA_Registrationdetails objRegistrationDB = new DA_Registrationdetails();
        DO_Registrationdetails objRegistration   = new DO_Registrationdetails();

        //DA_OutLaetMaster.DA_OutLaetMaster outlat = new DA_OutLaetMaster.DA_OutLaetMaster();
        string ip = Request.ServerVariables["HTTP_X_FORWARDED_FOR"];

        if (ip == null)
        {
            ip = Request.ServerVariables["REMOTE_ADDR"];
        }


        DataTable dt = new DataTable();

        objLogin.Username = Email.Trim();;
        objLogin.Password = password.Trim();

        dt = objLoginDB.GetDataSet(objLogin, DA_SKORKEL.DA_Login.Login_1.GmailFBLogin);
        if (dt.Rows.Count == 0)
        {
            Session["GmailLogin"] = "";
            password = GeneratePassword();

            objRegistration.FirstName  = fname;
            objRegistration.MiddleName = mname;
            objRegistration.LastName   = lname;
            objRegistration.UserName   = Email;
            objRegistration.Password   = password;
            objRegistration.UserTypeId = 1;

            Session["GmailLogin"] = objRegistration;
            string gpass  = "******";
            string strmsg = string.Empty;
            byte[] encode = new byte[gpass.Length];
            encode = Encoding.UTF8.GetBytes(gpass);
            strmsg = Convert.ToBase64String(encode);

            objRegistrationDB.AddEditDel_RegistrationDetails(objRegistration, DA_Registrationdetails.RegistrationDetails.Add);
            objRegistration.RegistrationId = objRegistration.RegOutId;

            CustomerLogin(Email, password);
            Response.Redirect("Home.aspx");

            Response.Redirect("SignUp2.aspx?flg=SKL&ID=" + strmsg + "", true);
        }
        else
        {
            CustomerLogin(Email, "");
            Response.Redirect("Home.aspx");
        }
    }
Ejemplo n.º 20
0
        private void addClaimInfo(FetchResponse claim, string identifier)
        {
            Email     = claim.GetAttributeValue(WellKnownAttributes.Contact.Email);
            FirstName = claim.GetAttributeValue(WellKnownAttributes.Name.First) ?? Loc.Dic.PendingFirstName;
            LastName  = claim.GetAttributeValue(WellKnownAttributes.Name.Last) ?? String.Empty;

            IsSignedByProvider = false;
            ClaimedIdentifier  = identifier;
        }
Ejemplo n.º 21
0
        internal static void ProcessAuthenticationChallenge(IAuthenticationRequest idrequest)
        {
            // Verify that RP discovery is successful.
            if (idrequest.IsReturnUrlDiscoverable(ProviderEndpoint.Provider) != RelyingPartyDiscoveryResult.Success)
            {
                idrequest.IsAuthenticated = false;
                return;
            }

            // Verify that the RP is on the whitelist.  Realms are case sensitive.
            string[] whitelist = ConfigurationManager.AppSettings["whitelistedRealms"].Split(';');
            if (Array.IndexOf(whitelist, idrequest.Realm.ToString()) < 0)
            {
                idrequest.IsAuthenticated = false;
                return;
            }

            if (idrequest.IsDirectedIdentity)
            {
                if (HttpContext.Current.User.Identity.IsAuthenticated)
                {
                    idrequest.LocalIdentifier = Util.BuildIdentityUrl();
                    idrequest.IsAuthenticated = true;
                }
                else
                {
                    idrequest.IsAuthenticated = false;
                }
            }
            else
            {
                string userOwningOpenIdUrl = Util.ExtractUserName(idrequest.LocalIdentifier);

                // NOTE: in a production provider site, you may want to only
                // respond affirmatively if the user has already authorized this consumer
                // to know the answer.
                idrequest.IsAuthenticated = userOwningOpenIdUrl == HttpContext.Current.User.Identity.Name;
            }

            if (idrequest.IsAuthenticated.Value)
            {
                // add extension responses here.
                var fetchRequest = idrequest.GetExtension <FetchRequest>();
                if (fetchRequest != null)
                {
                    var fetchResponse = new FetchResponse();
                    if (fetchRequest.Attributes.Contains(RolesAttribute))
                    {
                        // Inform the RP what roles this user should fill
                        // These roles would normally come out of the user database.
                        fetchResponse.Attributes.Add(RolesAttribute, "Member", "Admin");
                    }
                    idrequest.AddResponseExtension(fetchResponse);
                }
            }
        }
Ejemplo n.º 22
0
        public void UnifyExtensionsasSregFromSchemaOpenIdNet()
        {
            var axInjected = new FetchResponse();

            axInjected.Attributes.Add(ExtensionsInteropProviderHelper.TransformAXFormatTestHook(WellKnownAttributes.Name.Alias, AXAttributeFormats.SchemaOpenIdNet), "nate");
            this.extensions.Add(axInjected);
            var sreg = ExtensionsInteropHelper.UnifyExtensionsAsSreg(this.response, true);

            Assert.AreEqual("nate", sreg.Nickname);
        }
Ejemplo n.º 23
0
        public void UnifyExtensionsAsSregFromAXSchemaOrg()
        {
            var axInjected = new FetchResponse();

            axInjected.Attributes.Add(WellKnownAttributes.Name.Alias, "nate");
            this.extensions.Add(axInjected);
            var sreg = ExtensionsInteropHelper.UnifyExtensionsAsSreg(this.response, true);

            Assert.AreEqual("nate", sreg.Nickname);
        }
Ejemplo n.º 24
0
            internal OpenIdRelyingPartyBuilder AddResponseAttribute(string attributeName, string value)
            {
                if (fetchResponse == null)
                {
                    fetchResponse = new FetchResponse();
                }
                fetchResponse.Attributes.Add(attributeName, value);

                return(this);
            }
Ejemplo n.º 25
0
        /// <summary>
        /// Converts the Simple Registration extension response to whatever format the original
        /// attribute request extension came in.
        /// </summary>
        /// <param name="request">The authentication request with the response extensions already added.</param>
        /// <param name="cancellationToken">The cancellation token.</param>
        /// <returns>
        /// A task that completes with the asynchronous operation.
        /// </returns>
        /// <remarks>
        /// If the original attribute request came in as AX, the Simple Registration extension is converted
        /// to an AX response and then the Simple Registration extension is removed from the response.
        /// </remarks>
        internal static async Task ConvertSregToMatchRequestAsync(this Provider.IHostProcessedRequest request, CancellationToken cancellationToken)
        {
            var req             = (Provider.HostProcessedRequest)request;
            var protocolMessage = await req.GetResponseAsync(cancellationToken);

            var response    = protocolMessage as IProtocolMessageWithExtensions;          // negative responses don't support extensions.
            var sregRequest = request.GetExtension <ClaimsRequest>();

            if (sregRequest != null && response != null)
            {
                if (sregRequest.Synthesized)
                {
                    var axRequest = request.GetExtension <FetchRequest>();
                    ErrorUtilities.VerifyInternal(axRequest != null, "How do we have a synthesized Sreg request without an AX request?");

                    var sregResponse = response.Extensions.OfType <ClaimsResponse>().SingleOrDefault();
                    if (sregResponse == null)
                    {
                        // No Sreg response to copy from.
                        return;
                    }

                    // Remove the sreg response since the RP didn't ask for it.
                    response.Extensions.Remove(sregResponse);

                    AXAttributeFormats format = OpenIdExtensionsInteropHelper.DetectAXFormat(axRequest.Attributes.Select(att => att.TypeUri));
                    if (format == AXAttributeFormats.None)
                    {
                        // No recognized AX attributes were requested.
                        return;
                    }

                    var axResponse = response.Extensions.OfType <FetchResponse>().SingleOrDefault();
                    if (axResponse == null)
                    {
                        axResponse = new FetchResponse();
                        response.Extensions.Add(axResponse);
                    }

                    AddAXAttributeValue(axResponse, WellKnownAttributes.BirthDate.WholeBirthDate, format, sregResponse.BirthDateRaw);
                    AddAXAttributeValue(axResponse, WellKnownAttributes.Contact.HomeAddress.Country, format, sregResponse.Country);
                    AddAXAttributeValue(axResponse, WellKnownAttributes.Contact.HomeAddress.PostalCode, format, sregResponse.PostalCode);
                    AddAXAttributeValue(axResponse, WellKnownAttributes.Contact.Email, format, sregResponse.Email);
                    AddAXAttributeValue(axResponse, WellKnownAttributes.Name.FullName, format, sregResponse.FullName);
                    AddAXAttributeValue(axResponse, WellKnownAttributes.Name.Alias, format, sregResponse.Nickname);
                    AddAXAttributeValue(axResponse, WellKnownAttributes.Preferences.TimeZone, format, sregResponse.TimeZone);
                    AddAXAttributeValue(axResponse, WellKnownAttributes.Preferences.Language, format, sregResponse.Language);
                    if (sregResponse.Gender.HasValue)
                    {
                        AddAXAttributeValue(axResponse, WellKnownAttributes.Person.Gender, format, OpenIdExtensionsInteropHelper.GenderEncoder.Encode(sregResponse.Gender));
                    }
                }
            }
        }
Ejemplo n.º 26
0
 /// <summary>
 /// Adds the AX attribute value to the response if it is non-empty.
 /// </summary>
 /// <param name="ax">The AX Fetch response to add the attribute value to.</param>
 /// <param name="typeUri">The attribute type URI in axschema.org format.</param>
 /// <param name="format">The target format of the actual attribute to write out.</param>
 /// <param name="value">The value of the attribute.</param>
 private static void AddAXAttributeValue(FetchResponse ax, string typeUri, AXAttributeFormats format, string value)
 {
     if (!string.IsNullOrEmpty(value))
     {
         string targetTypeUri = OpenIdExtensionsInteropHelper.TransformAXFormat(typeUri, format);
         if (!ax.Attributes.Contains(targetTypeUri))
         {
             ax.Attributes.Add(targetTypeUri, value);
         }
     }
 }
Ejemplo n.º 27
0
            public IOpenIdMessageExtension GetExtension(Type extensionType)
            {
                if (extensionType == typeof(FetchResponse))
                {
                    var response = new FetchResponse();

                    return(response);
                }

                return(null);
            }
Ejemplo n.º 28
0
 public async Task <FetchResponse[]> FetchDataAsync(params FetchRequest[] requests)
 {
     FetchResponse[] res            = new FetchResponse[requests.Length];
     double[]        valuesToReturn = new double[] { 3, 5, 7, 11, 13, 17 }; //prime numbers for future checks
     for (int i = 0; i < res.Length; i++)
     {
         var a = RepeatValuesIntoArray(Array.CreateInstance(typeof(double), requests[i].Domain.GetDataArrayShape()), valuesToReturn[i]);
         res[i] = new FetchResponse(requests[i], a, a);
     }
     return(res);
 }
Ejemplo n.º 29
0
        /// <summary>
        /// Gets the latest offset for a Topic partition.
        /// </summary>
        /// <param name="router">Router used to derive latest offset.</param>
        /// <param name="topic">Topic to determine latest offset for.</param>
        /// <param name="partitionID">Topic partition to determine latest offset for.</param>
        /// <returns>The latest offset for a partition in a topic.</returns>
        public static long LatestOffset(this BrokerRouter router, string topic, int partitionID = 0)
        {
            long offset = 0;

            FetchResponse response = router.Fetch(topic, partitionID);

            if ((object)response != null)
            {
                offset = response.HighWaterMark;
            }

            return(offset);
        }
Ejemplo n.º 30
0
        public void Fetch()
        {
            var request = new FetchRequest();

            request.Attributes.Add(new AttributeRequest(NicknameTypeUri));
            request.Attributes.Add(new AttributeRequest(EmailTypeUri, false, int.MaxValue));

            var response = new FetchResponse();

            response.Attributes.Add(new AttributeValues(NicknameTypeUri, "Andrew"));
            response.Attributes.Add(new AttributeValues(EmailTypeUri, "*****@*****.**", "*****@*****.**"));

            ExtensionTestUtilities.Roundtrip(Protocol.Default, new[] { request }, new[] { response });
        }
Ejemplo n.º 31
0
 private void HandleResponseErrors(Fetch request, FetchResponse response)
 {
     switch ((ErrorResponseCode)response.Error)
     {
         case ErrorResponseCode.NoError:
             return;
         case ErrorResponseCode.OffsetOutOfRange:
             throw new OffsetOutOfRangeException("FetchResponse indicated we requested an offset that is out of range.  Requested Offset:{0}", request.Offset) { FetchRequest = request };
         case ErrorResponseCode.BrokerNotAvailable:
         case ErrorResponseCode.ConsumerCoordinatorNotAvailableCode:
         case ErrorResponseCode.LeaderNotAvailable:
         case ErrorResponseCode.NotLeaderForPartition:
             throw new InvalidMetadataException("FetchResponse indicated we may have mismatched metadata.  ErrorCode:{0}", response.Error) { ErrorCode = response.Error };
         default:
             throw new KafkaApplicationException("FetchResponse returned error condition.  ErrorCode:{0}", response.Error) { ErrorCode = response.Error };
     }
 }
Ejemplo n.º 32
0
        private void FixOffsetRangeError(FetchRequest fetchRequest, FetchResponse response)
        {
            var fetch = fetchRequest.Fetches[0];

            Func<OffsetTime, long> getOffset =
                offsetTime =>
                this.GetTopicOffsetAsync(response.Topic, 1, (int)offsetTime).Result.First(r => r.PartitionId == fetch.PartitionId).Offsets[0];

            var latest = getOffset(OffsetTime.Latest);
            var earliest = getOffset(OffsetTime.Earliest);

            var asked = fetch.Offset;

            if (asked < earliest) Offset = earliest;
            else if (asked > latest) Offset = latest;
        }
Ejemplo n.º 33
0
        private async Task<bool> ProcessResponseAndUpdateOffsetAsync(FetchResponse response, Fetch request, int partitionId)
        {
            if (response == null || response.Messages.Count <= 0)
                return false;

            response.HandleResponseErrors(request);

            foreach (var message in response.Messages)
            {
                await Task.Run(() =>
                {
                    _fetchResponseQueue.Add(message, _disposeToken.Token);//this is a block!!!
                }, _disposeToken.Token);

                if (_disposeToken.IsCancellationRequested) return false;
            }

            var nextOffset = response.Messages.Max(x => x.Meta.Offset) + 1;
            _partitionOffsetIndex.AddOrUpdate(partitionId, i => nextOffset, (i, l) => nextOffset);

            return true;
        }