public IAsyncResult BeginProcessRequest(HttpContext context, AsyncCallback cb, object extraData)
        {
            m_request = context.Request;
            m_response = context.Response;
            m_queryStringCollection = m_request.QueryString;
            string location = m_queryStringCollection.Get("location");
            string quickDate = m_queryStringCollection.Get("time_scope");
            int categoryId = 1;
            string flags = "PT";
            string sort = "distance-asc";
            string backfill = "further";
            string upcomingEventQueryUri =
                Uri.EscapeUriString(
					String.Format("http://api.eventful.com/rest/events/search?app_key={0}&location={1}&date={2}&keywords=music&page_size=20",
                    m_yahooApiKey,
                    location,
                    quickDate,
                    categoryId,
                    flags,
                    sort,
                    backfill)
                );

            //XElement upcomingEventsXmlResult = XElement.Load(upcomingEventQueryUri);

            m_argList.AddParam("location", String.Empty, location);
            m_argList.AddParam("format", String.Empty, m_queryStringCollection.Get("format"));
            m_argList.AddParam("current-dateTime", String.Empty, DateTime.UtcNow);
            xslt.Transform(upcomingEventQueryUri, m_argList, m_response.Output);
            m_asyncResult = new NuxleusAsyncResult(cb, extraData);
            m_asyncResult.CompleteCall();
            return m_asyncResult;

        }
コード例 #2
0
ファイル: Message.cs プロジェクト: xxjeng/nuxleus
        public void WriteResponseMessage ( XmlWriter writer, string innerXml, NuxleusAsyncResult asyncResult ) {

            using (writer) {
                writer.WriteStartDocument();
                if (m_responseType == ResponseType.REDIRECT) {
                    writer.WriteProcessingInstruction("xml-stylesheet", "type='text/xsl' href='/service/transform/openid-redirect.xsl'");
                }
                writer.WriteStartElement("auth");
                writer.WriteAttributeString("xml:base", "http://dev.amp.fm/");
                writer.WriteAttributeString("status", m_status);
                if (m_responseType == ResponseType.REDIRECT) {
                    writer.WriteElementString("url", "http://dev.amp.fm/");
                }
                if (m_responseType == ResponseType.QUERY_RESPONSE && innerXml != null) {
                    writer.WriteStartElement("response");
                    writer.WriteRaw(innerXml);
                    writer.WriteEndElement();
                }
                writer.WriteEndElement();
                writer.WriteEndDocument();
            }

            asyncResult.CompleteCall();

        }
コード例 #3
0
        public IAsyncResult BeginProcessRequest(HttpContext context, AsyncCallback cb, object extraData) {

            NuxleusAsyncResult result = new NuxleusAsyncResult(cb, extraData);

            HttpRequest request = context.Request;
            m_response = context.Response;
            m_response.ContentType = "text";

            NameValueCollection form = request.Params;

            string id = form.Get("id");
            string vote = form.Get("vote");
            string ip = context.Request.UserHostAddress.ToString();

            try {
                for (int i = 0; i <= form.Count; i++) {
                    this.LogInfo("Form value: {0}", form[i]);
                }
            } catch (Exception e) {
                this.LogInfo(e.Message);
            }

            using (MemoryStream stream = new MemoryStream()) {
                using (StreamWriter sWriter = new StreamWriter(m_response.OutputStream, Encoding.UTF8)) {
                    sWriter.Write("ID: {0} Vote: {1} IP: {2}", id, vote, ip);
                }
            }

            result.CompleteCall();
            return result;
        }
コード例 #4
0
        public IAsyncResult BeginProcessRequest(HttpContext context, AsyncCallback cb, object extraData)
        {
            m_request = context.Request;
            m_response = context.Response;
            m_cookieCollection = context.Request.Cookies;
            m_asyncResult = new NuxleusAsyncResult(cb, extraData);
            bool success = true;

            Dictionary<string, string> cookieDictionary = Nuxleus.Web.Utility.GetCookieValues(m_cookieCollection, out success, sessionCookies.ToArray());

            string ip = m_request.UserHostAddress.ToString();

            string currentUserId = String.Empty;
            if (cookieDictionary.TryGetValue("userid", out currentUserId))
            {
                DeleteAttributesTask task = new DeleteAttributesTask { DomainName = "event", ItemName = m_request.QueryString["eventid"], Attribute = deleteAttributes };
                IResponse response = task.Invoke();

                DeleteAttributesResult result = (DeleteAttributesResult)response.Result;

                SelectTask selectTask = new SelectTask { DomainName = new Domain { Name = "event" }, SelectExpression = String.Format("select * from event where eventcreator = '{0}'", currentUserId) };
                IResponse selectResponse = selectTask.Invoke();

                SelectResult selectResult = (SelectResult)selectResponse.Result;

                List<AwsSdbModel.Attribute> attributes = new List<AwsSdbModel.Attribute>();

                WriteDebugXmlToOutputStream(selectResult.Item);
            }


            m_asyncResult.CompleteCall();
            return m_asyncResult;
        }
コード例 #5
0
        public IAsyncResult BeginProcessRequest (HttpContext context, AsyncCallback cb, object extraData)
        {
            m_asyncResult = new NuxleusAsyncResult(cb, extraData);

            HttpRequest req = context.Request;
            HttpResponse resp = context.Response;

            IList<string> matches = new List<string>();
            string[] tokens = req.Path.Trim('/').ToLower().Split('/');
            string current = Directory.GetCurrentDirectory();
            FindMatch(current, matches, tokens, 0);

            StringBuilder sb = new StringBuilder(String.Format("<html><head/><body><p>Could not find {0}.</p>", HttpUtility.HtmlEncode(req.Path)));

            if (matches.Count != 0)
            {
                sb.Append("<p>We have however found potential match:</p><ul>");
                foreach (string m in matches)
                {
                    sb.Append(String.Format("<li>{0}</li>", HttpUtility.HtmlEncode(m)));
                }

                sb.Append("</ul>");
            }
            sb.Append("<p>Or maybe you'd rather create that resource instead?</p></body></html>");

            resp.Write(sb.ToString());

            // Even if we build a friendly page, this is still a Page Not Found
            // let's not break HTTP
            resp.StatusCode = 404;
            resp.StatusDescription = "Not Found";
            m_asyncResult.CompleteCall();
            return m_asyncResult;
        }
コード例 #6
0
        public IAsyncResult BeginProcessRequest ( HttpContext context, AsyncCallback cb, object extraData ) {

            HttpRequest request = context.Request;
            m_response = context.Response;
            m_statusCode = StatusCode.PENDING;
            m_builder = new StringBuilder();
            m_id = HttpUtility.UrlDecode(request.QueryString["id"]);
            m_message = MessageAttribute.FromMember(m_statusCode);
            NuxleusAsyncResult nuxleusAsyncResult = new NuxleusAsyncResult(cb, extraData);
            m_builder.AppendFormat("<result time='{0}'>", DateTime.Now);
            m_statusQueue = (Dictionary<string, string>)context.Application["as_statusQueue"];

            try {
                m_reader = XmlReader.Create(new StringReader((string)m_statusQueue[m_id]));
                Console.WriteLine("Content of status queue: {0}", (string)m_statusQueue[m_id]);
                nuxleusAsyncResult.CompleteCall();
                return nuxleusAsyncResult;
            } catch (Exception e) {
                m_statusCode = StatusCode.ERROR;
                m_message = e.Message;
                nuxleusAsyncResult.CompleteCall();
                return nuxleusAsyncResult;
            }
        }
コード例 #7
0
        public IAsyncResult BeginProcessRequest (HttpContext context, AsyncCallback cb, object extraData)
        {
            m_logoutSuccessful = false;
            m_returnLocation = "http://dev.amp.fm/";
            m_request = context.Request;
            m_response = context.Response;
            m_cookieCollection = context.Response.Cookies;
            m_asyncResult = new NuxleusAsyncResult(cb, extraData);

            try
            {
                HttpCookie sessionid = m_cookieCollection["sessionid"];
                HttpCookie userid = m_cookieCollection["userid"];
                HttpCookie username = m_cookieCollection["username"];
                HttpCookie name = m_cookieCollection["name"];
                HttpCookie uservalidated = m_cookieCollection["uservalidated"];
                DateTime expires = DateTime.Now.AddDays(-1);

                sessionid.Expires = expires;
                userid.Expires = expires;
                username.Expires = expires;
                uservalidated.Expires = expires;
                name.Expires = expires;

                m_response.Cookies.Add(sessionid);
                m_response.Cookies.Add(userid);
                m_response.Cookies.Add(username);
                m_response.Cookies.Add(name);
                m_response.Cookies.Add(uservalidated);

                m_logoutSuccessful = true;
            }
            catch (Exception e)
            {
                this.LogError(e.Message);
            }


            //Message responseMessage = new Message("redirect", ResponseType.REDIRECT);
            //responseMessage.WriteResponseMessage(XmlWriter.Create(m_response.Output), null, m_asyncResult);
            m_asyncResult.CompleteCall();
            return m_asyncResult;
        }
        public IAsyncResult BeginProcessRequest(HttpContext context, AsyncCallback cb, object extraData)
        {

            HttpRequest request = context.Request;
            Dictionary<string, string> cookies = new Dictionary<string, string>(m_cookieDict);
            m_request = context.Request;
            m_response = context.Response;
            m_cookieCollection = context.Request.Cookies;
            m_asyncResult = new NuxleusAsyncResult(cb, extraData);
            string ip = m_request.UserHostAddress;

            for (var i = 0; i < m_cookieCollection.Count; i++ )
            {
                cookies[m_cookieCollection[i].Name] = m_cookieCollection[i].Value;
            }


            if (ip == "::1" || ip == "127.0.0.1")
                //ip = GetLocalIPAddress();
                ip = "75.169.248.106";

            LatLongLocation location = new LatLongLocation(GetIPLocation(ip));

            NameValueCollection form = request.Form;

            
            //IPLocation.DefaultCity = "Salt Lake City";
            //IPLocation.DefaultCountry = "UNITED STATES";

            //IPLocation location = new IPLocation(ip);

            //Select task = new Select { DomainName = "account", SelectExpression = String.Format("select name from account where itemName() = '{0}'", "0123456") };

            //IResponse response = task.Invoke();
            //TextReader tReader = new StringReader(response.Response);
            //XmlReader reader = XmlReader.Create(tReader);

            XDocument doc = new XDocument(
		new XDeclaration("1.0", "UTF-8", "yes"),
                new XElement(r + "message",
                    new XAttribute("id", Guid.NewGuid()),
                    new XAttribute("date", DateTime.Now.Date),
                    new XAttribute("time", DateTime.Now.TimeOfDay),
                    new XElement(r + "session",
                        new XAttribute("id", cookies["sessionid"]),
                        new XElement(r + "name", cookies["name"]),
                        new XElement(r + "username", cookies["username"]),
                        new XElement(r + "userid", cookies["userid"]),
                        new XElement(r + "uservalidated", cookies["uservalidated"]),
                        new XElement(r + "preferences",
                            new XElement(r + "location",
                                new XElement(r + "country", (cookies["location:country"] == "not-set") ? location.Country : cookies["location:country"]),
                                new XElement(r + "region", (cookies["location:region"] == "not-set") ? location.Region : cookies["location:region"]),
                                new XElement(r + "city", (cookies["location:city"] == "not-set") ? location.City : cookies["location:city"])
                            ),
                            new XElement(r + "address",
                                new XElement(r + "street", (cookies["address:street"] == "not-set") ? location.Country : cookies["address:street"]),
                                new XElement(r + "region", (cookies["address:region"] == "not-set") ? location.Region : cookies["address:region"]),
                                new XElement(r + "city", (cookies["address:city"] == "not-set") ? location.City : cookies["address:city"]),
                                new XElement(r + "postalCode", (cookies["address:postalCode"] == "not-set") ? location.City : cookies["address:postalCode"])
                            )
                        )
                    ),
                    new XElement(r + "geo",
                        new XElement(r + "lat", location.Lat),
                        new XElement(r + "long", location.Long),
                        new XElement(r + "city", location.City),
                        new XElement(r + "country", location.Country),
                        new XElement(r + "region", location.Region),
                        new XElement(r + "postalCode", location.PostalCode),
                        new XElement(r + "areaCode", location.AreaCode),
                        new XElement(r + "ip", ip)
                    )
                )
            );
	    
            string xmlOutput = null;
	    XmlWriterSettings settings = new XmlWriterSettings();
	    settings.Encoding = Encoding.UTF8;
	    
            using (XmlWriter writer = XmlWriter.Create(m_response.Output, settings))
            {
		doc.Save(writer);
                writer.Flush();
            }
            m_asyncResult.CompleteCall();
            return m_asyncResult;
        }
        public IAsyncResult BeginProcessRequest(HttpContext context, AsyncCallback cb, object extraData)
        {
            m_request = context.Request;
            m_response = context.Response;
            m_cookieCollection = context.Request.Cookies;
            m_asyncResult = new NuxleusAsyncResult(cb, extraData);
            HttpCookie sessionid = m_cookieCollection["sessionid"];
            HttpCookie userid = m_cookieCollection["userid"];
            HttpCookie username = m_cookieCollection["username"];
            HttpCookie name = m_cookieCollection["name"];
            HttpCookie uservalidated = m_cookieCollection["uservalidated"];

            string ip = m_request.UserHostAddress.ToString();

            NameValueCollection form = m_request.Form;
            m_returnLocation = form.Get("return_url");
            string eventname = form.Get("name");
            string description = form.Get("description");
            //string location = form.Get("location");
            string venue = form.Get("venue");
            string genre = form.Get("genre");
            string startdate = form.Get("startdate");
            string starttime = form.Get("starttime");
            string endtime = form.Get("endtime");
            string tags = form.Get("tags");
            string eventid = Guid.NewGuid().ToString();

            List<AwsSdbModel.Attribute> attributes = new List<AwsSdbModel.Attribute>();
            attributes.Add(new AwsSdbModel.Attribute { Name = "name", Value = eventname });
            attributes.Add(new AwsSdbModel.Attribute { Name = "description", Value = description });
            attributes.Add(new AwsSdbModel.Attribute { Name = "venue", Value = venue });
            attributes.Add(new AwsSdbModel.Attribute { Name = "genre", Value = genre });
            attributes.Add(new AwsSdbModel.Attribute { Name = "startdate", Value = startdate });
            attributes.Add(new AwsSdbModel.Attribute { Name = "starttime", Value = starttime });
            attributes.Add(new AwsSdbModel.Attribute { Name = "endtime", Value = endtime });
            attributes.Add(new AwsSdbModel.Attribute { Name = "tags", Value = tags });
            attributes.Add(new AwsSdbModel.Attribute { Name = "eventid", Value = eventid });
            attributes.Add(new AwsSdbModel.Attribute { Name = "eventcreator", Value = userid.Value });

            PutAttributesTask task = new PutAttributesTask { DomainName = new Domain { Name = "event" }, Item = new Item { ItemName = eventid, Attribute = attributes } };
            IResponse response = task.Invoke();

            PutAttributesResult result = (PutAttributesResult)response.Result;
            WriteDebugXmlToOutputStream(attributes);
            m_asyncResult.CompleteCall();
            return m_asyncResult;
        }
コード例 #10
0
        public IAsyncResult BeginProcessRequest ( HttpContext context, AsyncCallback cb, object extraData ) {

            m_stopwatch.Start();

            FileInfo fileInfo = new FileInfo(context.Request.MapPath(context.Request.CurrentExecutionFilePath));
            this.LogDebug("File Date: {0}; File Length: {1}", fileInfo.LastWriteTimeUtc, fileInfo.Length);
            m_CONTENT_IS_MEMCACHED = false;
            m_USE_MEMCACHED = false;
            m_httpContext = context;
            m_returnOutput = true;
            m_httpMethod = m_httpContext.Request.HttpMethod;
            m_memcachedClient = (Client)context.Application["memcached"];
            m_encoding = (UTF8Encoding)context.Application["encoding"];
            m_queueClient = (QueueClient)context.Application["queueclient"];
            m_hashkey = (string)context.Application["hashkey"];
            m_xmlServiceOperationManager = (XPathServiceOperationManager)context.Application["xmlServiceOperationManager"];
            m_xslTransformationManager = (XsltTransformationManager)context.Application["xslTransformationManager"];
            m_transform = m_xslTransformationManager.Transform;
            m_xsltParams = (Hashtable)context.Application["globalXsltParams"];
            m_transformContext = new Transform.Context(context, m_hashAlgorithm, (string)context.Application["hashkey"], fileInfo, (Hashtable)m_xsltParams.Clone(), fileInfo.LastWriteTimeUtc, fileInfo.Length);
            m_namedXsltHashtable = (Hashtable)context.Application["namedXsltHashtable"];
            m_xmlSourceETagDictionary = m_xmlServiceOperationManager.XmlSourceETagDictionary;
            m_xmlReaderDictionary = m_xmlServiceOperationManager.XmlReaderDictionary;
            m_context = new Context(context, m_hashAlgorithm, m_hashkey, fileInfo, fileInfo.LastWriteTimeUtc, fileInfo.Length);
            this.LogDebug("File Date: {0}; File Length: {1}", m_context.RequestXmlFileInfo.LastWriteTimeUtc, m_context.RequestXmlFileInfo.Length);
            m_nuxleusAsyncResult = new Nuxleus.Core.NuxleusAsyncResult(cb, extraData);
            m_callback = cb;
            m_nuxleusAsyncResult.m_context = context;
            m_builder = new StringBuilder();
            m_CONTENT_IS_MEMCACHED = false;
            m_USE_MEMCACHED = (bool)context.Application["usememcached"];
            Uri requestUri = new Uri(m_context.RequestUri);
            m_requestHashcode = m_context.GetRequestHashcode(true).ToString();
            m_lastModifiedKey = String.Format("LastModified:{0}", m_context.RequestUri.GetHashCode());
            m_lastModifiedDate = String.Empty;
            m_request = new TransformRequest();
            m_response = new TransformResponse();
            Guid requestGuid = Guid.NewGuid();
            m_request.ID = requestGuid;

            
            context.Response.ContentType = "text/xml";

            IEnumerator headers = context.Request.Headers.GetEnumerator();
            for (int i = 0; headers.MoveNext(); i++) {
                string local = context.Request.Headers.AllKeys[i].ToString();
                this.LogDebug("KeyName: {0}, KeyValue: {1}", local, context.Request.Headers[local]);
            }
            bool hasXmlSourceChanged = m_xmlServiceOperationManager.HasXmlSourceChanged(m_context.RequestXmlETag, requestUri);

            //if (m_USE_MEMCACHED) {

            //    string obj = (string)m_memcachedClient.Get(m_context.GetRequestHashcode(true).ToString());

            //    if (obj != null && !hasXmlSourceChanged) {
            //        m_response.TransformResult = (string)obj;
            //        m_CONTENT_IS_MEMCACHED = true;
            //        if ((bool)context.Application["debug"]) {
            //            context.Response.ContentType = "text";
            //        }
            //    } else {
            //        //m_writer = new StringWriter(m_builder);
            //        m_CONTENT_IS_MEMCACHED = false;
            //    }
            //} else {
            //    m_writer = new StringWriter(m_builder);
            //}

            m_writer = new StringWriter(m_builder);

            try {

                switch (m_httpMethod) {
                    case "GET":
                    case "HEAD":
                    case "POST": {                     
                            string name = String.Format("Name: {0}", context.Request.QueryString["name"]);
                            this.LogDebug("QueryString Length: {0}", context.Request.QueryString.Count);
                            this.LogDebug(name);
                            this.LogDebug("If-None-Match: {0}, RequestHashCode: {1}", context.Request.Headers["If-None-Match"], m_requestHashcode);
                            this.LogDebug(context.Request.Path);
                            if (context.Request.Headers["If-None-Match"] == m_requestHashcode) {
                                object lastModified;
                                this.LogDebug("They matched.");
                                this.LogDebug("Use memcached: {0}, KeyExists: {1}, XmlSource Changed: {2}", m_USE_MEMCACHED, m_memcachedClient.TryGet(m_lastModifiedKey, out lastModified), hasXmlSourceChanged);
                                this.LogDebug("Last Modified Key Value: {0}", m_lastModifiedKey);
                                if (m_USE_MEMCACHED && m_memcachedClient.TryGet(m_lastModifiedKey, out lastModified) && !hasXmlSourceChanged)
                                {
                                    m_lastModifiedDate = (string)m_memcachedClient.Get(m_lastModifiedKey);
                                    this.LogDebug("Last Modified Date: {0}", m_lastModifiedDate);
                                    if (context.Request.Headers["If-Modified-Since"] == m_lastModifiedDate) {

                                        context.Response.StatusCode = 304;
                                        m_returnOutput = false;
                                        goto CompleteCall;
                                    } else {
                                        goto Process;
                                    }
                                } else if (m_CONTENT_IS_MEMCACHED) {
                                    goto CompleteCall;
                                } else {
                                    goto Process;
                                }
                            } else {
                                this.LogDebug("Headers do not match.  Beginning transformation process...");
                                m_returnOutput = true;
                                goto Process;
                            }
                        }
                    case "PUT": {
                            goto CompleteCall;
                        }
                    case "DELETE": {
                            goto CompleteCall;
                        }
                    default: {
                            goto CompleteCall;
                        }
                }

            } catch (Exception ex) {
                m_exception = ex;
                WriteError();
                goto CompleteCall;
            }
        Process:
            try {
                this.LogDebug("Processing Transformation");
                this.LogDebug("Request XML ETag Value: {0}, Request URI: {1}", m_context.RequestXmlETag, requestUri);

                XPathNavigator navigator = m_xmlServiceOperationManager.GetXPathNavigator(m_context.RequestXmlETag, requestUri);
                //if (initialReader == null) {
                //    initialReader = reader;
                //} else {
                //    this.LogDebug("XmlReaders are the same object: {0}", initialReader.Equals(reader));
                //}
                //this.LogDebug("XML Reader Value: {0}", reader.ReadOuterXml());
                //this.LogDebug("XML Reader Hash: {0}", reader.GetHashCode());
                XPathServiceOperationNavigator serviceOperationReader = new XPathServiceOperationNavigator(context, m_context, m_transformContext, navigator, m_request, m_response, m_xslTransformationManager);
                m_response = serviceOperationReader.Process();

            } catch (Exception e) {
                this.LogDebug("Error: {0} in transformation.", e.Message);
                m_exception = e;
                WriteError();
            }

            goto CompleteCall;

        CompleteCall:
            this.LogDebug("CompleteCall reached");
            if (m_lastModifiedDate == String.Empty) {
                m_lastModifiedDate = DateTime.UtcNow.ToString("r");
            }
            context.Response.AppendHeader("Cache-Control", "max-age=86400");
            context.Response.AddHeader("Last-Modified", m_lastModifiedDate);
            context.Response.AddHeader("ETag", String.Format("\"{0}\"", m_requestHashcode));
            m_nuxleusAsyncResult.CompleteCall();
            return m_nuxleusAsyncResult;
        }
コード例 #11
0
        public IAsyncResult BeginProcessRequest (HttpContext context, AsyncCallback cb, object extraData) {
            m_asyncResult = new NuxleusAsyncResult(cb, extraData);

            using (XmlWriter writer = XmlWriter.Create(context.Response.Output)) {
                bool useMemcached = (bool)context.Application["usememcached"];
                MemcachedClient client = (MemcachedClient)context.Application["memcached"];
                HttpCookieCollection cookieCollection = context.Request.Cookies;
                String hostAddress = context.Request.UserHostAddress;
                LatLongLocation location;
                String guid = "not-set";
                String openid = "not-set";

                if (hostAddress == "127.0.0.1") {
                    //hostAddress = Dns.GetHostAddresses(Dns.GetHostName()).GetValue(0).ToString();
                    hostAddress = "66.93.224.237";
                }

                if (context.Request.QueryString.Count > 0) {
                    if (context.Request.QueryString.Get("ip") != null) {
                        hostAddress = context.Request.QueryString.Get("ip");
                    }
                }

                if (useMemcached && client != null) {
                    if (client.KeyExists(hostAddress)) {
                        location = new LatLongLocation(((String)client.Get(hostAddress)).Split(new char[] { '|' }));
                    } else {
                        location = new LatLongLocation(GetIPLocation(hostAddress));
                        client.Add(hostAddress, LatLongLocation.ToDelimitedString("|", location));
                    }
                } else {
                    location = new LatLongLocation(GetIPLocation(hostAddress));
                }


                if (cookieCollection.Count > 0) {
                    try {
                        guid = cookieCollection.Get("guid").Value;
                        openid = cookieCollection.Get("openid").Value;
                    } catch (Exception e) {
                        Console.WriteLine(e.Message);
                    }
                }

                writer.WriteStartDocument();
                writer.WriteStartElement("message", "http://nuxleus.com/message/response");
                writer.WriteStartElement("session");
                writer.WriteStartAttribute("session-id");
                writer.WriteString(guid);
                writer.WriteEndAttribute();
                writer.WriteStartAttribute("openid");
                writer.WriteString(openid);
                writer.WriteEndAttribute();
                writer.WriteEndElement();
                writer.WriteStartElement("request-date");
                writer.WriteString(DateTime.Now.ToLongDateString());
                writer.WriteEndElement();
                writer.WriteStartElement("request-guid");
                writer.WriteString(Guid.NewGuid().ToString());
                writer.WriteEndElement();
                writer.WriteStartElement("geo");
                writer.WriteStartElement("city");
                writer.WriteString(location.City);
                writer.WriteEndElement();
                writer.WriteStartElement("country");
                writer.WriteString(location.Country);
                writer.WriteEndElement();
                writer.WriteStartElement("lat");
                writer.WriteString(location.Lat);
                writer.WriteEndElement();
                writer.WriteStartElement("long");
                writer.WriteString(location.Long);
                writer.WriteEndElement();
                writer.WriteEndElement();

                // Begin navigation section

                //IEnumerator pathEnumerator = context.Request.FilePath.Split(new char[] { '/' }).GetEnumerator();

                writer.WriteStartElement("navigation");
                writer.WriteStartElement("path");
                writer.WriteElementString("Home", "/");
                writer.WriteElementString("Profile", "./profile");
                //for (int i = 0; pathEnumerator.MoveNext(); i++)
                //{
                //    writer.WriteElementString("path", ((string)pathEnumerator.Current));
                //}
                writer.WriteEndElement();
                writer.WriteStartElement("member");
                writer.WriteElementString("blog", "./blog");
                writer.WriteElementString("event", "./event");
                writer.WriteEndElement();
                writer.WriteEndElement();

                writer.WriteEndElement();
                writer.WriteEndDocument();
            }
            m_asyncResult.CompleteCall();
            return m_asyncResult;
        }
        public IAsyncResult BeginProcessRequest(HttpContext context, AsyncCallback cb, object extraData) {
            m_request = context.Request;
            m_response = context.Response;
            m_cookieCollection = context.Response.Cookies;
            m_asyncResult = new NuxleusAsyncResult(cb, extraData);
            HttpCookie c_sessionid = new HttpCookie("sessionid");
            HttpCookie c_userid = new HttpCookie("userid");
            HttpCookie c_username = new HttpCookie("username");
            HttpCookie c_name = new HttpCookie("name");
            HttpCookie c_validated = new HttpCookie("uservalidated");
            DateTime expires = DateTime.Now.AddDays(1);

            c_sessionid.Expires = expires;
            c_userid.Expires = expires;
            c_username.Expires = expires;
            c_name.Expires = expires;
            c_validated.Expires = expires;

            string ip = m_request.UserHostAddress.ToString();

            NameValueCollection form = m_request.Form;
            m_returnLocation = form.Get("return_url");
            string name = form.Get("name");
            string userid = form.Get("email").GetHashCode().ToString();
            string username = form.Get("username");
            string password = form.Get("password");
            string email = form.Get("email");
            string user_time_zone = form.Get("user[time_zone]");
            string user_url = form.Get("user[url]");
            string user_description = form.Get("user[description]");
            string user_location = form.Get("user[location]");
            string user_lang = form.Get("user[lang]");
            string sessionid = Guid.NewGuid().ToString();

            string myuserid = MD5.Create().ComputeHash(Encoding.UTF8.GetBytes(String.Format("{0}:{1}:{2}", name, Guid.NewGuid(), email).ToCharArray())).ToString();

            c_sessionid.Value = sessionid;
            c_userid.Value = userid;
            c_username.Value = username;
            c_name.Value = name;
            c_validated.Value = "true";

            m_cookieCollection.Add(c_sessionid);
            m_cookieCollection.Add(c_userid);
            m_cookieCollection.Add(c_username);
            m_cookieCollection.Add(c_name);
            m_cookieCollection.Add(c_validated);


            List<AwsSdbModel.Attribute> attributes = new List<AwsSdbModel.Attribute>();
            attributes.Add(new AwsSdbModel.Attribute {
                Name = "name",
                Value = name
            });
            attributes.Add(new AwsSdbModel.Attribute {
                Name = "username",
                Value = username
            });
            attributes.Add(new AwsSdbModel.Attribute {
                Name = "password",
                Value = password
            });
            attributes.Add(new AwsSdbModel.Attribute {
                Name = "email",
                Value = email
            });
            attributes.Add(new AwsSdbModel.Attribute {
                Name = "user_time_zone",
                Value = user_time_zone
            });
            attributes.Add(new AwsSdbModel.Attribute {
                Name = "user_url",
                Value = user_url
            });
            attributes.Add(new AwsSdbModel.Attribute {
                Name = "user_description",
                Value = user_description
            });
            attributes.Add(new AwsSdbModel.Attribute {
                Name = "user_location",
                Value = user_location
            });
            attributes.Add(new AwsSdbModel.Attribute {
                Name = "user_lang",
                Value = user_lang
            });
            attributes.Add(new AwsSdbModel.Attribute {
                Name = "session_id",
                Value = sessionid
            });

            PutAttributesTask task = new PutAttributesTask {
                DomainName = new Domain {
                    Name = "account"
                },
                Item = new Item {
                    ItemName = myuserid,
                    Attribute = attributes
                }
            };

            IResponse response = task.Invoke();

            m_asyncResult.CompleteCall();
            return m_asyncResult;
        }
コード例 #13
0
        public IAsyncResult BeginProcessRequest(HttpContext context, AsyncCallback cb, object extraData)
        {
            FileInfo fileInfo = new FileInfo(context.Request.MapPath(context.Request.CurrentExecutionFilePath));
            m_CONTENT_IS_MEMCACHED = false;
            m_USE_MEMCACHED = false;
            m_context = context;
            m_httpMethod = m_context.Request.HttpMethod;
            m_memcachedClient = (Client)context.Application["memcached"];
            m_queueClient = (QueueClient)context.Application["queueclient"];
            m_xslTransformationManager = (XsltTransformationManager)context.Application["xslTransformationManager"];
            m_transform = m_xslTransformationManager.Transform;
            m_xsltParams = (Hashtable)context.Application["globalXsltParams"];
            m_namedXsltHashtable = (Hashtable)context.Application["namedXsltHashtable"];
            m_transformContext = new Transform.Context(context, m_hashAlgorithm, (string)context.Application["hashkey"], fileInfo, (Hashtable)m_xsltParams.Clone(), fileInfo.LastWriteTimeUtc, fileInfo.Length);
            m_transformAsyncResult = new NuxleusAsyncResult(cb, extraData);
            m_callback = cb;
            m_transformAsyncResult.m_context = context;
            m_builder = new StringBuilder();
            m_CONTENT_IS_MEMCACHED = false;
            m_USE_MEMCACHED = (bool)context.Application["usememcached"];

            bool hasXmlSourceChanged = m_xslTransformationManager.HasXmlSourceChanged(m_transformContext.RequestXmlETag);
            bool hasBaseXsltSourceChanged = m_xslTransformationManager.HasBaseXsltSourceChanged();

            if (m_USE_MEMCACHED)
            {

                string obj = (string)m_memcachedClient.Get(m_transformContext.GetRequestHashcode(true));

                if (obj != null && !(hasXmlSourceChanged || hasBaseXsltSourceChanged) && !(m_context.Request.CurrentExecutionFilePath.StartsWith("/service/session")  && !(m_context.Request.CurrentExecutionFilePath.StartsWith("/service/geo"))))
                {
                    m_builder.Append(obj);
                    m_CONTENT_IS_MEMCACHED = true;
                    if ((bool)context.Application["debug"])
                        context.Response.ContentType = "text";
                    else
                        context.Response.ContentType = "text/xml";
                }
                else
                {
                    m_writer = new StringWriter(m_builder);
                    m_CONTENT_IS_MEMCACHED = false;
                }
            }
            else
            {
                m_writer = new StringWriter(m_builder);
            }

            //if ((bool)context.Application["debug"])
            //{
            //    context.Response.Write("<debug>");
            //    context.Response.Write("<file-info>");
            //    context.Response.Write("Has Xml Changed: " + hasXmlSourceChanged + ":" + m_transformContext.RequestXmlETag + "<br/>");
            //    context.Response.Write("Has Xslt Changed: " + hasBaseXsltSourceChanged + "<br/>");
            //    context.Response.Write("Xml ETag: " + m_transformContext.GetRequestHashcode(true) + "<br/>");
            //    context.Response.Write("XdmNode Count: " + m_xslTransformationManager.GetXdmNodeHashtableCount() + "<br/>");
            //    context.Response.Write("</file-info>");
            //    context.Application["debugOutput"] = (string)("<DebugOutput>" + WriteDebugOutput(m_transformContext, m_xslTransformationManager, new StringBuilder(), m_CONTENT_IS_MEMCACHED).ToString() + "</DebugOutput>");
            //    context.Response.Write("</debug>");
            //}

            try
            {

                switch (m_httpMethod)
                {
                    case "GET":
                    case "HEAD":
                        {
                            if (m_CONTENT_IS_MEMCACHED)
                            {
                                m_transformAsyncResult.CompleteCall();
                                return m_transformAsyncResult;
                            }
                            else
                            {
                                try
                                {
                                    string file = m_context.Request.FilePath;
                                    string baseXslt;

                                    if (file.EndsWith("index.page"))
                                    {
                                        baseXslt = "precompile-atomictalk";
                                    }
                                    else if (file.EndsWith("service.op"))
                                        baseXslt = "base";
                                    else
                                        baseXslt = m_xslTransformationManager.BaseXsltName;

                                    //m_transform.BeginTransformProcess(m_transformContext, context, m_xslTransformationManager, m_writer, baseXslt, m_transformAsyncResult);
                                    return m_transformAsyncResult;
                                }
                                catch (Exception e)
                                {
                                    m_exception = e;
                                    WriteError();
                                    m_transformAsyncResult.CompleteCall();
                                    return m_transformAsyncResult;
                                }
                            }
                        }
                    case "PUT":
                        {
                            
                            return m_transformAsyncResult;
                        }
                    case "POST":
                        {
                            return m_transformAsyncResult;
                        }
                    case "DELETE":
                        {
                            return m_transformAsyncResult;
                        }
                    default:
                        {
                            return m_transformAsyncResult;
                        }
                }

            }
            catch (Exception ex)
            {
                m_exception = ex;
                WriteError();
                m_transformAsyncResult.CompleteCall();
                return m_transformAsyncResult;
            }
        }
コード例 #14
0
        private void ProcessRequests ( NuxleusAsyncResult asyncResult ) {

            int queryArrayLength = m_httpRequestArrayLength;
            TextWriter logWriter = m_logWriter;
            bool DEBUG = m_DEBUG;
            List<long> elaspedTimeList = m_elapsedTimeList;

            Encoding encoding = Encoding.UTF8;

            foreach (string r in m_httpRequestArray) {
                Stopwatch stopwatch = new Stopwatch();
                if (DEBUG) {
                    stopwatch.Start();
                }
                string requestString = r;
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(requestString);
                request.Timeout = 10000;
                request.KeepAlive = m_pipelineRequests;
                request.Pipelined = m_pipelineRequests;

                if (!m_runSynchronously) {
                    new AsyncHttpRequest(request, logWriter, DEBUG, stopwatch,
                            delegate( Stream stream, System.Diagnostics.Stopwatch myStopwatch ) {
                                //logWriter.WriteLine("The stopwatch objects are the same: {0}", stopwatch.Equals(myStopwatch));
                                myStopwatch.Stop();
                                long elapsedTime = stopwatch.ElapsedMilliseconds;
                                elaspedTimeList.Add(elapsedTime);
                                myStopwatch.Reset();
                                if (DEBUG) {
                                    logWriter.WriteLine("Current thread id: {0} for current request: {1}", Thread.CurrentThread.ManagedThreadId, requestString);
                                    logWriter.WriteLine("KeepAlive connection? {0}", request.KeepAlive);
                                    logWriter.WriteLine("Pipelined request? {0}", request.Pipelined);
                                }

                                try {
                                    using (stream) {
                                        StreamReader reader = new StreamReader(stream);
                                        m_responseStreamDictionary.Add(requestString.GetHashCode(), new MemoryStream(encoding.GetBytes(reader.ReadToEnd())));
                                    }
                                } catch (Exception e) {
                                    Console.WriteLine("Exception: {0}", e.Message);
                                }

                                if (m_responseStreamDictionary.Count == queryArrayLength) {
                                    if (DEBUG) {
                                        logWriter.WriteLine("Elapsed time of this request:\t {0}ms", elapsedTime);
                                        logWriter.WriteLine("Completing call.");
                                    }
                                    asyncResult.CompleteCall();
                                } else {
                                    if (DEBUG) {
                                        logWriter.WriteLine("Elapsed time of this request:\t {0}ms", elapsedTime);
                                        logWriter.WriteLine("Continuing process...");
                                    }
                                }

                            });
                } else {

                    using (Stream stream = request.GetResponse().GetResponseStream()) {
                        StreamReader reader = new StreamReader(stream);
                        m_responseStreamDictionary.Add(requestString.GetHashCode(), new MemoryStream(encoding.GetBytes(reader.ReadToEnd())));
                    }

                    stopwatch.Stop();
                    long elapsedTime = stopwatch.ElapsedMilliseconds;
                    elaspedTimeList.Add(elapsedTime);
                    stopwatch.Reset();

                    if (DEBUG) {
                        logWriter.WriteLine("Current thread id: {0} for current request: {1}", Thread.CurrentThread.ManagedThreadId, requestString);
                        logWriter.WriteLine("KeepAlive connection? {0}", request.KeepAlive);
                        logWriter.WriteLine("Pipelined request? {0}", request.Pipelined);
                        logWriter.WriteLine("Elapsed time of this request:\t {0}ms", elapsedTime);
                    }

                    if (m_responseStreamDictionary.Count == queryArrayLength) {
                        if (DEBUG) {
                            logWriter.WriteLine("Completing call.");
                        }
                        asyncResult.CompleteCall();
                    } else {
                        if (DEBUG) {
                            logWriter.WriteLine("Continue process");
                        }
                    }
                }
            }
        }
        public IAsyncResult BeginProcessRequest(HttpContext context, AsyncCallback cb, object extraData)
        {
            m_request = context.Request;
            m_response = context.Response;
            m_cookieCollection = context.Request.Cookies;
            m_asyncResult = new NuxleusAsyncResult(cb, extraData);
            HttpCookie sessionid = m_cookieCollection["sessionid"];
            HttpCookie userid = m_cookieCollection["userid"];
            HttpCookie username = m_cookieCollection["username"];
            HttpCookie name = m_cookieCollection["name"];
            HttpCookie uservalidated = m_cookieCollection["uservalidated"];

            string ip = m_request.UserHostAddress.ToString();

            NameValueCollection form = m_request.Form;
            m_returnLocation = form.Get("return-url");
            //string collection_id = form.Get("collection-id");
            string collection_name = form.Get("collection-name");
            string collection_id = Guid.NewGuid().ToString();
            string path = m_request.MapPath(String.Format("/member/{0}/media/{1}", userid.Value, collection_id));

            if (!Directory.Exists(path))
            {
                DirectoryInfo directory = Directory.CreateDirectory(path);
            }

            List<AwsSdbModel.Attribute> attributes = new List<AwsSdbModel.Attribute>();
            attributes.Add(new AwsSdbModel.Attribute { Name = "CollectionName", Value = collection_name });
            attributes.Add(new AwsSdbModel.Attribute { Name = "CollectionOwner", Value = userid.Value });

            PutAttributesTask task = new PutAttributesTask { 
                DomainName = new Domain {
                    Name = "collections" }, 
                    Item = new Item { 
                        ItemName = collection_id,
                        Attribute = attributes 
                    } 
            };
            IResponse response = task.Invoke();
            PutAttributesResult result = (PutAttributesResult)response.Result;
            foreach (string header in response.Headers)
            {
                m_response.Write(String.Format("ResponseHeader: {0}: {1}", header, response.Headers[header]));
            }
            //m_response.Write(result.Metadata.RequestId);
            WriteDebugXmlToOutputStream(attributes);
            m_asyncResult.CompleteCall();
            return m_asyncResult;
        }
コード例 #16
0
        public IAsyncResult BeginProcessRequest(HttpContext context, AsyncCallback cb, object extraData)
        {
            m_request = context.Request;
            m_response = context.Response;
            m_cookieCollection = context.Request.Cookies;
            m_asyncResult = new NuxleusAsyncResult(cb, extraData);
            HttpCookie sessionid = m_cookieCollection["sessionid"];
            HttpCookie userid = m_cookieCollection["userid"];
            HttpCookie username = m_cookieCollection["username"];
            HttpCookie name = m_cookieCollection["name"];
            HttpCookie uservalidated = m_cookieCollection["uservalidated"];

            string ip = m_request.UserHostAddress.ToString();

            NameValueCollection form = m_request.Form;
            HttpFileCollection files = m_request.Files;
            m_response.Write(files.Count);

            m_returnLocation = form.Get("return-url");
            string medianame = form.Get("name");
            string description = form.Get("description");
            string collection_name = form.Get("collection-name");
            string collection_id = form.Get("collection-id");
            string tags = form.Get("tags");
            string mediaid = Guid.NewGuid().ToString();
            string virtualPath = String.Format("/member/{0}/media/{1}", userid.Value, collection_id);
            string path = m_request.MapPath(virtualPath);

            for (int i = 0; i < files.Count; i++)
            {
                HttpPostedFile postedFile = files[i];
                string localFilePath = String.Empty;
                try
                {
                    if (!Directory.Exists(path))
                    {
                        DirectoryInfo directory = Directory.CreateDirectory(path);
                    }

                    Stream fileStream = postedFile.InputStream;
                    string hash = new HashcodeGenerator(fileStream).GetHashCode().ToString();
                    string fileName = String.Format("{0}{1}", hash, Path.GetExtension(postedFile.FileName));
                    localFilePath = String.Format("{0}\\{1}", path, fileName);
                    postedFile.SaveAs(localFilePath);

                    string uri = String.Format("{0}{1}/{2}", m_baseMediaDomain, virtualPath, fileName);

                    List<AwsSdbModel.Attribute> attributes = new List<AwsSdbModel.Attribute>();
                    attributes.Add(new AwsSdbModel.Attribute { Name = "medianame", Value = medianame });
                    attributes.Add(new AwsSdbModel.Attribute { Name = "description", Value = description });
                    attributes.Add(new AwsSdbModel.Attribute { Name = "tags", Value = tags });
                    attributes.Add(new AwsSdbModel.Attribute { Name = "CollectionName", Value = collection_name });
                    attributes.Add(new AwsSdbModel.Attribute { Name = "CollectionId", Value = collection_id });
                    attributes.Add(new AwsSdbModel.Attribute { Name = "mediaid", Value = mediaid });
                    attributes.Add(new AwsSdbModel.Attribute { Name = "uri", Value = uri });
                    attributes.Add(new AwsSdbModel.Attribute { Name = "mediacreator", Value = userid.Value });

                    PutAttributesTask task = new PutAttributesTask { 
                        DomainName = new Domain { 
                            Name = "media" }, 
                            Item = new Item { 
                                ItemName = mediaid, 
                                Attribute = attributes 
                            } 
                    };

                    IResponse response = task.Invoke();
                    PutAttributesResult result = (PutAttributesResult)response.Result;
                    foreach (string header in response.Headers)
                    {
                        m_response.Write(String.Format("ResponseHeader: {0}: {1}", header, response.Headers[header]));
                    }

                    WriteDebugXmlToOutputStream(attributes);
                }
                catch (Exception e)
                {
                    m_response.Write(e.Message);
                }
            }

            m_asyncResult.CompleteCall();
            return m_asyncResult;
        }