public IAsyncResult BeginExecuteQuery(string query, string[] parameters, AsyncCallback callback, object state)
        {
            #region Input check

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

            if (!query.Contains("<ViewFields>"))
            {
                throw new AttributeStoreQueryFormatException("Query must contain ViewFields clause to indicate which fields should be returned by the query");
            }

            #endregion

            /* Note the usage of TypedAsyncResult class defined in Microsoft.IdentityModel.Threading namespace. */
            AsyncResult queryResult = new TypedAsyncResult<string[][]>(callback, state);

            /* The asynchronous query is being implemented using a delegate. This is to show the asynchronous way of running the query,
             * even though we are reading from a simple text file, which can be done synchronously.
             * You may also use a data access interface that provides an asynchronous way to access the data.
             * For example, the BeginExecuteReader method of System.Data.SqlClient.SqlCommand class asynchronously accesses data from a SQL Server data store. */
            RunQueryDelegate queryDelegate = new RunQueryDelegate(RunQuery);
            queryDelegate.BeginInvoke(query, parameters, new AsyncCallback(AsyncQueryCallback), queryResult);
            return queryResult;
        }
Example #2
0
        ///<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;
        }
Example #3
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);
        }
Example #4
0
 public string[][] EndExecuteQuery(IAsyncResult result)
 {
     return(TypedAsyncResult <string[][]> .End(result));
 }
Example #5
0
    public static T End(IAsyncResult result)
    {
        TypedAsyncResult <T> typedResult = AsyncResult.End <TypedAsyncResult <T> >(result);

        return(typedResult.Data);
    }
Example #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);
        }
Example #8
0
        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;
        }
Example #9
0
        /// <summary>
        /// 
        /// </summary>
        /// <param name="cb"></param>
        /// <param name="state"></param>
        /// <returns></returns>
        /// <exception cref="ObjectDisposedException">The underlying socket has been closed.</exception>
        /// <exception cref="ArgumentNullException">host is null.</exception>
        /// <exception cref="SocketException">An error is encountered when resolving Hostname or connecting.</exception>
        public IAsyncResult BeginLogin(AsyncCallback cb, object state)
        {
            if (_disposed) throw new ObjectDisposedException(GetType().FullName);
            if (_disconnected) throw ErrorWeAreDisconnected();

            var ar = new TypedAsyncResult<LoginResult>(WrapCallback(cb), state);

            string openStream = String.Format("<stream:stream to='{0}' xmlns='jabber:client' xmlns:stream='http://etherx.jabber.org/streams'>", _serverName);
            byte[] buffer = _encoding.GetBytes(openStream);
            _writeArgs.Completed += OnSentOpenStream;
            _writeArgs.SetBuffer(buffer, 0, buffer.Length);
            _writeArgs.UserToken = ar;
            if (!_socket.SendAsync(_writeArgs))
            {
                OnSentOpenStream(_socket, _writeArgs);
            }

            return ar;
        }
Example #10
-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);
            });
        }