Esempio n. 1
0
        public static HttpWebRequest CreatePostRequest(IWebConnection connection, string path, IDictionary<string, object> parameters)
        {
            var webRequest = (HttpWebRequest)WebRequest.Create(string.Format("{0}//{1}", connection.Address, path));
            webRequest.Headers.Add(CookieContainer.REQUESTHEADER_SESSIONCOOKIE, connection.CookieContainer.Cookie);
            webRequest.Method = WebMethod.POST;
            webRequest.UserAgent = WebConnection.USER_AGENT;
            webRequest.ContentType = WebConnection.CONTENT_TYPE;
            webRequest.AllowAutoRedirect = false;
            webRequest.Headers.Add("X-CSRF-Token", connection.CsrfTokenContainer.CsrfToken);

            //parameters.Add(WebConnection.CSRF_TOKEN_PARAM_NAME, connection.CsrfTokenContainer.CsrfToken);
            string postData = ParseParametersToJson(parameters);

            webRequest.AllowWriteStreamBuffering = true;
            Stream requestStream = webRequest.GetRequestStream();
            var encoding = new UTF8Encoding();
            byte[] bytes = encoding.GetBytes(postData);
            if (bytes.Length > 0)
                requestStream.Write(bytes, 0, bytes.Length);
            else
                webRequest.ContentLength = 0;

            requestStream.Close();

            return webRequest;
        }
 public WebDataService(string key)
 {
     //default to ComicVine
     this.connection = new ComicVineWebConnection();
     this.reader = new ComicVineXMLReader();
     this.urlBuilder = new ComicVineURLBuilder(key, format);
 }
        public static string ProcessResponse(IWebConnection connection,
                                             HttpWebResponse httpWebResponse)
        {
            string responseText = string.Empty;
            string cookie = httpWebResponse.Headers.Get(CookieContainer.RESPONSEHEADER_SESSIONCOOKIE);
            if (!string.IsNullOrEmpty(cookie)) {
                connection.CookieContainer.SetCookie(cookie);
            }

            using (Stream stream = httpWebResponse.GetResponseStream()) {
                if (stream != null) {
                    using (var reader = new StreamReader(stream, true)) {
                        var responseTextBuilder = new StringBuilder((int)httpWebResponse.ContentLength);
                        while (!reader.EndOfStream) {
                            var buffer = new char[1024];
                            reader.Read(buffer, 0, buffer.Length);

                            var cleanBuffer = buffer.Where(c => c != '\0').ToArray();

                            if (cleanBuffer.Length > 0)
                                responseTextBuilder.Append(cleanBuffer);
                        }
                        responseText = responseTextBuilder.ToString();
                    }
                }
            }

            string csrfToken = ExtractCsrfToken(responseText);
            if (!string.IsNullOrEmpty(csrfToken))
                connection.CsrfTokenContainer.SetCsrfToken(csrfToken);

            return responseText;
        }
Esempio n. 4
0
        public ShellWebConnection(
            IWebConnection webConnection,
            ISession session,
            string requestedFile,
            RequestParameters getParameters,
            byte[] content,
            string contentType,
            CookiesFromBrowser cookiesFromBrowser,
            CallingFrom callingFrom)
            : base(webConnection.WebServer, callingFrom, webConnection.Generation + 1)
        {
            _Content = new WebConnectionContent.InMemory(content);
            _ContentType = contentType;
            _Session = session;
            _Method = WebMethod.GET;
            _CookiesFromBrowser = cookiesFromBrowser;
            _CookiesToSet = webConnection.CookiesToSet;
            _HttpVersion = webConnection.HttpVersion;
            _RequestedHost = webConnection.RequestedHost;
            _Headers = new Dictionary<string, string>(webConnection.Headers);
            _MimeReader = webConnection.MimeReader;

            BaseWebConnection = webConnection;

            _RequestedFile = requestedFile;
            _GetParameters = getParameters;
            _PostParameters = null;
        }
Esempio n. 5
0
 public WebDataService(string key)
 {
     //default to ComicVine
     this.connection = new ComicVineWebConnection();
     this.reader     = new ComicVineXMLReader();
     this.urlBuilder = new ComicVineURLBuilder(key, format);
 }
Esempio n. 6
0
            public override IWebResults CallMethod(IWebConnection webConnection, IWebHandlerPlugin webHandlerPlugin)
            {
                object[] arguments = new object[NumParameters];

                // Decode the arguments
                foreach (MimeReader.Part mimePart in webConnection.MimeReader)
                    if (ParameterIndexes.ContainsKey(mimePart.Name))
                    {
                        uint parameterIndex = ParameterIndexes[mimePart.Name];
                        arguments[parameterIndex] = mimePart;
                    }

                // The first argument is always the web connection
                arguments[0] = webConnection;

                object toReturn;

                try
                {
                    toReturn = MethodInfo.Invoke(webHandlerPlugin, arguments);
                }
                catch (TargetInvocationException e)
                {
                    // Invoke wraps exceptions
                    throw e.InnerException;
                }

                return (IWebResults)toReturn;
            }
Esempio n. 7
0
 public DerpImagesViewModel(bool favorite, IWebConnection web)
 {
     IsFavoriteView   = favorite;
     CurrentKey       = string.Empty;
     HasNavigationBar = true;
     derpibooru       = new DerpibooruService(web);
 }
Esempio n. 8
0
		public static RootInfo GetRoot (string rootUri, IWebConnection connection)
		{
			// TODO: Error-handling in GET and Deserialize
			string jsonString = connection.Get (rootUri, null);
			RootInfo root = ParseJson (jsonString);
			return root;
		}
Esempio n. 9
0
        public ShellWebConnection(
            IWebConnection webConnection,
            WebMethod method,
            string url,
            byte[] content,
            string contentType,
            CookiesFromBrowser cookiesFromBrowser,
            CallingFrom callingFrom)
            : base(webConnection.WebServer, callingFrom, webConnection.Generation + 1)
        {
            _Content = new WebConnectionContent.InMemory(content);
            _ContentType = contentType;
            _Session = webConnection.Session;
            _Method = method;
            _CookiesFromBrowser = cookiesFromBrowser;
            _CookiesToSet = webConnection.CookiesToSet;
            _HttpVersion = webConnection.HttpVersion;
            _RequestedHost = webConnection.RequestedHost;
            _Headers = new Dictionary<string, string>(webConnection.Headers);
            _MimeReader = webConnection.MimeReader;

            BaseWebConnection = webConnection;

            DetermineRequestedFileAndGetParameters(url);
            TryDecodePostParameters();
        }
Esempio n. 10
0
        /// <summary>
        /// Evaluates the named template
        /// </summary>
        /// <param name="webConnection"></param>
        /// <param name="filename"></param>
        /// <param name="arguments"></param>
        /// <returns></returns>
        public IWebResults Evaluate(IWebConnection webConnection, string filename, IDictionary<string, object> arguments)
        {
            try
            {
                Stream results = EvaluateToStream(
                    webConnection,
                    arguments,
                    filename);

                IWebResults toReturn;

                // Hack to work around a bug in IE handling xhtml
                // Basically, IE won't handle &gt; and &lt; in xhtml
                string userAgent;
                if (webConnection.Headers.TryGetValue("USER-AGENT", out userAgent))
                    if (userAgent.Contains(" MSIE "))
                    {
                        StreamReader sr = new StreamReader(results);
                        string result = sr.ReadToEnd();
                        result = result.Replace("<?xml version=\"1.0\" encoding=\"utf-8\"?><html", "");
                        result = result.Split(new char[] { '>' }, 2)[1];
                        result = "<!DOCTYPE html>\n<html>" + result;

                        string[] splitAtScriptTag = result.Split(new string[] {"<script>"}, StringSplitOptions.None);
                        StringBuilder resultBuilder = new StringBuilder(splitAtScriptTag[0]);

                        for (int ctr = 1; ctr < splitAtScriptTag.Length; ctr++)
                        {
                            string[] scriptAndPostTags = splitAtScriptTag[ctr].Split(new string[] {"</script>"}, StringSplitOptions.None);

                            if (scriptAndPostTags.Length == 1)
                                resultBuilder.Append(scriptAndPostTags[0]);
                            else
                            {
                                string script = scriptAndPostTags[0].Replace("&gt;", ">").Replace("&lt;", "<");
                                resultBuilder.Append("<script>");
                                resultBuilder.Append(script);
                                resultBuilder.Append("</script>");
                                resultBuilder.Append(scriptAndPostTags[1]);
                            }
                        }

                        toReturn = WebResults.From(Status._200_OK, resultBuilder.ToString());
                        toReturn.ContentType = "text/html";

                        return toReturn;
                    }

                // Everyone else gets real XML
                toReturn = WebResults.From(Status._200_OK, results);
                toReturn.ContentType = ContentType;

                return toReturn;
            }
            catch (TemplateException te)
            {
                throw new WebResultsOverrideException(WebResults.From(Status._500_Internal_Server_Error, te.Message), te);
            }
        }
Esempio n. 11
0
        public IWebResults Evaluate(IWebConnection webConnection, string filename)
        {
            Dictionary<string, object> arguments = new Dictionary<string, object>();
            foreach (KeyValuePair<string, string> getParameter in webConnection.GetParameters)
                arguments[getParameter.Key] = getParameter.Value;

            return Evaluate(webConnection, filename, arguments);
        }
Esempio n. 12
0
        public static RootInfo GetRoot(string rootUri, IWebConnection connection)
        {
            // TODO: Error-handling in GET and Deserialize
            string   jsonString = connection.Get(rootUri, null);
            RootInfo root       = ParseJson(jsonString);

            return(root);
        }
Esempio n. 13
0
 public ShellWebConnection(
     string url,
     IWebConnection webConnection,
     RequestParameters postParameters,
     CookiesFromBrowser cookiesFromBrowser)
     : this(url, webConnection, postParameters, cookiesFromBrowser, webConnection.CallingFrom)
 {
 }
Esempio n. 14
0
		public static UserInfo GetUser (string userUri, IWebConnection connection)
		{
			// TODO: Error-handling in GET and Deserialize
			string jsonString = connection.Get (userUri, null);
			UserInfo user = ParseJson (jsonString);
			user.Connection = connection;
			user.Uri = userUri;
			return user;
		}
Esempio n. 15
0
 public ShellWebConnection(
     string url,
     IWebConnection webConnection,
     RequestParameters postParameters,
     CookiesFromBrowser cookiesFromBrowser,
     CallingFrom callingFrom)
     : this(url, webConnection, postParameters, cookiesFromBrowser, callingFrom, WebMethod.GET)
 {
 }
Esempio n. 16
0
        public IWebConnection Connect()
        {
            if (_webConnection == null || _webConnection.State == ConnectionState.Corrupted) {
                _webConnection = new WebConnection(Address, _username, _password);
                _webConnection.Open();
            }

            return _webConnection;
        }
Esempio n. 17
0
        public static UserInfo GetUser(string userUri, IWebConnection connection)
        {
            // TODO: Error-handling in GET and Deserialize
            string   jsonString = connection.Get(userUri, null);
            UserInfo user       = ParseJson(jsonString);

            user.Connection = connection;
            user.Uri        = userUri;
            return(user);
        }
Esempio n. 18
0
 public static HttpWebRequest CreateGetRequest(IWebConnection connection, string path)
 {
     var webRequest = (HttpWebRequest)WebRequest.Create(string.Format("{0}//{1}", connection.Address, path));
     webRequest.Headers.Add(CookieContainer.REQUESTHEADER_SESSIONCOOKIE, connection.CookieContainer.Cookie);
     webRequest.Method = WebMethod.GET;
     webRequest.UserAgent = WebConnection.USER_AGENT;
     webRequest.ContentType = WebConnection.CONTENT_TYPE;
     webRequest.AllowAutoRedirect = false;
     return webRequest;
 }
 public BlockingShellWebConnection(
     IWebConnection webConnection,
     WebMethod method,
     string url,
     byte[] content,
     string contentType,
     CookiesFromBrowser cookiesFromBrowser,
     CallingFrom callingFrom)
     : base(webConnection, method, url, content, contentType, cookiesFromBrowser, callingFrom)
 {
 }
 public BlockingShellWebConnection(
     IWebConnection webConnection,
     ISession session,
     string requestedFile,
     RequestParameters getParameters,
     byte[] content,
     string contentType,
     CookiesFromBrowser cookiesFromBrowser,
     CallingFrom callingFrom)
     : base(webConnection, session, requestedFile, getParameters, content, contentType, cookiesFromBrowser, callingFrom)
 {
 }
Esempio n. 21
0
        public IWebResults CallMethod(IWebConnection webConnection, CallingFrom callingFrom)
        {
            object toReturn;

            FilePermissionEnum? minimumPermission;
            switch (callingFrom)
            {
                case CallingFrom.Local:
                    minimumPermission = WebCallableMethod.WebCallableAttribute.MinimumPermissionForTrusted;
                    break;

                case CallingFrom.Web:
                    minimumPermission = WebCallableMethod.WebCallableAttribute.MinimumPermissionForWeb;
                    break;

                default:
                    // This clause shouldn't be hit, but in case it is, require the strictest permission possible
                    minimumPermission = FilePermissionEnum.Administer;
                    break;
            }

            ID<IUserOrGroup, Guid> userId = webConnection.Session.User.Id;

            // If this user isn't the owner, then verify that the user has the appropriate permission
            if (null != minimumPermission)
                if (FileContainer.OwnerId != userId)
                {
                    bool hasPermission = false;

                    // Get appropriate permission
                    FilePermissionEnum? userPermission = FileContainer.LoadPermission(userId);

                    if (null != userPermission)
                        if (userPermission.Value >= minimumPermission.Value)
                            hasPermission = true;

                    // If the user doesn't explicitly have the needed permission, try loading any potentially-needed declaritive permissions
                    if (!hasPermission)
                        hasPermission = FileContainer.HasNamedPermissions(userId, WebCallableMethod.NamedPermissions);

                    if (!hasPermission)
                        return WebResults.From(Status._401_Unauthorized, "Permission Denied for method " + WebCallableMethod.MethodInfo.Name);
                }

            if (null != WebCallableMethod.WebMethod)
                if (WebCallableMethod.WebMethod.Value != webConnection.Method)
                    return WebResults.From(Status._405_Method_Not_Allowed, "Allowed method: " + WebCallableMethod.WebMethod.Value.ToString());

            toReturn = WebCallableMethod.CallMethod(webConnection, WebHandlerPlugin);

            return (IWebResults)toReturn;
        }
Esempio n. 22
0
        public static HttpWebRequest CreateGetRequest(IWebConnection connection, string path, IDictionary<string, object> parameters)
        {
            var queryStringBuilder = new StringBuilder();
            queryStringBuilder.Append('?');
            foreach (var parameter in parameters)
            {
                queryStringBuilder.Append(string.Format("{0}={1}&", parameter.Key, parameter.Value));
            }

            // Remove last &
            queryStringBuilder.Remove(queryStringBuilder.Length - 1, 1);
            string queryString = Uri.EscapeUriString(queryStringBuilder.ToString());

            return CreateGetRequest(connection, string.Concat(path, queryString));
        }
Esempio n. 23
0
            public override IWebResults CallMethod(IWebConnection webConnection, IWebHandlerPlugin webHandlerPlugin)
            {
                object toReturn;

                try
                {
                    toReturn = MethodInfo.Invoke(webHandlerPlugin, new object[] { webConnection });
                }
                catch (TargetInvocationException e)
                {
                    // Invoke wraps exceptions
                    throw e.InnerException;
                }

                return (IWebResults)toReturn;
            }
Esempio n. 24
0
        /// <summary>
        /// Creates a scope wrapper
        /// </summary>
        /// <param name="fileHandlerFactoryLocator"></param>
        /// <param name="webConnection"></param>
        /// <param name="javascript"></param>
        /// <param name="fileContainer"></param>
        /// <param name="constructScopeResults"></param>
        public ScopeWrapper(
            FileHandlerFactoryLocator fileHandlerFactoryLocator,
            SubProcess subProcess,
            IFileContainer fileContainer,
            ParentScope parentScope,
            IWebConnection constructWebConnection,
            out object constructScopeResults)
        {
            _FileContainer = fileContainer;
            _SubProcess = subProcess;
            _ParentScope = parentScope;

            _ScopeId = GetScopeID();

            _FileHandlerFactoryLocator = fileHandlerFactoryLocator;

            constructScopeResults = ConstructScope(constructWebConnection);
        }
Esempio n. 25
0
            public override IWebResults CallMethod(IWebConnection webConnection, IWebHandlerPlugin webHandlerPlugin)
            {
                if (null == webConnection.Content)
                    return WebResults.From(Status._400_Bad_Request, "No data sent");

                object toReturn;

                try
                {
                    toReturn = MethodInfo.Invoke(webHandlerPlugin, new object[] { webConnection, GetSecondArgument(webConnection.Content) });
                }
                catch (TargetInvocationException e)
                {
                    // Invoke wraps exceptions
                    throw e.InnerException;
                }

                return (IWebResults)toReturn;
            }
Esempio n. 26
0
        public void Setup()
        {
            if (testMode == "Live")
            {
                repository = new MSSQLDatabase();
                connection = new ComicVineWebConnection();
            }
            else
            {
                repository = new TestRepository();
                connection = new TestWebConnection();
            }

            key = repository.GetSetting("WebServiceKey");
            format = "xml";

            urlBuilder = new ComicVineURLBuilder(key, format);
            reader = new ComicVineXMLReader();
            service = new WebDataService(connection, reader, urlBuilder);
        }
Esempio n. 27
0
        public void Setup()
        {
            if (testMode == "Live")
            {
                repository = new MSSQLDatabase();
                connection = new ComicVineWebConnection();
            }
            else
            {
                repository = new TestRepository();
                connection = new TestWebConnection();
            }

            key    = repository.GetSetting("WebServiceKey");
            format = "xml";

            urlBuilder = new ComicVineURLBuilder(key, format);
            reader     = new ComicVineXMLReader();
            service    = new WebDataService(connection, reader, urlBuilder);
        }
Esempio n. 28
0
        public IWebResults DoComet(IWebConnection webConnection)
        {
            ushort sessionIdValue = default(ushort);

            if (!ushort.TryParse(
                webConnection.EitherArgumentOrException("s"),
                NumberStyles.AllowHexSpecifier,
                CultureInfo.InvariantCulture,
                out sessionIdValue))
            {
                return WebResults.FromString(Status._417_Expectation_Failed, "Invalid session ID");
            }

            ID<ICometSession, ushort> sessionId = new ID<ICometSession, ushort>(sessionIdValue);

            ICometSession cometSession;
            try
            {
                cometSession = CometHandler[sessionId];
            }
            catch (BadCometSessionId)
            {
                return WebResults.FromString(Status._400_Bad_Request, "Bad SESSION_KEY");
            }

            //object data = JsonReader.Deserialize("{\"d\": " + webConnection.Content.AsString() + "}");
            // This is silly, but for some reason the array is quoted when it's sent...
            string wtf = JsonReader.Deserialize<string>(webConnection.Content.AsString());
            object[] packets = JsonReader.Deserialize<object[]>(wtf);

            foreach (object[] packet in packets)
                cometSession.RecieveData(
                    Convert.ToUInt64(packet[0]),
                    packet[2].ToString());

            return WebResults.FromStatus(Status._200_OK);
        }
Esempio n. 29
0
 public static HttpWebResponse Dispatch(IWebConnection connection, HttpWebRequest httpWebRequest)
 {
     try {
         return (HttpWebResponse) httpWebRequest.GetResponse();
     }
     catch (WebException webException)
     {
         Log.Error(webException);
         if (webException.Response is HttpWebResponse)
         {
             var response = webException.Response as HttpWebResponse;
             if (response.StatusCode == HttpStatusCode.Unauthorized)
             {
                 throw new NeedLogonException();
             }
         }
         throw;
     }
     catch (Exception exception)
     {
         Log.Error(exception);
         throw;
     }
 }
Esempio n. 30
0
		public WebSyncServer (string serverUrl, IWebConnection connection)
		{
			this.connection = connection;
			rootUri = serverUrl.TrimEnd ('/') + "/api/1.0/";
		}
Esempio n. 31
0
 public DerpibooruService(IWebConnection web)
 {
     _web = web;
 }
Esempio n. 32
0
        public List <DerpTag> GetTagInfoFromDerpibooru(List <DerpTag> oldTags, int max, IWebConnection _web, out int newcount)
        {
            newcount = 0;

            List <DerpTag> newTags = new List <DerpTag>();

            using (WebClient webClient = new WebClient())
            {
                int    pageindex = 1;
                string url       = "https://derpibooru.org/tags?page=";
                string infostr;
                string tempstr;
                string tempstr2;

                ProgressBarHeight    = 8;
                ProgressBarIsVisible = true;

                while (true)
                {
                    infostr = webClient.DownloadString(url + pageindex);
                    infostr = Library.extractionString(infostr, "<div class=\"tag-list\">", "</div>");

                    if (infostr.Contains("<span class=\"tag dropdown\" "))
                    {
                        while (infostr.Contains("<span class=\"tag dropdown\" "))
                        {
                            try
                            {
                                Library.extractionString(infostr, out infostr, "<span class=\"tag dropdown\" ", "Filter</a></span></span>", out tempstr);
                                DerpTag tag = new DerpTag();
                                tag.CategoryStrEn = Library.extractionString(tempstr, "data-tag-category=\"", "\"");
                                tag.Id            = Library.extractionString(tempstr, "data-tag-id=\"", "\"");
                                tempstr2          = Library.extractionString(tempstr, "data-tag-name=\"", "\"");
                                tag.NameEn        = tag.NameKr = System.Web.HttpUtility.HtmlDecode(tempstr2).Replace("&#39;", "'");
                                tempstr2          = Library.extractionString(tempstr, "title=\"", "\"");
                                tag.DescriptionEn = tag.DescriptionKr = System.Web.HttpUtility.HtmlDecode(tempstr2);
                                DerpTag temp = oldTags.Find(i => i.Id == tag.Id);
                                if (temp != null)
                                {
                                    tag = temp;
                                }
                                else
                                {
                                    newcount++;
                                }
                                tag.Index = newTags.Count;
                                newTags.Add(tag);

                                Progress = (float)newTags.Count / max;
                                if (newTags.Count >= max)
                                {
                                    goto EndPoint;
                                }
                            }
                            catch (Exception ex)
                            {
                                Console.WriteLine(ex);
                                goto EndPoint;
                            }
                        }
                    }
                    else
                    {
                        break;
                    }
                    pageindex++;
                }

EndPoint:
                for (int season = 9; season > 0; season--)
                {
                    int fin  = season == 3 ? 13 : 26;
                    var tags = new DerpTag($"spoiler:s{season.ToString("D2")}")
                    {
                        Category = DerpTagCategory.SPOILER, Index = newTags.Count
                    };
                    newTags.RemoveAll(i => i.NameEn == tags.NameEn);
                    newTags.Add(tags);
                    for (int episod = fin; episod > 0; episod--)
                    {
                        var tage = new DerpTag($"spoiler:s{season.ToString("D2")}e{episod.ToString("D2")}")
                        {
                            Category = DerpTagCategory.SPOILER, Index = newTags.Count
                        };
                        newTags.RemoveAll(i => i.NameEn == tage.NameEn);
                        newTags.Add(tage);
                    }
                }
                newTags.Add(new DerpTag("score.gt:100"));
                newTags.Add(new DerpTag("score.gt:500"));
                newTags.Add(new DerpTag("score.gt:1000"));
                newTags.Add(new DerpTag("score.gte:100"));
                newTags.Add(new DerpTag("score.gte:500"));
                newTags.Add(new DerpTag("score.gte:1000"));
                newTags.Add(new DerpTag("score.lt:100"));
                newTags.Add(new DerpTag("score.lt:500"));
                newTags.Add(new DerpTag("score.lt:1000"));
                newTags.Add(new DerpTag("score.lte:100"));
                newTags.Add(new DerpTag("score.lte:500"));
                newTags.Add(new DerpTag("score.lte:1000"));


                var olds = oldTags.FindAll(i => newTags.Find(j => j.NameEn == i.NameEn) == null);
                newTags.AddRange(olds);

                ProgressBarHeight    = 0;
                ProgressBarIsVisible = false;
            }
            return(newTags);
        }
Esempio n. 33
0
 public WebDataService(IWebConnection connection, IWebDataReader reader, IURLBuilder urlBuilder)
 {
     this.connection = connection;
     this.reader     = reader;
     this.urlBuilder = urlBuilder;
 }
Esempio n. 34
0
 public WebSyncServer(string serverUrl, IWebConnection connection)
 {
     this.connection = connection;
     rootUri         = serverUrl.TrimEnd('/') + "/api/1.0/";
 }
Esempio n. 35
0
 public WebSyncServer(string serverUrl, IWebConnection connection)
 {
     this.connection = connection;
     rootUri         = serverUrl + "/api/1.0/";     // TODO: Trim trailing / from serverUrl if necessary
 }
Esempio n. 36
0
        /// <summary>
        /// Constructor for when a web request is generated publicly instead of externally
        /// </summary>
        /// <param name="webServer"></param>
        /// <param name="session"></param>
        /// <param name="url"></param>
        /// <param name="content"></param>
        /// <param name="contentType"></param>
        /// <param name="cookiesFromBrowser"></param>
        /// <param name="callingFrom"></param>
        /// <param name="method"></param>
        public ShellWebConnection(
            IWebServer webServer,
            ISession session,
            string url,
            byte[] content,
            string contentType,
            CookiesFromBrowser cookiesFromBrowser,
            CallingFrom callingFrom,
            WebMethod method)
            : base(webServer, callingFrom, 0)
        {
            _Content = new WebConnectionContent.InMemory(content);
            _ContentType = contentType;
            _Session = session;
            _Method = method;
            _CookiesFromBrowser = cookiesFromBrowser;
            _CookiesToSet = new List<CookieToSet>();
            _HttpVersion = 1;
            _RequestedHost = null;
            _Headers = new Dictionary<string, string>();

            DetermineRequestedFileAndGetParameters(url);

            TryDecodePostParameters();

            if (null == BaseWebConnection)
                BaseWebConnection = this;
        }
Esempio n. 37
0
        public ShellWebConnection(
            string url,
            IWebConnection webConnection,
            RequestParameters postParameters,
            CookiesFromBrowser cookiesFromBrowser,
            CallingFrom callingFrom,
            WebMethod method)
            : base(webConnection.WebServer, callingFrom, webConnection.Generation + 1)
        {
            _PostParameters = postParameters;
            _Content = webConnection.Content;
            _ContentType = webConnection.ContentType;
            _Session = webConnection.Session;
            _Method = method;
            _CookiesFromBrowser = cookiesFromBrowser;
            _CookiesToSet = webConnection.CookiesToSet;
            _HttpVersion = webConnection.HttpVersion;
            _RequestedHost = webConnection.RequestedHost;
            _Headers = new Dictionary<string, string>(webConnection.Headers);
            _MimeReader = webConnection.MimeReader;

            BaseWebConnection = webConnection;

            DetermineRequestedFileAndGetParameters(url);
        }
Esempio n. 38
0
        /// <summary>
        /// Generates composite Javascript from a list of scripts
        /// </summary>
        /// <param name="webConnection"></param>
        /// <param name="scriptUrls"></param>
        /// <returns></returns>
        private string GenerateCompositeJavascript(IWebConnection webConnection, IEnumerable<string> scriptUrls)
        {
            StringBuilder scriptBuilder = new StringBuilder();

            foreach (string scriptUrl in scriptUrls)
            {
                try
                {
                    IWebResults webResult = webConnection.ShellTo(scriptUrl);

                    int statusCode = (int)webResult.Status;

                    if ((statusCode >= 200) && (statusCode < 300))
                    {
                        string script = webResult.ResultsAsString;
                        script = JavaScriptMinifier.Instance.Minify(script);

                        scriptBuilder.AppendFormat("\n// {0}\n", scriptUrl);
                        scriptBuilder.Append("try {");
                        scriptBuilder.Append(script);
                        scriptBuilder.Append("} catch (exception) { }");

                        // Note: exceptions are swallowed
                        // This form of compression shouldn't be used when a developer is trying to debug, instead, they should
                        // turn on Javascript debug mode, which disables this compression and allows them to use the browser's
                        // debugger
                    }
                }
                catch (Exception e)
                {
                    log.Error("Error loading script in GenerateCompositeJavascript for script " + scriptUrl, e);
                }
            }

            return scriptBuilder.ToString();
        }
Esempio n. 39
0
        public IWebResults GetScaled(
            IWebConnection webConnection,
            int? width,
            int? height,
            int? maxWidth,
            int? maxHeight,
            int? minWidth,
            int? minHeight)
        {
            int returnedWidth;
            int returnedHeight;

            double aspectRatio = Convert.ToDouble(Image.Width) / Convert.ToDouble(Image.Height);
            double inverseAspectRatio = Convert.ToDouble(Image.Height) / Convert.ToDouble(Image.Width);

            // First, figure out what the size of the returned image will be based on specified height or width

            if ((null != width) && (null != height))
            {
                returnedHeight = height.Value;
                returnedWidth = width.Value;
                aspectRatio = Convert.ToDouble(returnedWidth) / Convert.ToDouble(returnedHeight);
                inverseAspectRatio = Convert.ToDouble(returnedHeight) / Convert.ToDouble(returnedWidth);
            }
            else if (null != width)
            {
                returnedWidth = width.Value;
                returnedHeight = Convert.ToInt32(
                    Convert.ToDouble(width.Value) * inverseAspectRatio);
            }
            else if (null != height)
            {
                returnedHeight = height.Value;
                returnedWidth = Convert.ToInt32(
                    Convert.ToDouble(height.Value) * aspectRatio);
            }
            else
            {
                returnedWidth = Image.Width;
                returnedHeight = Image.Height;
            }

            // Second, make sure that maxes and mins aren't violated

            if (null != maxWidth)
                if (returnedWidth > maxWidth.Value)
                {
                    returnedWidth = maxWidth.Value;
                    returnedHeight = Convert.ToInt32(
                        Convert.ToDouble(maxWidth.Value) * inverseAspectRatio);
                }

            if (null != maxHeight)
                if (returnedHeight > maxHeight.Value)
                {
                    returnedHeight = maxHeight.Value;
                    returnedWidth = Convert.ToInt32(
                        Convert.ToDouble(maxHeight.Value) * aspectRatio);
                }

            if (null != minWidth)
                if (returnedWidth < minWidth.Value)
                {
                    returnedWidth = minWidth.Value;
                    returnedHeight = Convert.ToInt32(
                        Convert.ToDouble(minWidth.Value) * inverseAspectRatio);
                }

            if (null != minHeight)
                if (returnedHeight < minHeight.Value)
                {
                    returnedHeight = minHeight.Value;
                    returnedWidth = Convert.ToInt32(
                        Convert.ToDouble(minHeight.Value) * aspectRatio);
                }

            // Now, in the rare chance that size doesn't change, don't do anything
            // (disabled due to MIME ambiguities)
            //if ((returnedWidth == Image.Width) && (returnedHeight == Image.Height))
            //    return ReadAll(webConnection);

            // The image must be resized.

            // Check to see if there is a cached version
            string cacheKey = "resized_w_" + returnedWidth + "_h_" + returnedHeight;
            byte[] resizedImageBytes;
            IWebResults toReturn;
            if (FileHandler.TryGetCached(cacheKey, out resizedImageBytes))
            {
                MemoryStream stream = new MemoryStream(resizedImageBytes, false);
                toReturn = WebResults.From(Status._200_OK, stream);
            }
            else
            {
                // There wasn't a cached version.  The resizing must occur

                // reference: http://www.glennjones.net/Post/799/Highqualitydynamicallyresizedimageswithnet.htm

                Image thumbnail = new Bitmap(returnedWidth, returnedHeight);
                Graphics graphic = System.Drawing.Graphics.FromImage(thumbnail);

                // Set up high-quality resize mode
                graphic.InterpolationMode = InterpolationMode.HighQualityBicubic;
                graphic.SmoothingMode = SmoothingMode.HighQuality;
                graphic.PixelOffsetMode = PixelOffsetMode.HighQuality;
                graphic.CompositingQuality = CompositingQuality.HighQuality;

                // do the resize
                graphic.DrawImage(Image, 0, 0, returnedWidth, returnedHeight);

                // Save as a high quality JPEG
                ImageCodecInfo[] info = ImageCodecInfo.GetImageEncoders();
                EncoderParameters encoderParameters;
                encoderParameters = new EncoderParameters(1);
                encoderParameters.Param[0] = new EncoderParameter(Encoder.Quality, 100L);

                MemoryStream ms = new MemoryStream();
                thumbnail.Save(ms, info[1], encoderParameters);
                resizedImageBytes = new byte[ms.Length];

                // Saved the resized image in the cache
                ms.Seek(0, SeekOrigin.Begin);
                ms.Read(resizedImageBytes, 0, resizedImageBytes.Length);
                FileHandler.SetCached(cacheKey, resizedImageBytes);

                ms.Seek(0, SeekOrigin.Begin);
                toReturn = WebResults.From(Status._200_OK, ms);
            }

            toReturn.ContentType = "image/jpeg";
            return toReturn;
            //Image.
        }
Esempio n. 40
0
        /// <summary>
        /// Returns the file with all header/footers resolved as XML for further processing
        /// </summary>
        /// <param name="arguments"></param>
        /// <param name="templateFileContainer"></param>
        /// <param name="webConnection"></param>
        /// <param name="templateParsingState"></param>
        /// <returns></returns>
        private void ResolveHeaderFooter(
            IWebConnection webConnection,
            IDictionary<string, object> arguments,
            IFileContainer templateFileContainer,
            TemplateParsingState templateParsingState)
        {
            HashSet<string> checkedHeaderFooters = new HashSet<string>();

            XmlDocument templateDocument = templateParsingState.LoadXmlDocumentAndReplaceGetParameters(arguments, templateFileContainer, XmlParseMode.Xml);

            // I think this is to work around an issue when directly viewing a template with an empty <oc:component /> tag
            templateParsingState.TemplateDocument = templateDocument;

            // While the first node isn't HTML, keep loading header/footers
            while ("html" != templateDocument.FirstChild.LocalName)
            {
                XmlNode firstChild = templateDocument.FirstChild;
                string headerFooter = "/DefaultTemplate/headerfooter.ochf";

                XmlNodeList nodesToInsert;
                if (("componentdef" == firstChild.LocalName) && (templateParsingState.TemplateHandlerLocator.TemplatingConstants.TemplateNamespace == firstChild.NamespaceURI))
                {
                    XmlAttribute headerFooterAttribue = firstChild.Attributes["headerfooter"];
                    if (null != headerFooterAttribue)
                        headerFooter = FileHandlerFactoryLocator.FileSystemResolver.GetAbsolutePath(
                            templateFileContainer.ParentDirectoryHandler.FileContainer.FullPath,
                            headerFooterAttribue.Value);

                    nodesToInsert = firstChild.ChildNodes;
                }
                else
                    nodesToInsert = templateDocument.ChildNodes;

                string headerFooterOverride;
                if (webConnection.GetParameters.TryGetValue("HeaderFooterOverride", out headerFooterOverride))
                    headerFooter = headerFooterOverride;

                if (checkedHeaderFooters.Contains(headerFooter))
                    throw new TemplateException("Looping within templates:  " + headerFooter + " eventually points to itself as a headerfooter!!!");
                else
                    checkedHeaderFooters.Add(headerFooter);

                templateParsingState.SetCWD(nodesToInsert, templateFileContainer.ParentDirectoryHandler.FileContainer.FullPath);

                try
                {
                    templateFileContainer = FileHandlerFactoryLocator.FileSystemResolver.ResolveFile(headerFooter);
                } catch (FileDoesNotExist fdne)
                {
                    log.Error(headerFooter + " does not exist", fdne);

                    throw new WebResultsOverrideException(WebResults.From(Status._500_Internal_Server_Error, headerFooter + " does not exist"));
                }

                templateDocument = templateParsingState.LoadXmlDocumentAndReplaceGetParameters(
                    arguments,
                    templateFileContainer,
                    XmlParseMode.Xml);

                templateParsingState.TemplateDocument = templateDocument;

                // find <oc:component /> tag
                int numOcComponentTags = 0;
                XmlNodeList componentTags = templateDocument.GetElementsByTagName("component", templateParsingState.TemplateHandlerLocator.TemplatingConstants.TemplateNamespace);
                foreach (XmlNode componentNode in Enumerable<XmlNode>.FastCopy(Enumerable<XmlNode>.Cast(componentTags)))
                    if ((null == componentNode.Attributes.GetNamedItem("url", templateParsingState.TemplateHandlerLocator.TemplatingConstants.TemplateNamespace)) && (null == componentNode.Attributes.GetNamedItem("src", templateParsingState.TemplateHandlerLocator.TemplatingConstants.TemplateNamespace)))
                    {
                        numOcComponentTags++;

                        if (1 == numOcComponentTags)
                            templateParsingState.ReplaceNodes(componentNode, nodesToInsert);

                        else
                            templateParsingState.ReplaceNodes(
                                componentNode,
                                templateParsingState.GenerateWarningNode("Warning:  Duplicate <oc:component /> tag, count " + numOcComponentTags.ToString()));
                    }

                // Attempt to recover from a missing <oc:component /> tag
                if (0 == numOcComponentTags)
                {
                    XmlNodeList bodyTags = templateDocument.GetElementsByTagName(
                        "body", templateParsingState.TemplateHandlerLocator.TemplatingConstants.HtmlNamespace);

                    XmlElement bodyTag = null;

                    if (null != bodyTags)
                        if (bodyTags.Count > 0)
                            bodyTag = (XmlElement)bodyTags[0];

                    if (null == bodyTag)
                    {
                        bodyTag = (XmlElement)templateDocument.FirstChild;
                    }

                    bodyTag.AppendChild(
                        templateParsingState.GenerateWarningNode(
            @"WARNING!!!
            --------------
            " + headerFooter + @" is missing a needed <oc:component /> tag!!!
            The tag must be empty with no attributes.  This is where the content for each page is displayed"));

                    XmlElement componentNode = templateDocument.CreateElement(
                        "component", templateParsingState.TemplateHandlerLocator.TemplatingConstants.TemplateNamespace);

                    bodyTag.AppendChild(componentNode);
                    templateParsingState.ReplaceNodes(componentNode, nodesToInsert);
                }
            }

            templateParsingState.SetCWD(templateDocument.ChildNodes, templateFileContainer.ParentDirectoryHandler.FileContainer.FullPath);
        }