예제 #1
0
        private bool HandleResource(string resourceName, HandlePackage package)
        {
            switch (resourceName)
            {
            case "corecss.css":
                package.ResponseHeader.SetField("Content-Type", MIME.GetContentType("css", "text/css"));
                package.ContentStream.Write(Properties.Resources.CoreCSS);
                return(true);

            case "ubuntu-r.ttf":
                package.ResponseHeader.SetField("Content-Type", MIME.GetContentType("ttf", "x/application-font"));
                package.ContentStream.Write(Properties.Resources.Ubuntu_R, 0, Properties.Resources.Ubuntu_R.Length);
                return(true);

            case "folder.png":
                package.ResponseHeader.SetField("Content-Type", MIME.GetContentType("png", "image/png"));
                Properties.Resources.appbar_folder.Save(package.ContentStream, System.Drawing.Imaging.ImageFormat.Png);
                return(true);

            case "page.png":
                package.ResponseHeader.SetField("Content-Type", MIME.GetContentType("png", "image/png"));
                Properties.Resources.appbar_page_bold.Save(package.ContentStream, System.Drawing.Imaging.ImageFormat.Png);
                return(true);

            default:
                return(false);
            }
        }
        /// <summary>
        /// This triggers the current action to download a real file storaged in disk.
        /// </summary>
        /// <param name="controller">You must pass current request controller.</param>
        /// <param name="path">The physical path of the file you wanna download.</param>
        /// <param name="filename">Real file name. Will be used to generate correct MIME type.</param>
        /// <param name="download">If set, will let the browser directly download the file.</param>
        /// <param name="suggestedFileName">If `download` was set and this was not empty, will override the file name argument to be the file name after downloading.</param>
        /// <returns></returns>
        public static async Task <IActionResult> AiurFile(this ControllerBase controller, string path, string filename, bool download, string suggestedFileName)
        {
            return(await Task.Run <IActionResult>(() =>
            {
                var fileInfo = new FileInfo(path);
                var extension = filename.Substring(filename.LastIndexOf('.') + 1);
                long etagHash = fileInfo.LastWriteTime.ToUniversalTime().ToFileTime() ^ fileInfo.Length;
                var _etag = Convert.ToString(etagHash, 16);
                controller.Response.Headers.Add("ETag", '\"' + _etag + '\"');
                if (controller.Request.Headers.Keys.Contains("If-None-Match") && controller.Request.Headers["If-None-Match"].ToString().Trim('\"') == _etag)
                {
                    return new StatusCodeResult(304);
                }
                controller.Response.Headers.Add("Content-Length", fileInfo.Length.ToString());

                // Download mode, or not supported MIME.
                if (download || !MIME.HasKey(extension))
                {
                    if (string.IsNullOrEmpty(suggestedFileName))
                    {
                        suggestedFileName = filename;
                    }
                    return controller.PhysicalFile(path, "application/octet-stream", suggestedFileName, true);
                }
                // Open mode, and supported MIME
                else
                {
                    return controller.PhysicalFile(path, MIME.GetContentType(extension), true);
                }
            }));
        }
예제 #3
0
        private void PrintFile(string path, HandlePackage package)
        {
            if (!File.Exists(path))
            {
                return;
            }

            try
            {
                FileStream fs = File.Open(path, FileMode.Open);
                fs.CopyTo(package.ContentStream);
                try
                {
                    fs.Close();
                }
                catch (Exception ex)
                {
                    Log.e("Failed to close file {0}:\n {1}", path, ex.Message);
                }

                string ext = StringUtil.GetExtension(path).ToLower();
                package.ResponseHeader.SetField("Content-Type", MIME.GetContentType(ext));
            }
            catch (Exception ex)
            {
                Log.e("Failed to write file to HTTP {0}", ex.Message);
            }
        }
        public ContentGenerator(Type ContentRoot)
        {
            _rootPath = ContentRoot.FullName.Substring(0, ContentRoot.FullName.LastIndexOf("."));

            _pages = new Dictionary <string, string>();
            _files = new Dictionary <string, byte[]>();

            //Assembly a = Assembly.GetExecutingAssembly();
            Assembly a = Assembly.GetAssembly(ContentRoot);

            foreach (string name in a.GetManifestResourceNames())
            {
                if (MIME.GetMimeType(Path.GetExtension(name)).Contains("text"))
                {
                    using (Stream stream = a.GetManifestResourceStream(name))
                        using (StreamReader reader = new StreamReader(stream))
                        {
                            string pageContent = reader.ReadToEnd();
                            _pages.Add(name, pageContent);
                        }
                }
                else
                {
                    using (Stream stream = a.GetManifestResourceStream(name))
                    {
                        byte[] streamBytes = new byte[stream.Length];
                        stream.Read(streamBytes, 0, streamBytes.Length);
                        _files.Add(name, streamBytes);
                    }
                }
            }
        }
예제 #5
0
        public ContentServer(string[] prefixes, Type contentLocation, Func <HttpListenerRequest, Server.ResponseInformation> method = null)
        {
            ContentGenerator gen = new ContentGenerator(contentLocation);

            _wServer = new Server(prefixes, (request) =>
            {
                Server.ResponseInformation resp;
                if (method != null)
                {
                    resp = method(request);
                    if (resp != null)
                    {
                        if (resp.Content != null)
                        {
                            return(resp);
                        }
                    }
                }
                resp = new Server.ResponseInformation();

                resp.Content     = gen.GetContent(request.Url.AbsolutePath);
                resp.ContentType = MIME.GetMimeType(System.IO.Path.GetExtension(request.Url.AbsoluteUri));

                return(resp);
            });

            _wServer.Run();
        }
예제 #6
0
        // GET: /Report/DocView/n
        public IActionResult DocView(int?id)
        {
            string method = "Report/DocView";

            if (NullId(id, "PendingId", method))
            {
                return(RedirectToAction("Error", "Home"));
            }

            try
            {
                PendingReport report = null;
                if ((report = Read(id.Value, method)) == null)
                {
                    return(RedirectToAction("Error", "Home"));
                }

                string filename = report.eFileName;
                if (IsNull(filename, "eFileName", method))
                {
                    return(RedirectToAction("Error", "Home"));
                }

                _filesys.ChangeDirectory(Config.Get("UploadDirectory"));
                byte[] file = _filesys.FileDownload(filename);

                return(new FileContentResult(file, MIME.GetMimeType(Path.GetExtension(filename))));
            }
            catch (Exception ex)
            {
                Log.Me.Error("Exception in " + method + ": " + ex.Message);
                return(RedirectToAction("Error", "Home"));
            }
        }
예제 #7
0
        private static ActionResult ReturnFromService(Func <Stream> method, string defaultFile = null, string etag = null)
        {
            if (etag != null && HttpContext.Current.Request.Headers["If-None-Match"] == String.Format("\"{0}\"", etag))
            {
                HttpContext.Current.Response.StatusCode = (int)HttpStatusCode.NotModified;
                SetCacheHeaders(6 * 30, etag);
                return(new EmptyResult());
            }

            using (var scope = WCFClient.EnterOperationScope(Connections.Current.MASStream))
            {
                var image = method.Invoke();

                var returnCode = WCFClient.GetHeader <int>("responseCode");
                if ((HttpStatusCode)returnCode != HttpStatusCode.OK)
                {
                    // don't cache failed-to-load images very long, as artwork may be added later on
                    SetCacheHeaders(1);
                    if (defaultFile == null)
                    {
                        return(new HttpStatusCodeResult(returnCode));
                    }
                    else
                    {
                        string virtualPath  = ContentLocator.Current.LocateContent(defaultFile);
                        string physicalPath = HttpContext.Current.Server.MapPath(virtualPath);
                        return(new FilePathResult(physicalPath, MIME.GetFromFilename(physicalPath, "application/octet-stream")));
                    }
                }

                // we can cache these for quite long, as they probably won't change
                SetCacheHeaders(6 * 30, etag);
                return(new FileStreamResult(image, WCFClient.GetHeader <string>("contentType", "image/jpeg")));
            }
        }
예제 #8
0
 public void TestCanHandle()
 {
     Assert.IsTrue(MIME.CanHandle("aaaa.mp4"));
     Assert.IsTrue(MIME.CanHandle(".mp4"));
     Assert.IsFalse(MIME.CanHandle("aaa.exe"));
     Assert.IsFalse(MIME.CanHandle(".exe"));
 }
예제 #9
0
        public bool HandleRequest(HandlePackage package)
        {
            string host = package.RequestHeader.Host.ToLower();

            if (MachineData.HostNames.ContainsName(host))
            {
                // Prevent a giant messy loop of requests
                return(false);
            }

            string    completeURL = string.Format("http://{0}{1}{2}", host, package.RequestHeader.URL, package.RequestHeader.ConcatGetValues());
            WebClient webClient   = new WebClient();

            try
            {
                // Download the data and dump it into the stream
                byte[] proxyData = webClient.DownloadData(completeURL);
                package.ContentStream.Write(proxyData, 0, proxyData.Length);
                package.ResponseHeader.SetField("Content-Type", MIME.GetContentType(StringUtil.GetExtension(completeURL)));
                webClient.Dispose();

                // Well, that's all folks!
                return(true);
            }
            catch (Exception ex)
            {
                Log.e("Failed to do proxy magic:\n{0}", ex.Message);
                package.ContentStream.Write("Well something went wrong");
                return(true);
            }
        }
예제 #10
0
        public IActionResult OnGetDownload(string filename)
        {
            string ext = Path.GetExtension(filename);

            _filesys.ChangeDirectory(testDir);
            byte[] file = _filesys.FileDownload(filename);
            return(new FileContentResult(file, MIME.GetMimeType(ext)));
        }
예제 #11
0
        public Stream Download(string clientDescription, WebMediaType type, int?provider, string itemId, long?position)
        {
            // validate source first
            MediaSource source = new MediaSource(type, provider, itemId);

            if (!source.Exists)
            {
                throw new FileNotFoundException();
            }

            // create context
            DownloadContext context = new DownloadContext()
            {
                ClientDescription = clientDescription,
                Source            = source,
                StartTime         = DateTime.Now,
                Stream            = new ReadTrackingStreamWrapper(source.Retrieve()),
                MediaInfo         = MediaInfoHelper.LoadMediaInfoOrSurrogate(source) // for playerposition view
            };

            // seek to start position if wanted/needed
            if (position != null && position > 0)
            {
                if (context.Stream.CanSeek)
                {
                    context.Stream.Seek(position.Value, SeekOrigin.Begin);
                }
                else
                {
                    Log.Warn("Download: Cannot seek on stream, failed to set start position to {0}", position);
                }
            }

            // see comment in Streaming.cs:151
            string realIp = WCFUtil.GetHeaderValue("forwardedFor", "X-Forwarded-For");

            context.ClientIP = realIp == null?WCFUtil.GetClientIPAddress() : String.Format("{0} (via {1})", realIp, WCFUtil.GetClientIPAddress());

            // set headers for downloading
            WCFUtil.AddHeader("Content-Disposition", "attachment; filename=\"" + source.GetFileInfo().Name + "\"");
            if (source.MediaType != WebMediaType.TV)
            {
                WCFUtil.SetContentLength(source.GetFileInfo().Size);
            }

            // FIXME: there has to be a better way to do this
            string mime = MIME.GetFromFilename(source.GetFileInfo().Name);

            if (mime != null)
            {
                WCFUtil.SetContentType(mime);
            }

            // finally, save the context and return
            runningDownloads.Add(context);
            return(context.Stream);
        }
예제 #12
0
 public void TestGetType()
 {
     Assert.AreEqual(MIME.GetContentType(".mp4"), "video/mp4");
     Assert.AreEqual(MIME.GetContentType(".html"), "text/html");
     Assert.AreEqual(MIME.GetContentType(".png"), "image/png");
     Assert.AreEqual(MIME.GetContentType(".tiff"), "image/tiff");
     Assert.AreEqual(MIME.GetContentType(".exe"), "application/octet-stream");
     Assert.AreEqual(MIME.GetContentType(".dll"), "application/octet-stream");
     Assert.AreEqual(MIME.GetContentType(".msi"), "application/octet-stream");
 }
예제 #13
0
 public void TestIsVideo()
 {
     Assert.IsTrue(MIME.IsVideo("aaaa.mp4"));
     Assert.IsTrue(MIME.IsVideo(".mp4"));
     Assert.IsTrue(MIME.IsVideo("aaaa.webm"));
     Assert.IsTrue(MIME.IsVideo(".webm"));
     Assert.IsTrue(MIME.IsVideo("aaaa.ogg"));
     Assert.IsTrue(MIME.IsVideo(".ogg"));
     Assert.IsFalse(MIME.IsVideo("aaa.exe"));
     Assert.IsFalse(MIME.IsVideo(".exe"));
 }
예제 #14
0
 public static IActionResult WebFile(this ControllerBase controller, string path, string extension)
 {
     var(etag, length) = GetFileHTTPProperties(path);
     // Handle etag
     controller.Response.Headers.Add("ETag", '\"' + etag + '\"');
     if (controller.Request.Headers.Keys.Contains("If-None-Match") && controller.Request.Headers["If-None-Match"].ToString().Trim('\"') == etag)
     {
         return(new StatusCodeResult(304));
     }
     // Return file result.
     controller.Response.Headers.Add("Content-Length", length.ToString());
     return(controller.PhysicalFile(path, MIME.GetContentType(extension), true));
 }
예제 #15
0
파일: FileService.cs 프로젝트: BenyT/Pylon
 public static async Task <IActionResult> AiurFile(this ControllerBase controller, string path, string filename)
 {
     return(await Task.Run <IActionResult>(() =>
     {
         var fileInfo = new FileInfo(path);
         var extension = filename.LastIndexOf('.') > 0 ? filename.Substring(filename.LastIndexOf('.') + 1) : string.Empty;
         long etagHash = fileInfo.LastWriteTime.ToUniversalTime().ToFileTime() ^ fileInfo.Length;
         var etag = Convert.ToString(etagHash, 16);
         controller.Response.Headers.Add("ETag", '\"' + etag + '\"');
         if (controller.Request.Headers.Keys.Contains("If-None-Match") && controller.Request.Headers["If-None-Match"].ToString().Trim('\"') == etag)
         {
             return new StatusCodeResult(304);
         }
         controller.Response.Headers.Add("Content-Length", fileInfo.Length.ToString());
         return controller.PhysicalFile(path, MIME.GetContentType(extension), true);
     }));
 }
예제 #16
0
        public static async Task <IActionResult> AiurFile(this ControllerBase controller, string path, string filename, bool download = false)
        {
            await Task.Delay(0);

            var  fileInfo  = new FileInfo(path);
            var  extension = filename.Substring(filename.LastIndexOf('.') + 1);
            long etagHash  = fileInfo.LastWriteTime.ToUniversalTime().ToFileTime() ^ fileInfo.Length;
            var  _etag     = Convert.ToString(etagHash, 16);

            controller.Response.Headers.Add("ETag", '\"' + _etag + '\"');
            if (controller.Request.Headers.Keys.Contains("If-None-Match") && controller.Request.Headers["If-None-Match"].ToString().Trim('\"') == _etag)
            {
                return(new StatusCodeResult(304));
            }
            controller.Response.Headers.Add("Content-Length", fileInfo.Length.ToString());
            return(controller.PhysicalFile(path, MIME.GetContentType(extension, download)));
        }
예제 #17
0
        public ActionResult Download(WebMediaType type, string item)
        {
            // Create URL to GetMediaItem
            Log.Debug("User wants to download type={0}; item={1}", type, item);
            var queryString = HttpUtility.ParseQueryString(String.Empty); // you can't instantiate that class manually for some reason

            queryString["clientDescription"] = String.Format("WebMediaPortal download (user {0})", HttpContext.User.Identity.Name);
            queryString["type"]   = ((int)type).ToString();
            queryString["itemId"] = item;
            string     address = type == WebMediaType.TV || type == WebMediaType.Recording ? Connections.Current.Addresses.TAS : Connections.Current.Addresses.MAS;
            string     fullUrl = String.Format("http://{0}/MPExtended/StreamingService/stream/GetMediaItem?{1}", address, queryString.ToString());
            UriBuilder fullUri = new UriBuilder(fullUrl);

            // If we can access the file without any problems, let IIS stream it; that is a lot faster
            if (NetworkInformation.IsLocalAddress(fullUri.Host, false) && type != WebMediaType.TV)
            {
                var path = type == WebMediaType.Recording ?
                           Connections.Current.TAS.GetRecordingFileInfo(Int32.Parse(item)).Path :
                           Connections.Current.MAS.GetMediaItem(GetProvider(type), type, item).Path[0];
                if (System.IO.File.Exists(path))
                {
                    return(File(path, MIME.GetFromFilename(path, "application/octet-stream"), Path.GetFileName(path)));
                }
            }

            // If we connect to the services at localhost, actually give the extern IP address to users
            if (NetworkInformation.IsLocalAddress(fullUri.Host, false))
            {
                fullUri.Host = NetworkInformation.GetIPAddress(false);
            }

            // Do the actual streaming
            if (GetStreamMode() == StreamType.Proxied)
            {
                Log.Debug("Proxying download at {0}", fullUri.ToString());
                GetStreamControl(type).AuthorizeStreaming();
                ProxyStream(fullUri.ToString());
            }
            else if (GetStreamMode() == StreamType.Direct)
            {
                Log.Debug("Redirecting user to download at {0}", fullUri.ToString());
                GetStreamControl(type).AuthorizeRemoteHostForStreaming(HttpContext.Request.UserHostAddress);
                return(Redirect(fullUri.ToString()));
            }
            return(new EmptyResult());
        }
예제 #18
0
        public Stream GetFile(string filePath)
        {
            System.Diagnostics.Debug.WriteLine("Request file:" + filePath);
            //for test right now
            WebOperationContext context = WebOperationContext.Current;
            var path = Path.Combine(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Web"), filePath);

            System.Diagnostics.Debug.WriteLine(path);
            if (context == null)
            {
                return(null);
            }
            if (File.Exists(path))
            {
                var fi = new FileInfo(path);
                if (MIME.ContainsKey(fi.Extension))
                {
                    context.OutgoingResponse.ContentType = MIME[fi.Extension];
                }
                else
                {
                    context.OutgoingResponse.ContentType = "application/octet-stream";
                }
                try
                {
                    FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read);
                    context.OutgoingResponse.ContentLength = fs.Length;
                    return(fs);
                }
                catch (Exception e)
                {
                    context.OutgoingResponse.StatusCode  = HttpStatusCode.ServiceUnavailable;
                    context.OutgoingResponse.ContentType = "application/plain";
                    return(new MemoryStream(Encoding.UTF8.GetBytes(e.ToString())));
                }
            }
            context.OutgoingResponse.StatusCode  = HttpStatusCode.NotFound;
            context.OutgoingResponse.ContentType = "application/plain";
            return(new MemoryStream(Encoding.UTF8.GetBytes("Not Found")));
        }
 public override string ToString()
 {
     return(string.Format(@"data:{0};base64,{1}", MIME.ToLower(), Convert.ToBase64String(Data)));
 }
예제 #20
0
 public virtual void VisitMIME(MIME node)
 {
 }
예제 #21
0
        public virtual void VisitItem(Object item)
        {
            if (item == null)
            {
                return;
            }

            Module module = item as Module;

            if (module != null)
            {
                VisitModule(module);
                return;
            }
            Product product = item as Product;

            if (product != null)
            {
                VisitProduct(product);
                return;
            }
            Feature feature = item as Feature;

            if (feature != null)
            {
                VisitFeature(feature);
                return;
            }
            AdvtExecuteSequence advtExecuteSequence = item as AdvtExecuteSequence;

            if (advtExecuteSequence != null)
            {
                VisitAdvtExecuteSequence(advtExecuteSequence);
                return;
            }
            InstallUISequence installUISequence = item as InstallUISequence;

            if (installUISequence != null)
            {
                VisitInstallUISequence(installUISequence);
                return;
            }
            User user = item as User;

            if (user != null)
            {
                VisitUser(user);
                return;
            }
            Upgrade upgrade = item as Upgrade;

            if (upgrade != null)
            {
                VisitUpgrade(upgrade);
                return;
            }
            Directory directory = item as Directory;

            if (directory != null)
            {
                VisitDirectory(directory);
                return;
            }
            PropertyRef propertyRef = item as PropertyRef;

            if (propertyRef != null)
            {
                VisitPropertyRef(propertyRef);
                return;
            }
            WebSite webSite = item as WebSite;

            if (webSite != null)
            {
                VisitWebSite(webSite);
                return;
            }
            AdminUISequence adminUISequence = item as AdminUISequence;

            if (adminUISequence != null)
            {
                VisitAdminUISequence(adminUISequence);
                return;
            }
            CustomAction customAction = item as CustomAction;

            if (customAction != null)
            {
                VisitCustomAction(customAction);
                return;
            }
            DirectoryRef directoryRef = item as DirectoryRef;

            if (directoryRef != null)
            {
                VisitDirectoryRef(directoryRef);
                return;
            }
            AppId appId = item as AppId;

            if (appId != null)
            {
                VisitAppId(appId);
                return;
            }
            Media media = item as Media;

            if (media != null)
            {
                VisitMedia(media);
                return;
            }
            CustomTable customTable = item as CustomTable;

            if (customTable != null)
            {
                VisitCustomTable(customTable);
                return;
            }
            Condition condition = item as Condition;

            if (condition != null)
            {
                VisitCondition(condition);
                return;
            }
            SFPCatalog sFPCatalog = item as SFPCatalog;

            if (sFPCatalog != null)
            {
                VisitSFPCatalog(sFPCatalog);
                return;
            }
            UI ui = item as UI;

            if (ui != null)
            {
                VisitUI(ui);
                return;
            }
            FragmentRef fragmentRef = item as FragmentRef;

            if (fragmentRef != null)
            {
                VisitFragmentRef(fragmentRef);
                return;
            }
            Icon icon = item as Icon;

            if (icon != null)
            {
                VisitIcon(icon);
                return;
            }
            Property property = item as Property;

            if (property != null)
            {
                VisitProperty(property);
                return;
            }
            FeatureRef featureRef = item as FeatureRef;

            if (featureRef != null)
            {
                VisitFeatureRef(featureRef);
                return;
            }
            WebDirProperties webDirProperties = item as WebDirProperties;

            if (webDirProperties != null)
            {
                VisitWebDirProperties(webDirProperties);
                return;
            }
            ComplianceCheck complianceCheck = item as ComplianceCheck;

            if (complianceCheck != null)
            {
                VisitComplianceCheck(complianceCheck);
                return;
            }
            InstallExecuteSequence installExecuteSequence = item as InstallExecuteSequence;

            if (installExecuteSequence != null)
            {
                VisitInstallExecuteSequence(installExecuteSequence);
                return;
            }
            AdminExecuteSequence adminExecuteSequence = item as AdminExecuteSequence;

            if (adminExecuteSequence != null)
            {
                VisitAdminExecuteSequence(adminExecuteSequence);
                return;
            }
            Binary binary = item as Binary;

            if (binary != null)
            {
                VisitBinary(binary);
                return;
            }
            Group group = item as Group;

            if (group != null)
            {
                VisitGroup(group);
                return;
            }
            WebApplication webApplication = item as WebApplication;

            if (webApplication != null)
            {
                VisitWebApplication(webApplication);
                return;
            }
            ActionSequenceType actionSequenceType = item as ActionSequenceType;

            if (actionSequenceType != null)
            {
                VisitActionSequenceType(actionSequenceType);
                return;
            }
            ActionModuleSequenceType actionModuleSequenceType = item as ActionModuleSequenceType;

            if (actionModuleSequenceType != null)
            {
                VisitActionModuleSequenceType(actionModuleSequenceType);
                return;
            }
            BillboardAction billboardAction = item as BillboardAction;

            if (billboardAction != null)
            {
                VisitBillboardAction(billboardAction);
                return;
            }
            Error error = item as Error;

            if (error != null)
            {
                VisitError(error);
                return;
            }
            Dialog dialog = item as Dialog;

            if (dialog != null)
            {
                VisitDialog(dialog);
                return;
            }
            ProgressText progressText = item as ProgressText;

            if (progressText != null)
            {
                VisitProgressText(progressText);
                return;
            }
            TextStyle textStyle = item as TextStyle;

            if (textStyle != null)
            {
                VisitTextStyle(textStyle);
                return;
            }
            ListBox listBox = item as ListBox;

            if (listBox != null)
            {
                VisitListBox(listBox);
                return;
            }
            ListView listView = item as ListView;

            if (listView != null)
            {
                VisitListView(listView);
                return;
            }
            ComboBox comboBox = item as ComboBox;

            if (comboBox != null)
            {
                VisitComboBox(comboBox);
                return;
            }
            UIText uIText = item as UIText;

            if (uIText != null)
            {
                VisitUIText(uIText);
                return;
            }
            RadioGroup radioGroup = item as RadioGroup;

            if (radioGroup != null)
            {
                VisitRadioGroup(radioGroup);
                return;
            }
            IniFileSearch iniFileSearch = item as IniFileSearch;

            if (iniFileSearch != null)
            {
                VisitIniFileSearch(iniFileSearch);
                return;
            }
            RegistrySearch registrySearch = item as RegistrySearch;

            if (registrySearch != null)
            {
                VisitRegistrySearch(registrySearch);
                return;
            }
            ComponentSearch componentSearch = item as ComponentSearch;

            if (componentSearch != null)
            {
                VisitComponentSearch(componentSearch);
                return;
            }
            FileSearch fileSearch = item as FileSearch;

            if (fileSearch != null)
            {
                VisitFileSearch(fileSearch);
                return;
            }
            DirectorySearch directorySearch = item as DirectorySearch;

            if (directorySearch != null)
            {
                VisitDirectorySearch(directorySearch);
                return;
            }
            File file = item as File;

            if (file != null)
            {
                VisitFile(file);
                return;
            }
            Component component = item as Component;

            if (component != null)
            {
                VisitComponent(component);
                return;
            }
            Merge merge = item as Merge;

            if (merge != null)
            {
                VisitMerge(merge);
                return;
            }
            Custom custom = item as Custom;

            if (custom != null)
            {
                VisitCustom(custom);
                return;
            }
            WebError webError = item as WebError;

            if (webError != null)
            {
                VisitWebError(webError);
                return;
            }
            WebVirtualDir webVirtualDir = item as WebVirtualDir;

            if (webVirtualDir != null)
            {
                VisitWebVirtualDir(webVirtualDir);
                return;
            }
            WebDir webDir = item as WebDir;

            if (webDir != null)
            {
                VisitWebDir(webDir);
                return;
            }
            WebFilter webFilter = item as WebFilter;

            if (webFilter != null)
            {
                VisitWebFilter(webFilter);
                return;
            }
            MergeRef mergeRef = item as MergeRef;

            if (mergeRef != null)
            {
                VisitMergeRef(mergeRef);
                return;
            }
            Subscribe subscribe = item as Subscribe;

            if (subscribe != null)
            {
                VisitSubscribe(subscribe);
                return;
            }
            Publish publish = item as Publish;

            if (publish != null)
            {
                VisitPublish(publish);
                return;
            }
            TypeLib typeLib = item as TypeLib;

            if (typeLib != null)
            {
                VisitTypeLib(typeLib);
                return;
            }
            Shortcut shortcut = item as Shortcut;

            if (shortcut != null)
            {
                VisitShortcut(shortcut);
                return;
            }
            ODBCTranslator oDBCTranslator = item as ODBCTranslator;

            if (oDBCTranslator != null)
            {
                VisitODBCTranslator(oDBCTranslator);
                return;
            }
            Permission permission = item as Permission;

            if (permission != null)
            {
                VisitPermission(permission);
                return;
            }
            Class _class = item as Class;

            if (_class != null)
            {
                VisitClass(_class);
                return;
            }
            CopyFile copyFile = item as CopyFile;

            if (copyFile != null)
            {
                VisitCopyFile(copyFile);
                return;
            }
            Patch patch = item as Patch;

            if (patch != null)
            {
                VisitPatch(patch);
                return;
            }
            ODBCDriver oDBCDriver = item as ODBCDriver;

            if (oDBCDriver != null)
            {
                VisitODBCDriver(oDBCDriver);
                return;
            }
            PerfCounter perfCounter = item as PerfCounter;

            if (perfCounter != null)
            {
                VisitPerfCounter(perfCounter);
                return;
            }
            FileShare fileShare = item as FileShare;

            if (fileShare != null)
            {
                VisitFileShare(fileShare);
                return;
            }
            Certificate certificate = item as Certificate;

            if (certificate != null)
            {
                VisitCertificate(certificate);
                return;
            }
            Category category = item as Category;

            if (category != null)
            {
                VisitCategory(category);
                return;
            }
            WebAppPool webAppPool = item as WebAppPool;

            if (webAppPool != null)
            {
                VisitWebAppPool(webAppPool);
                return;
            }
            SqlString sqlString = item as SqlString;

            if (sqlString != null)
            {
                VisitSqlString(sqlString);
                return;
            }
            ServiceControl serviceControl = item as ServiceControl;

            if (serviceControl != null)
            {
                VisitServiceControl(serviceControl);
                return;
            }
            IsolateComponent isolateComponent = item as IsolateComponent;

            if (isolateComponent != null)
            {
                VisitIsolateComponent(isolateComponent);
                return;
            }
            ServiceConfig serviceConfig = item as ServiceConfig;

            if (serviceConfig != null)
            {
                VisitServiceConfig(serviceConfig);
                return;
            }
            WebProperty webProperty = item as WebProperty;

            if (webProperty != null)
            {
                VisitWebProperty(webProperty);
                return;
            }
            SqlScript sqlScript = item as SqlScript;

            if (sqlScript != null)
            {
                VisitSqlScript(sqlScript);
                return;
            }
            SqlDatabase sqlDatabase = item as SqlDatabase;

            if (sqlDatabase != null)
            {
                VisitSqlDatabase(sqlDatabase);
                return;
            }
            WebLockdown webLockdown = item as WebLockdown;

            if (webLockdown != null)
            {
                VisitWebLockdown(webLockdown);
                return;
            }
            Extension extension = item as Extension;

            if (extension != null)
            {
                VisitExtension(extension);
                return;
            }
            ReserveCost reserveCost = item as ReserveCost;

            if (reserveCost != null)
            {
                VisitReserveCost(reserveCost);
                return;
            }
            RemoveFile removeFile = item as RemoveFile;

            if (removeFile != null)
            {
                VisitRemoveFile(removeFile);
                return;
            }
            ProgId progId = item as ProgId;

            if (progId != null)
            {
                VisitProgId(progId);
                return;
            }
            Microsoft.Tools.WindowsInstallerXml.Serialize.Environment environment = item as
                                                                                    Microsoft.Tools.WindowsInstallerXml.Serialize.Environment;
            if (environment != null)
            {
                VisitEnvironment(environment);
                return;
            }
            ServiceInstall serviceInstall = item as ServiceInstall;

            if (serviceInstall != null)
            {
                VisitServiceInstall(serviceInstall);
                return;
            }
            IniFile iniFile = item as IniFile;

            if (iniFile != null)
            {
                VisitIniFile(iniFile);
                return;
            }
            Registry registry = item as Registry;

            if (registry != null)
            {
                VisitRegistry(registry);
                return;
            }
            CreateFolder createFolder = item as CreateFolder;

            if (createFolder != null)
            {
                VisitCreateFolder(createFolder);
                return;
            }
            MIME mIME = item as MIME;

            if (mIME != null)
            {
                VisitMIME(mIME);
                return;
            }
            Verb verb = item as Verb;

            if (verb != null)
            {
                VisitVerb(verb);
                return;
            }
        }
예제 #22
0
        public ClientRequest(BinaryReader S, IPAddress source)
        {
            this.Address    = source;
            this.Reader     = S;
            this.headerList = new List <string> ();
            string line = String.Empty;
            char   cb;

            while (true)
            {
                while (true)
                {
                    cb = S.ReadChar();
                    if (cb == '\n')
                    {
                        break;
                    }
                    if (cb == '\r')
                    {
                        continue;
                    }
                    line += cb;
                }
                if (line == String.Empty)
                {
                    break;
                }
                else
                {
                    headerList.Add(String.Copy(line));
                    line = String.Empty;
                }
            }
            this.RequestTime = new TimeTracker();
            string[] requestLine = headerList [0].Split(' ');
            this.type = requestLine[0];
            string decpath  = HttpUtility.UrlDecode(requestLine[1]);
            int    argindex = decpath.IndexOf('?');

            if (argindex == -1 || argindex == decpath.Length - 1)
            {
                this.path = decpath.Trim('?');
            }
            else
            {
                string[] rawargs = decpath.Substring(argindex + 1).Split('&');
                this.path = decpath.Substring(0, argindex);
                foreach (string kvp in rawargs)
                {
                    if (kvp.Length < 3)
                    {
                        continue;
                    }
                    string[] splitargs = kvp.Split('=');
                    if (splitargs.Length != 2)
                    {
                        continue;
                    }
                    this.Arguments[splitargs[0]] = splitargs[1];
                }
            }
            foreach (string h in headerList)
            {
                string[] lineInstruction = h.Split(new string[] { ": " }, 2, StringSplitOptions.None);
                if (lineInstruction.Length > 1)
                {
                    this.headerDict [lineInstruction [0]] = lineInstruction [1];
                }
                switch (lineInstruction[0])
                {
                case "Content-Type":
                    string boundary;
                    this.contenttype = MIME.FromText(lineInstruction [1], out boundary);
                    if (boundary != String.Empty)
                    {
                        this.boundaryMultipart = boundary;
                    }
                    break;

                case "Content-Length":
                    this.contentlength = Convert.ToInt32(lineInstruction [1]);
                    break;

                case "Host":
                    this.host   = lineInstruction [1];
                    this.sphost = this.host.Split('.');
                    Array.Reverse(sphost);
                    break;

                case "Cookie":
                    this.Cookies = lineInstruction[1].Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries).Select(x => x.Trim().Split(new char[] { '=' }, StringSplitOptions.None)).ToDictionary(x => x[0], x => x[1]);
                    break;

                case "If-Modified-Since":
                    DateTime.TryParseExact(lineInstruction[1], "R", System.Globalization.DateTimeFormatInfo.CurrentInfo, System.Globalization.DateTimeStyles.AllowWhiteSpaces, out LastModified);

                case "If-None-Match":
                    this.ETag = lineInstruction [1].Trim('\"');
                    break;
                }
            }
            //Console.WriteLine (this.Header);
        }
예제 #23
0
        //
        // Streaming
        public ActionResult Download(WebMediaType type, string item, string token = null)
        {
            // Check authentication
            if (!IsUserAuthenticated())
            {
                string expectedData  = String.Format("{0}_{1}_{2}", type, item, HttpContext.Application["randomToken"]);
                byte[] expectedBytes = SHA256.Create().ComputeHash(Encoding.UTF8.GetBytes(expectedData));
                string expectedToken = expectedBytes.ToHexString();
                if (token == null || expectedToken != token)
                {
                    Log.Error("Denying download type={0}, item={1}, token={2}, ip={3}: user is not logged in and token is invalid", type, item, token, Request.UserHostAddress);
                    return(new HttpUnauthorizedResult());
                }
            }

            // Create URL to GetMediaItem
            Log.Debug("User wants to download type={0}; item={1}", type, item);
            var queryString     = HttpUtility.ParseQueryString(String.Empty); // you can't instantiate that class manually for some reason
            var userDescription = !String.IsNullOrEmpty(HttpContext.User.Identity.Name) ? String.Format(" (user {0})", HttpContext.User.Identity) :
                                                                              // TODO: also grab the user from the Authorization header here
                                  !String.IsNullOrEmpty(token) ? " (token-based download)" : String.Empty;

            queryString["clientDescription"] = "WebMediaPortal download" + userDescription;
            queryString["type"]   = ((int)type).ToString();
            queryString["itemId"] = item;
            string     address = type == WebMediaType.TV || type == WebMediaType.Recording ? Connections.Current.Addresses.TAS : Connections.Current.Addresses.MAS;
            string     fullUrl = String.Format("http://{0}/MPExtended/StreamingService/stream/GetMediaItem?{1}", address, queryString.ToString());
            UriBuilder fullUri = new UriBuilder(fullUrl);

            // If we can access the file without any problems, let IIS stream it; that is a lot faster
            if (NetworkInformation.IsLocalAddress(fullUri.Host) && type != WebMediaType.TV)
            {
                var path = type == WebMediaType.Recording ?
                           Connections.Current.TAS.GetRecordingFileInfo(Int32.Parse(item)).Path :
                           Connections.Current.MAS.GetMediaItem(GetProvider(type), type, item).Path[0];
                if (System.IO.File.Exists(path))
                {
                    return(File(path, MIME.GetFromFilename(path, "application/octet-stream"), Path.GetFileName(path)));
                }
            }

            // If we connect to the services at localhost, actually give the extern IP address to users
            if (NetworkInformation.IsLocalAddress(fullUri.Host))
            {
                fullUri.Host = NetworkInformation.GetIPAddressForUri();
            }

            // Do the actual streaming
            if (GetStreamMode() == StreamType.Proxied)
            {
                Log.Debug("Proxying download at {0}", fullUri.ToString());
                GetStreamControl(type).AuthorizeStreaming();
                ProxyStream(fullUri.ToString());
            }
            else if (GetStreamMode() == StreamType.Direct)
            {
                Log.Debug("Redirecting user to download at {0}", fullUri.ToString());
                GetStreamControl(type).AuthorizeRemoteHostForStreaming(HttpContext.Request.UserHostAddress);
                return(Redirect(fullUri.ToString()));
            }
            return(new EmptyResult());
        }
예제 #24
0
 internal static Instruction ContentType(MIME type)
 {
     return(new Instruction("Content-Type", type.ToString()));
 }
예제 #25
0
 public void SetBody(byte[] B, MIME M)
 {
     this.httpBody = new GeneratedResource(B, M);
 }
예제 #26
0
        static void Main(string[] args)
        {
            string   sFail;
            bool     bFail;
            string   sTest, sTest2, s;
            DateTime dBadDate = new DateTime(1, 1, 1);
            DateTime dTest;

            sFail  = "";
            sTest  = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
            sTest2 = "ABC\nDEFGHI\tJKLMNOPQRSTUVWXYZ";

            // Cache Tests
            Cache <string> .GetCache().Set("one", () => "First Value");

            Cache <string> .GetCache().Set("two", () => "Second Value");

            List <string> l = Cache <string> .GetCache().ListKeys();

            foreach (string s1 in l)
            {
                if (s1 != "one" && s1 != "two")
                {
                    sFail += "CacheTest1 ";
                }
            }
            if (Cache <string> .GetCache().Get("two", () => "Second Value") != "Second Value")
            {
                sFail += "CacheTest2 ";
            }

            // Config Tests
            try
            {
                Config.Setup("test.xml", ".", "web", "app");
            }
            catch (Exception ex)
            {
                Console.WriteLine("Config.Setup failed with: " + ex.Message);
                sFail += "ConfigTest1 ";
            }
            if (Config.ContentRoot != ".")
            {
                sFail += "ConfigTest2 ";
            }
            if (Config.WebRoot != "web")
            {
                sFail += "ConfigTest3 ";
            }
            if (Config.AppName != "app")
            {
                sFail += "ConfigTest4 ";
            }
            if (Config.AppURL.Left(8) != "http://r")
            {
                sFail += "ConfigTest5 ";
            }
            if (Config.Env.Left(4) != "Prod")
            {
                sFail += "ConfigTest6 ";
            }
            if (Config.Debug)
            {
                sFail += "ConfigTest7 ";
            }
            string delim = System.IO.Path.DirectorySeparatorChar.ToString();

            if (Config.LogFile != "." + delim + "Logs" + delim + "app.log")
            {
                sFail += "ConfigTest8 ";
            }

            try
            {
                Config.Setup("appsettings.json", ".", "web", "app");
            }
            catch (Exception ex)
            {
                Console.WriteLine("Config.Setup failed with: " + ex.Message);
                sFail += "ConfigTest9 ";
            }
            if (Config.ContentRoot != ".")
            {
                sFail += "ConfigTest10 ";
            }
            if (Config.WebRoot != "web")
            {
                sFail += "ConfigTest11 ";
            }
            if (Config.AppName != "app")
            {
                sFail += "ConfigTest12 ";
            }
            if (Config.AppURL.Left(8) != "http://r")
            {
                sFail += "ConfigTest13 ";
            }
            if (Config.Env.Left(4) != "Prod")
            {
                sFail += "ConfigTest14 ";
            }
            if (Config.Debug)
            {
                sFail += "ConfigTest15 ";
            }
            if (Config.LogFile != "." + delim + "Logs" + delim + "app.log")
            {
                sFail += "ConfigTest16 ";
            }


            // DateTime tests

            // Time Tests

            // Test Midnight, Noon and SetTime
            if (DateTime.Now.Midnight().Hour != 0)
            {
                sFail += "Midnight ";
            }
            if (DateTime.Now.Noon().Hour != 12)
            {
                sFail += "Noon ";
            }
            if (DateTime.Now.SetTime(5, 59).Minute != 59)
            {
                sFail += "SetTime1 ";
            }
            if (DateTime.Now.SetTime(5, 59).Second != 0)
            {
                sFail += "SetTime2 ";
            }

            // Date Tests

            // Test DOW
            if ("24/12/2009".ToDateTime().DOW() != 4)
            {
                sFail += "DOW1 ";
            }
            if ("27/12/2009".ToDateTime().DOW() != 7)
            {
                sFail += "DOW2 ";
            }
            if ("29/02/2008".ToDateTime().DOW() != 5)
            {
                sFail += "DOW3 ";
            }
            if ("01/01/2010".ToDateTime().DOW() != 5)
            {
                sFail += "DOW4 ";
            }

            // Test Jan1WeekDay
            // Answers as per: http://en.wikipedia.org/wiki/File:Permanent_calendar.png
            if ("1/1/1600".ToDateTime().Jan1WeekDay() != 6)
            {
                sFail += "Jan1WeekDay1 ";
            }
            if ("1/1/1601".ToDateTime().Jan1WeekDay() != 1)
            {
                sFail += "Jan1WeekDay2 ";
            }
            if ("1/1/1602".ToDateTime().Jan1WeekDay() != 2)
            {
                sFail += "Jan1WeekDay3 ";
            }
            if ("1/1/1603".ToDateTime().Jan1WeekDay() != 3)
            {
                sFail += "Jan1WeekDay4 ";
            }
            if ("1/1/1604".ToDateTime().Jan1WeekDay() != 4)
            {
                sFail += "Jan1WeekDay5 ";
            }
            if ("1/1/1605".ToDateTime().Jan1WeekDay() != 6)
            {
                sFail += "Jan1WeekDay6 ";
            }
            if ("1/1/1606".ToDateTime().Jan1WeekDay() != 7)
            {
                sFail += "Jan1WeekDay7 ";
            }
            if ("1/1/1607".ToDateTime().Jan1WeekDay() != 1)
            {
                sFail += "Jan1WeekDay8 ";
            }
            if ("1/1/1608".ToDateTime().Jan1WeekDay() != 2)
            {
                sFail += "Jan1WeekDay9 ";
            }
            if ("1/1/1609".ToDateTime().Jan1WeekDay() != 4)
            {
                sFail += "Jan1WeekDay10 ";
            }
            if ("1/1/1610".ToDateTime().Jan1WeekDay() != 5)
            {
                sFail += "Jan1WeekDay11 ";
            }
            if ("1/1/1611".ToDateTime().Jan1WeekDay() != 6)
            {
                sFail += "Jan1WeekDay12 ";
            }
            if ("1/1/1612".ToDateTime().Jan1WeekDay() != 7)
            {
                sFail += "Jan1WeekDay13 ";
            }
            if ("1/1/1613".ToDateTime().Jan1WeekDay() != 2)
            {
                sFail += "Jan1WeekDay14 ";
            }
            if ("1/1/1614".ToDateTime().Jan1WeekDay() != 3)
            {
                sFail += "Jan1WeekDay15 ";
            }
            if ("1/1/1615".ToDateTime().Jan1WeekDay() != 4)
            {
                sFail += "Jan1WeekDay16 ";
            }
            if ("1/1/1616".ToDateTime().Jan1WeekDay() != 5)
            {
                sFail += "Jan1WeekDay17 ";
            }
            if ("1/1/1617".ToDateTime().Jan1WeekDay() != 7)
            {
                sFail += "Jan1WeekDay18 ";
            }
            if ("1/1/1618".ToDateTime().Jan1WeekDay() != 1)
            {
                sFail += "Jan1WeekDay19 ";
            }

            // Test DOY
            dTest = "1/1/2009".ToDateTime();
            bFail = false;
            for (int i = 0; i < 365; i++)
            {
                if (dTest.DOY() != i + 1)
                {
                    bFail = true;
                }
                dTest = dTest.AddDays(1);
            }
            if (bFail)
            {
                sFail += "DOY1 ";
            }

            dTest = "1/1/2008".ToDateTime();
            bFail = false;
            for (int i = 0; i < 366; i++)
            {
                if (dTest.DOY() != i + 1)
                {
                    bFail = true;
                }
                dTest = dTest.AddDays(1);
            }
            if (bFail)
            {
                sFail += "DOY2 ";
            }

            // Test IsLeapYear
            if ("1/1/2009".ToDateTime().IsLeapYear() == true)
            {
                sFail += "IsLeapYear1 ";
            }
            if ("1/1/1600".ToDateTime().IsLeapYear() == false)
            {
                sFail += "IsLeapYear2 ";
            }
            if ("1/1/1700".ToDateTime().IsLeapYear() == true)
            {
                sFail += "IsLeapYear4 ";
            }
            if ("1/1/1800".ToDateTime().IsLeapYear() == true)
            {
                sFail += "IsLeapYear5 ";
            }
            if ("1/1/1900".ToDateTime().IsLeapYear() == true)
            {
                sFail += "IsLeapYear6 ";
            }
            if ("1/1/2000".ToDateTime().IsLeapYear() == false)
            {
                sFail += "IsLeapYear3 ";
            }
            if ("1/1/2100".ToDateTime().IsLeapYear() == true)
            {
                sFail += "IsLeapYear7 ";
            }
            if ("1/1/2200".ToDateTime().IsLeapYear() == true)
            {
                sFail += "IsLeapYear8 ";
            }
            if ("1/1/2300".ToDateTime().IsLeapYear() == true)
            {
                sFail += "IsLeapYear9 ";
            }

            // Test ISOWeekNum
            if ("1/3/2020".ToDateTime().ISOWeekNum() != 9)
            {
                sFail += "ISOWeekNum1 ";
            }
            if ("3/1/2010".ToDateTime().ISOWeekNum() != 53)
            {
                sFail += "ISOWeekNum2 ";
            }

            // Test ISOWeekOne
            if ("1/3/2009".ToDateTime().ISOWeekOne() != "29/12/2008".ToDateTime())
            {
                sFail += "ISOWeekOne ";
            }

            // Test ISOYear
            if ("3/1/2010".ToDateTime().ISOYear() != 2009)
            {
                sFail += "ISOWeekOne ";
            }

            // Test ToDateStamp
            if ("25/12/2019".ToDateTime().Noon().ToDateStamp() != "201912251200")
            {
                sFail += "ToDateStamp ";
            }

            // Test ToLogStamp
            if ("25/12/2019".ToDateTime().Midnight().ToLogStamp() != "25/12 00:00:00")
            {
                sFail += "ToLogStamp ";
            }

            // Test ToDateString
            if ("25/12/2019".ToDateTime().ToDateString() != "25/12/2019")
            {
                sFail += "ToDateString ";
            }

            // Test ToISODateString
            if ("1/3/2020".ToDateTime().ToISODateString() != "2020-9-7")
            {
                sFail += "ToISODateString ";
            }

            // Test Encryption
            Encryption.Key = string.Format("TheLORDismyShepherdIshallnot{0:dd}inwantHemakes=", DateTime.Now);
            if (Encryption.Decrypt(Encryption.Encrypt(sTest)) != sTest)
            {
                sFail += "Encryption ";
            }

            // Test Log and FileRead
            Log.Me.LogFile = "Test.log";
            Log.Me.Info("Hello, World");
            using (FileRead f = new FileRead("." + delim, "Test.log")) s = f.ReadLine();
            if (s.Left(9) != DateTime.Now.ToLogStamp().Left(9))
            {
                sFail += "Log&FileRead1 ";
            }
            if (s.Right(21) != "] INFO : Hello, World")
            {
                sFail += "Log&FileRead2 ";
            }
            File.Delete("Test.Log");

            // Test MIME
            if (MIME.GetMimeType("mp3") != "audio/mpeg")
            {
                sFail += "MIME ";
            }

            // String Tests

            // Test Truncate
            if (sTest.Truncate(12) != "ABCDEFGHIJKL")
            {
                sFail += "Truncate ";
            }

            // Test Left
            if (sTest.Left(10) != "ABCDEFGHIJ")
            {
                sFail += "Left1 ";
            }
            if (sTest.Left(50) != sTest)
            {
                sFail += "Left2 ";
            }

            // Test Mid
            if (sTest.Mid(25, 1) != "Z")
            {
                sFail += "Mid1 ";
            }
            if (sTest.Mid(26, 1) != "")
            {
                sFail += "Mid2 ";
            }
            if (sTest.Mid(27, 50) != "")
            {
                sFail += "Mid3 ";
            }
            if (sTest.Mid(10, 3) != "KLM")
            {
                sFail += "Mid4 ";
            }
            if (sTest.Mid(16, 20) != "QRSTUVWXYZ")
            {
                sFail += "Mid5 ";
            }

            // Test Right
            if (sTest.Right(10) != "QRSTUVWXYZ")
            {
                sFail += "Right1 ";
            }
            if (sTest.Right(50) != sTest)
            {
                sFail += "Right2 ";
            }

            // Test ThrowOnNullOrEmpty
            try
            {
                s = null;
                s.ThrowOnNullOrEmpty("s", "message");
                sFail += "ThrowOnNullOrEmpty ";
            }
            catch {}

            //Test IsInteger
            if ("1.0".IsInteger())
            {
                sFail += "IsInteger1 ";
            }
            if ("?z£".IsInteger())
            {
                sFail += "IsInteger2 ";
            }
            if ("a".IsInteger())
            {
                sFail += "IsInteger3 ";
            }
            if (!("123".IsInteger()))
            {
                sFail += "IsInteger4 ";
            }

            //Test ToInteger
            if ("10".ToInteger() != 10)
            {
                sFail += "ToInteger1 ";
            }
            if ("-10".ToInteger() != -10)
            {
                sFail += "ToInteger2 ";
            }
            try
            {
                int i = "fred".ToInteger();
                sFail += "ToInteger3 ";
            }
            catch {}

            // Test ToDouble
            if ("5.4".ToDouble() != 5.4)
            {
                sFail += "ToDouble ";
            }

            // Test ToBool
            if ("false".ToBool())
            {
                sFail += "ToBool ";
            }

            // Test ToEnum<T>
            if ("THURSDAY".ToEnum <DayOfWeek>(true) != DayOfWeek.Thursday)
            {
                sFail += "ToEnum ";
            }

            // Test CleanString
            if (sTest2.CleanString() != sTest)
            {
                sFail += "CleanString ";
            }

            // Test EscapeSingleQuote
            if ("abc\'xyz".EscapeSingleQuote() != "abc\'\'xyz")
            {
                sFail += "EscapeSingleQuote ";
            }

            // Test StripQuotes
            if ("\"abc\"".StripQuotes() != "abc")
            {
                sFail += "StripQuotes ";
            }

            // Test RemoveNonNumeric
            if ("a1b2c3.4xyz".RemoveNonNumeric() != "1234")
            {
                sFail += "RemoveNonNumeric ";
            }

            // Test ToDateTime
            if ("".ToDateTime() != dBadDate)
            {
                sFail += "ToDateTime1 ";
            }
            if ("fred".ToDateTime() != dBadDate)
            {
                sFail += "ToDateTime2 ";
            }

            // Test AsciiCtlStrip
            if ("abcde\vfgh\rijk".AsciiCtlStrip() != "abcdefghijk")
            {
                sFail += "AsciiCtlStrip ";
            }

            // Test MailMerge and ToDict
            if ("Hi Mr {Fred}".MailMerge("Fred=Bloggs".ToDict(), "{}") != "Hi Mr Bloggs")
            {
                sFail += "MailMerge&ToDict ";
            }

            // Test NormalPath
            if ("abc\\def".NormalPath() != "abc/def")
            {
                sFail += "NormalPath ";
            }

            // Test Padding
            if ("abcdef".Padding(4, '=') != "abcdef==")
            {
                sFail += "Padding ";
            }

            // Test Wordise
            s = "one two   three  \"Fred Bloggs\"   ";
            if (s.Wordise().ListToString(":") != "one:two:three:\"Fred Bloggs\"")
            {
                sFail += "Wordise ";
            }

            // Test Match
            if (!("abcde".Match("abcd")))
            {
                sFail += "Match ";
            }

            // Test ToStream
            StreamReader reader = new StreamReader(sTest.ToStream());

            if (reader.ReadToEnd() != sTest)
            {
                sFail += "ToStream ";
            }
            reader.Dispose();

            // Test ListTrim
            s = "a: b :c :d";
            if (s.StringToList(':').ListTrim().ListToString(":") != "a:b:c:d")
            {
                sFail += "ListTrim ";
            }

            // Test ListToString and StringToList
            s = "a:b:c:d";
            if (s.StringToList(':').ListToString(":") != s)
            {
                sFail += "ListToString&StringToList ";
            }

            // Test ListToUpper
            if (s.StringToList(':').ListToUpper().ListToString(";") != "A;B;C;D")
            {
                sFail += "ListToUpper ";
            }

            // Test ToInlist
            if (s.StringToList(':').ToInList() != "\'a\',\'b\',\'c\',\'d\'")
            {
                sFail += "ToInList ";
            }

            // Test Validate
            if (!"b".Validate(s.StringToList(':')))
            {
                sFail += "Validate ";
            }

            // Test MultiPart
            if (s.MultiPart(':').ToList <string>().ListToString(":") != s)
            {
                sFail += "Multipart ";
            }


            // Test XML

            // Test LoadList and ToDictionary
            Dictionary <string, string> dict = XML.LoadList("Types.xml", "Types/SearchTypes", "value", "name").ToDictionary();

            if (dict.DictToString() != "R=Report,M=Memo,WP=Welding Procedure")
            {
                sFail += "XML LoadList&ToDictionary ";
            }

            // Test XMLTransform and AsString
            XmlDocument xdoc = new XmlDocument();

            xdoc.Load("Types.xml");
            string xml = xdoc.AsString();

            xml = XML.XmlNodePoke(xml, "Types/SearchTypes[1]", "text", "Rubbish");
            xml = XML.XMLTransform(xml, "Types.xslt");

            // Test ReadXMLNode
            if (XML.ReadXmlNode(xml, "root/Types/Type[@Key='WP']") != "Welding Procedure (WP)")
            {
                sFail += "ReadXMLNode ";
            }

            // Test ReadXMLAttribute
            if (XML.ReadXmlAttribute(xml, "root/Types/Type[@Key='M']/@Name") != "Memo")
            {
                sFail += "ReadXMLAttribute ";
            }

            // Test XMLNodePoke
            if (XML.ReadXmlNode(xml, "root/Types/Type[@Key='R']") != "Rubbish")
            {
                sFail += "XMLNodePoke ";
            }

            if (sFail.Length == 0)
            {
                Console.WriteLine("**********************");
                Console.WriteLine("** All Tests passed **");
                Console.WriteLine("**********************");
            }
            else
            {
                Console.WriteLine("!!!!!!!!!!!!!!!!!!!");
                Console.WriteLine("!! Failed tests: " + sFail);
                Console.WriteLine("!!!!!!!!!!!!!!!!!!!");
            }
        }
예제 #27
0
 public GeneratedResource(byte[] content, MIME format)
 {
     this.content = content;
     this.format  = format;
 }
예제 #28
0
        public ClientBody ReadBody()
        {
            ClientBody CB = new ClientBody();

            if (this.ContentLength > 0)
            {
                byte[]     bodybytes     = Reader.ReadBytes(this.ContentLength);
                byte[]     boundarybytes = Encoding.UTF8.GetBytes("--" + this.boundaryMultipart);
                List <int> indexes       = new List <int> ();
                int        ct            = 0;
                for (int i = 0; i < bodybytes.Length; ++i)
                {
                    if (bodybytes[i] == boundarybytes[ct])
                    {
                        ++ct;
                        if (ct == boundarybytes.Length)
                        {
                            indexes.Add(i);
                            ct = 0;
                        }
                    }
                    else
                    {
                        ct = 0;
                    }
                }
                List <byte[]> parts = new List <byte[]> (indexes.Count - 1);
                for (int i = 0; i < indexes.Count - 1; ++i)
                {
                    int    range = (indexes [i + 1] - indexes [i]) - (boundarybytes.Length + 4);
                    byte[] part  = new byte[range];
                    Buffer.BlockCopy(bodybytes, indexes[i] + 3, part, 0, range);
                    parts.Add(part);
                }
                foreach (byte[] part in parts)
                {
                    List <string> headerLines = new List <string> ();
                    int           index       = 0;
                    string        line        = String.Empty;
                    char          cb;
                    do
                    {
                        cb = Convert.ToChar(part[index]);
                        if (cb == '\r')
                        {
                            continue;
                        }
                        if (cb == '\n')
                        {
                            if (line == String.Empty)
                            {
                                break;
                            }
                            headerLines.Add(String.Copy(line));
                            line = String.Empty;
                        }
                        else
                        {
                            line += cb;
                        }
                    } while (index++ < part.Length);
                    byte[] partbody = new byte[part.Length - index - 1];
                    Buffer.BlockCopy(part, index + 1, partbody, 0, partbody.Length);
                    Dictionary <string, string> infodict = new Dictionary <string, string> ();
                    MIME CT = null;
                    foreach (string headerLine in headerLines)
                    {
                        string[] sline = headerLine.Split(new string[] { ": " }, 2, StringSplitOptions.None);
                        switch (sline[0])
                        {
                        case "Content-Disposition":
                            foreach (KeyValuePair <string, string> KVP in sline[1].Split(new string[] { "; " }, StringSplitOptions.None).Select((s) => s.Split('=')).Where((sa) => sa.Length > 1).Select((ss) => new KeyValuePair <string, string>(ss.ElementAt(0), ss.ElementAt(1))))
                            {
                                infodict.Add(KVP.Key.Trim('\"'), KVP.Value.Trim('\"'));
                            }
                            break;

                        case "Content-Type":
                            CT = MIME.FromText(sline[1]);
                            break;

                        default:
                            break;
                        }
                    }
                    if (CT == null)
                    {
                        string name;
                        if (infodict.Count > 0 && infodict.TryGetValue("name", out name))
                        {
                            CB.FormData.Add(name, Encoding.UTF8.GetString(partbody));
                        }
                    }
                    else
                    {
                        string name;
                        string filename;
                        if (infodict.Count > 1 && infodict.TryGetValue("name", out name) && infodict.TryGetValue("filename", out filename))
                        {
                            CB.FormDataBodies.Add(name, new Tuple <string, IStreamableContent> (filename, new GeneratedResource(partbody, CT)));
                        }
                    }
                }
                return(CB);
            }
            else
            {
                return(null);
            }
        }