コード例 #1
0
    void AsyncCallCallback(IAsyncResult result)
    {
        CallState       cs        = (CallState)result.AsyncState;
        Response        data      = cs.client.EndGetUserRoles(result);
        List <string[]> claimData = new List <string[]>();

        foreach (var val in data.Values)
        {
            claimData.Add(new string[1] {
                val
            });
        }
        string[][] retVal = claimData.ToArray();
        TypedAsyncResult <string[][]> queryResult = (TypedAsyncResult <string[][]>)cs.result;

        queryResult.Complete(retVal, false);
    }
コード例 #2
0
        public IAsyncResult BeginExecuteQuery(string query, string[] parameters, AsyncCallback callback, object state)
        {
            ValidateQuery(query, parameters);

            string[][] outputValues = new string[1][];
            switch (query)
            {
            case "getCprNumber":
                AttributeStoreLogger.Debug("looking up cprNumber for user '" + parameters[0] + "'");

                Object cprNo = this.client.Profile(parameters[0], null)["cprNr"];
                if (cprNo == null)
                {
                    AttributeStoreLogger.Debug("CPRNumber, not found");
                    outputValues[0] = new string[1] {
                        null
                    };
                }
                else
                {
                    AttributeStoreLogger.Debug("CPRNumber, found");
                    outputValues[0] = new string[1] {
                        cprNo.ToString()
                    };
                }

                break;

            default:
                throw new AttributeStoreQueryFormatException("The query string is not supported:" + query);
            }

            TypedAsyncResult <string[][]> asyncResult = new TypedAsyncResult <string[][]>(callback, state);

            asyncResult.Complete(outputValues, true);

            return(asyncResult);
        }
コード例 #3
0
        void AsyncQueryCallback(IAsyncResult result)
        {
            TypedAsyncResult <string[][]> queryResult = (TypedAsyncResult <string[][]>)result.AsyncState;

            System.Runtime.Remoting.Messaging.AsyncResult delegateAsyncResult = (System.Runtime.Remoting.Messaging.AsyncResult)result;
            RunQueryDelegate runQueryDelegate = (RunQueryDelegate)delegateAsyncResult.AsyncDelegate;

            string[][] values            = null;
            Exception  originalException = null;

            try
            {
                values = runQueryDelegate.EndInvoke(result);
            }
            /* We don't want exceptions to be thrown from the callback method as these need to be made available to the thread that calls EndExecuteQuery. */
            catch (Exception e)
            {
                originalException = e;
            }

            /* Any exception is stored in query Result and re-thrown when EndExecuteQueryMethod calls TypedAsyncResult<string[][]>.End(..) method. */
            queryResult.Complete(values, false, originalException);
        }
コード例 #4
0
ファイル: OAuthUtil.cs プロジェクト: bbyk/graph.net
        ///<summary>
        /// Begin to authenticate current request synchronously. Returns <c>true</c> if the request is authenticated and <see cref="Session"/> is set; otherwise <c>false</c>.
        ///</summary>
        ///<param name="context">http context to authenticate.</param>
        ///<param name="cb">a callback to call upon operation is completed.</param>
        ///<param name="state">the user state to pass to the callback.</param>
        ///<exception cref="ArgumentNullException"><paramref name="context"/> is null.</exception>
        public IAsyncResult BeginAuthenticateRequest([NotNull] HttpContext context, [CanBeNull] AsyncCallback cb, [CanBeNull] object state)
        {
            if (context == null)
                throw FacebookApi.Nre("context");

            bool saveSession = true;
            var tar = new TypedAsyncResult<bool>(cb, state);
            string code = context.Request.QueryString["code"];
            if (!String.IsNullOrEmpty(code))
                return BeginAuthenticate(code, GetCurrentUrl(context),
                    tar.AsSafe(ar =>
                    {
                        EndAuthenticate(ar);
                        SaveSession(context);

                        tar.Complete(IsAuthenticated, false);
                    }),
                    null);

            ISessionStorage ss = SessionStorage;
            if (ss != null)
            {
                _fbSession = ss.Session;
                if (_fbSession != null
                    && !ss.IsSecure
                    && _fbSession.Signature != GenerateSignature(_fbSession.ToJsonObject()))
                {
                    _fbSession = null;
                }

                saveSession = _fbSession == null;
            }

            if (saveSession)
                SaveSession(context);

            tar.Complete(true);

            return tar;
        }
コード例 #5
0
        public IAsyncResult BeginExecuteQuery(string query, string[] parameters, AsyncCallback callback, object state)
        {
            if (String.IsNullOrEmpty(query))
            {
                throw new AttributeStoreQueryFormatException("No query string.");
            }

            if (parameters == null)
            {
                throw new AttributeStoreQueryFormatException("No query parameter.");
            }

            if (parameters.Length != 1)
            {
                throw new AttributeStoreQueryFormatException("More than one query parameter.");
            }

            string inputString = parameters[0];

            if (inputString == null)
            {
                throw new AttributeStoreQueryFormatException("Query parameter cannot be null.");
            }

            string result = null;

            switch (query)
            {
            case "toUpper":
            {
                result = inputString.ToUpper();
                break;
            }

            case "toLower":
            {
                result = inputString.ToLower();
                break;
            }

            case "base64":
            {
                // MS says we can assume that input string is in UTF-8 form?
                result = Convert.ToBase64String(Encoding.UTF8.GetBytes(inputString));
                break;
            }

            case "trim":
            {
                result = inputString.Trim();
                break;
            }

            case "removeDashes":
            {
                result = inputString.Replace("-", "");
                break;
            }

            case "truncateTo12Chars":
            {
                result = Truncate(inputString, 12);
                break;
            }

            case "truncateTo16Chars":
            {
                result = Truncate(inputString, 16);
                break;
            }

            default:
            {
                throw new AttributeStoreQueryFormatException(String.Format("The query string \"{0}\" is not supported.", query));
            }
            }
            string[][] outputValues = new string[1][];
            outputValues[0]    = new string[1];
            outputValues[0][0] = result;

            TypedAsyncResult <string[][]> asyncResult = new TypedAsyncResult <string[][]>(callback, state);

            asyncResult.Complete(outputValues, true);
            return(asyncResult);
        }
コード例 #6
0
        public IAsyncResult BeginExecuteQuery(string query, string[] parameters, AsyncCallback callback, object state)
        {
            //c:[Type == "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress"]
            //=> issue(store = "AddlevelStore", types = ("groups"), query = "email", param = c.Value);

            if (string.IsNullOrEmpty(query))
            {
                throw new AttributeStoreQueryFormatException("No query string.");
            }

            if (null == parameters)
            {
                throw new AttributeStoreQueryFormatException("No query parameters.");
            }

            if (parameters.Length != 1)
            {
                throw new AttributeStoreQueryFormatException("More than one query parameter.");
            }

            if (!query.Equals("email"))
            {
                throw new AttributeStoreQueryFormatException("The query string is not supported.");
            }

            string inputString = parameters[0];

            if (string.IsNullOrEmpty(inputString))
            {
                throw new AttributeStoreQueryFormatException("Query parameter cannot be null or empty.");
            }

            try
            {
                // Dummy value to illustrate the principle.
                List <string> claimValues = new List <string> {
                    "Group1", "Group2"
                };
                List <string[]> claimData = new List <string[]>();

                // Each claim value is added to its own string array
                foreach (string claimVal in claimValues)
                {
                    claimData.Add(new string[1] {
                        claimVal
                    });
                }

                // The claim value string arrays are added to the string [][] that is returned by the Custom Attribute Store EndExecuteQuery()
                string[][] resultData = claimData.ToArray();

                TypedAsyncResult <string[][]> asyncResult = new TypedAsyncResult <string[][]>(callback, state);
                asyncResult.Complete(resultData, true);
                return(asyncResult);
            }
            catch (Exception ex)
            {
                String innerMess = "";
                if (ex.InnerException != null)
                {
                    innerMess = ex.InnerException.ToString();
                }

                throw new AttributeStoreQueryExecutionException("CAS exception : " + ex.Message + " " + innerMess);
            }
        }
        public IAsyncResult BeginExecuteQuery(string query, string[] parameters, AsyncCallback callback, object state)
        {
            if (String.IsNullOrEmpty(query))
            {
                throw new AttributeStoreQueryFormatException("No query string.");
            }

            if (parameters == null)
            {
                throw new AttributeStoreQueryFormatException("No query parameter.");
            }

            if (parameters.Length != 1)
            {
                throw new AttributeStoreQueryFormatException("More than one query parameter.");
            }

            string inputString = parameters[0];

            if (inputString == null)
            {
                throw new AttributeStoreQueryFormatException("Query parameter cannot be null.");
            }

            List <string> groupNames = new List <string>();

            Trace.Listeners.Add(new TextWriterTraceListener(Console.Out));

            switch (query)
            {
            case "ldapGroups":
            {
                try
                {
                    LdapDirectoryIdentifier ldapDirectoryIdentifier = new LdapDirectoryIdentifier(ldapHost, ldapPort);
                    NetworkCredential       networkCredential       = new NetworkCredential(ldapUser, ldapPassword);
                    LdapConnection          ldapConnection          = new LdapConnection(ldapDirectoryIdentifier, networkCredential, AuthType.Basic);
                    ldapConnection.SessionOptions.ProtocolVersion = 3;

                    // Look for a user based upon the email address. From this we will get the Distinguished Name
                    SearchRequest  userRequest = new SearchRequest(null, "(&(objectClass=dominoperson)(mail=" + inputString + "))", SearchScope.Subtree, new string[] { "cn" });
                    SearchResponse user        = ldapConnection.SendRequest(userRequest) as SearchResponse;
                    if (user.Entries[0] != null)
                    {
                        SearchRequest  request        = new SearchRequest(null, "(member=" + user.Entries[0].DistinguishedName + ")", SearchScope.Subtree, new string[] { "cn", "dominoAccessGroups" });
                        SearchResponse searchResponse = ldapConnection.SendRequest(request) as SearchResponse;

                        foreach (SearchResultEntry entry in searchResponse.Entries)
                        {
                            if (entry.Attributes["dominoAccessGroups"] != null)
                            {
                                groupNames.Add(entry.Attributes["dominoAccessGroups"][0].ToString().Replace("CN=", ""));
                            }
                            List <string> group = new List <string>();
                            groupNames.Add(entry.Attributes["cn"][0] + "");
                        }
                        groupNames = groupNames.Distinct().ToList();
                        Trace.WriteLine(string.Join(", ", groupNames.ToArray()));
                    }
                    else
                    {
                        // No user could be found from the email address
                        throw new AttributeStoreQueryFormatException("No user could be found for the email address '" + inputString + "'.");
                    }
                }
                catch (Exception e)
                {
                    using (EventLog eventLog = new EventLog("Application"))
                    {
                        eventLog.Source = "CustomLdapAttributeStore";
                        eventLog.WriteEntry("Error whilst retrieving groups for user " + inputString + ", " + e.Message + "%n" + e.StackTrace, EventLogEntryType.Error, 101, 1);
                    }
                    // Throw the error up the stack to ensure ADFS is aware that there's a problem
                    throw e;
                }

                break;
            }

            default:
            {
                throw new AttributeStoreQueryFormatException("The query string is not supported.");
            }
            }

            // Convert the results into the correct format to return from this interface
            List <string[]> claimData = new List <string[]>();

            foreach (string name in groupNames)
            {
                claimData.Add(new string[1] {
                    name
                });
            }

            TypedAsyncResult <string[][]> asyncResult = new TypedAsyncResult <string[][]>(callback, state);

            asyncResult.Complete(claimData.ToArray(), true);
            return(asyncResult);
        }
コード例 #8
0
ファイル: FacebookAPI.Async.cs プロジェクト: bbyk/graph.net
        internal IAsyncResult BeginRequest(
            string url,
            HttpVerb httpVerb,
            Dictionary<string, string> args,
            AsyncCallback cb, object state)
        {
            if (args != null && args.Keys.Count > 0 && httpVerb == HttpVerb.Get)
                url = url+ (url.Contains("?") ? "&" : "?") + EncodeDictionary(args);

            var request = (HttpWebRequest)WebRequest.Create(url);
            request.Proxy = Proxy;
            request.Headers.Add(HttpRequestHeader.AcceptLanguage, Culture.IetfLanguageTag.ToLowerInvariant());
            request.Method = httpVerb.ToString();
            var tar = new TypedAsyncResult<ResponseData>(cb, state);

            Action beginGetResp = () => request.BeginGetResponse(tar.AsSafe(gr =>
            {
                HttpWebResponse resp;
                Stream respStm;
                string contentType;
                try
                {
                    resp = (HttpWebResponse)request.EndGetResponse(gr);
                    contentType = ExtractContentType(resp);
                    respStm = resp.GetResponseStream();
                }
                catch (WebException ex)
                {
                    if (ex.Status == WebExceptionStatus.ProtocolError)
                    {
                        resp = (HttpWebResponse)ex.Response;
                        contentType = ExtractContentType(resp);

                        if (contentType == "text/javascript")
                        {
                            respStm = resp.GetResponseStream();
                            goto ok;
                        }
                    }

                    throw TransportError(ex);
                }

                ok: var buf = new byte[4096];
                var ms = new MemoryStream(buf.Length);

                AsyncCallback cbr = null;
                cbr = tar.AsSafe(br =>
                {
                    int cnt = respStm.EndRead(br);
                    if (cnt == 0)
                    {
                        if (!tar.IsCompleted)
                        {
                            ((IDisposable)resp).Dispose();
                            ms.Seek(0, SeekOrigin.Begin);
                            tar.Complete(new ResponseData
                            {
                                Json = Encoding.UTF8.GetString(ms.ToArray()),
                                ContentType = contentType,
                            }, false);
                        }
                    }
                    else
                    {
                        ms.Write(buf, 0, cnt);
                        respStm.BeginRead(buf, 0, buf.Length, cbr, null);
                    }
                }, ex => ((IDisposable)resp).Dispose());

                respStm.BeginRead(buf, 0, buf.Length, cbr, null);
            }), null);

            try
            {
                if (httpVerb == HttpVerb.Post)
                {
                    string postData = EncodeDictionary(args);
                    byte[] postDataBytes = Encoding.UTF8.GetBytes(postData);
                    request.ContentType = "application/x-www-form-urlencoded";
                    request.ContentLength = postDataBytes.Length;

                    request.BeginGetRequestStream(tar.AsSafe(rar =>
                    {
                        Stream rqStm = request.EndGetRequestStream(rar);
                        rqStm.BeginWrite(postDataBytes, 0, postDataBytes.Length, tar.AsSafe(wr =>
                        {
                            rqStm.EndWrite(wr);
                            beginGetResp();
                        }), null);
                    }), null);
                }
                else
                {
                    beginGetResp();
                }
            }
            catch (Exception ex)
            {
                if (!tar.IsCompleted)
                    tar.Complete(true, ex);
            }

            return tar;
        }
コード例 #9
-1
        public void Init(HttpApplication app)
        {
            app.AddOnPostAcquireRequestStateAsync((s, e, cb, state) =>
            {
                HttpContext context = app.Context;

                var tar = new TypedAsyncResult<Identity>(cb, state);
                if (context.Session == null || !context.Request.Url.AbsolutePath.Contains("/Connect"))
                {
                    tar.Complete(true);
                    return tar;
                }

                var util = new OAuthContext(AppId, AppSecret)
                {
                    Culture = CultureInfo.CurrentCulture,
                    ExProcessor = ex => Debug.Write(ex),
                };

                util.SessionStorage = new AspNetSessionStore(context, util);

                util.BeginAuthenticateRequest(context, tar.AsSafe(ar =>
                {
                    util.EndAuthenticateRequest(ar);
                    tar.Complete(new Identity(util), false);
                }), null);
                return tar;
            },
            ar =>
            {
                var ident = TypedAsyncResult<Identity>.End(ar, null);
                if (ident == null)
                    return;

                HttpContext context = app.Context;
                if (!ident.IsAuthenticated)
                {
                    //var @params = new Dictionary<string, string> { { "scope", "user_birthday" } };
                    context.Response.Redirect(ident.AuthContext.GetLoginUrl(context.Request.Url, new LoginParams { ReqPerms = "user_birthday" }), false);
                    context.ApplicationInstance.CompleteRequest();
                    return;
                }

                context.User = new GenericPrincipal(ident, null);
            });
        }