示例#1
0
文件: Program.cs 项目: won21kr/Serac
        static void Main(string[] args)
        {
            new WebServer()
            .EnableCompression()
            .EnableStaticCache()
            .WebSocket("/socket", async(ws, request) => {
                ws.Disconnect += (_, fromClient) => WriteLine($"{(fromClient ? "Client" : "Server")} disconnected");

                WriteLine($"Message from client: '{await ws.ReadText()}'");
                await ws.Write(request.Path);
                await ws.Write("Hello!");
                await ws.Write(new byte[] { 0x41, 0x42 });
                //await ws.Close();
                while (true)
                {
                    await ws.Write(await ws.ReadText());
                }
            })
            .StaticFile("/favicon.ico", "./static/images/favicon.ico")
            .Katatonic("/katatonic", app => {
                app.Register <Root>();
                app.Register <Test>();
            })
            .RegisterHandler("/", StaticContent.Serve("./static"))
            .ListenOn(12345)
            .RunForever();
        }
示例#2
0
        public ActionResult GetHomeIntro(int MenuId)
        {
            int languageId = _workContext.WorkingLanguage.Id;

            StaticContent staticContent = this._staticContentService.Get((StaticContent x) => x.Id == MenuId, true);

            if (staticContent == null)
            {
                return(HttpNotFound());
            }

            StaticContent staticContentLocalized = new StaticContent
            {
                Id                = staticContent.Id,
                MenuId            = staticContent.MenuId,
                VirtualCategoryId = staticContent.VirtualCategoryId,
                Language          = staticContent.Language,
                Status            = staticContent.Status,
                SeoUrl            = staticContent.SeoUrl,
                ImagePath         = staticContent.ImagePath,

                Title           = staticContent.GetLocalizedByLocaleKey(staticContent.Title, staticContent.Id, languageId, "StaticContent", "Title"),
                ShortDesc       = staticContent.GetLocalizedByLocaleKey(staticContent.ShortDesc, staticContent.Id, languageId, "StaticContent", "ShortDesc"),
                Description     = staticContent.GetLocalizedByLocaleKey(staticContent.Description, staticContent.Id, languageId, "StaticContent", "Description"),
                MetaTitle       = staticContent.GetLocalizedByLocaleKey(staticContent.MetaTitle, staticContent.Id, languageId, "StaticContent", "MetaTitle"),
                MetaKeywords    = staticContent.GetLocalizedByLocaleKey(staticContent.MetaKeywords, staticContent.Id, languageId, "StaticContent", "MetaKeywords"),
                MetaDescription = staticContent.GetLocalizedByLocaleKey(staticContent.MetaDescription, staticContent.Id, languageId, "StaticContent", "MetaDescription")
            };

            return(base.PartialView(staticContentLocalized));
        }
示例#3
0
        public static StaticContent ToModel(this StaticContent entity)
        {
            if (entity == null)
            {
                return(null);
            }

            var model = new StaticContent
            {
                Id                = entity.Id,
                MenuId            = entity.MenuId,
                VirtualCategoryId = entity.VirtualCategoryId,
                Language          = entity.Language,
                Status            = entity.Status,
                SeoUrl            = entity.SeoUrl,
                ImagePath         = entity.ImagePath,
                MenuLink          = entity.MenuLink,

                Title           = entity.GetLocalized(x => x.Title, entity.Id),
                ShortDesc       = entity.GetLocalized(x => x.ShortDesc, entity.Id),
                Description     = entity.GetLocalized(x => x.Description, entity.Id),
                MetaTitle       = entity.GetLocalized(x => x.MetaTitle, entity.Id),
                MetaKeywords    = entity.GetLocalized(x => x.MetaKeywords, entity.Id),
                MetaDescription = entity.GetLocalized(x => x.MetaDescription, entity.Id)
            };

            return(model);
        }
示例#4
0
        public void icon(ActionContext ac)
        {
            string shopid = ac[this];

            using (var dc = Service.NewDbContext())
            {
                if (dc.Query1("SELECT icon FROM shops WHERE id = @1", p => p.Set(shopid)))
                {
                    ArraySegment <byte> byteas;
                    dc.Let(out byteas);
                    if (byteas.Count == 0)
                    {
                        ac.Give(204);                    // no content
                    }
                    else
                    {
                        StaticContent cont = new StaticContent(byteas);
                        ac.Give(200, cont, pub: true, maxage: 60 * 5);
                    }
                }
                else
                {
                    ac.Give(404, pub: true, maxage: 60 * 5);  // not found
                }
            }
        }
示例#5
0
        public async void RequestCorrectETagReceivesNotModified()
        {
            var bytes   = LoadSampleJpeg();
            var content = new StaticContent(bytes, ContentTypes.ImageJpeg);

            await Context.Application.Start();

            var address = LaraUI.GetFirstURL(Context.Application.GetHost());

            Context.Application.PublishFile("/", content);

            var request = new HttpRequestMessage
            {
                Method     = new HttpMethod("GET"),
                RequestUri = new Uri(address)
            };

            request.Headers.TryAddWithoutValidation("If-None-Match", content.ETag);

            using var response = await Client.SendAsync(request);

            var downloaded = await response.Content.ReadAsByteArrayAsync();

            Assert.Equal(HttpStatusCode.NotModified, response.StatusCode);
            Assert.False(response.Headers.Contains("ETag"));
            Assert.Empty(downloaded);
        }
示例#6
0
        public async void RequestWrongETagReceivesFile()
        {
            var bytes   = LoadSampleJpeg();
            var content = new StaticContent(bytes, ContentTypes.ImageJpeg);

            await Context.Application.Start(new StartServerOptions
            {
                AllowLocalhostOnly = true
            });

            var address = LaraUI.GetFirstURL(Context.Application.GetHost());

            Context.Application.PublishFile("/", content);

            var request = new HttpRequestMessage
            {
                Method     = new HttpMethod("GET"),
                RequestUri = new Uri(address)
            };

            request.Headers.TryAddWithoutValidation("If-None-Match", "lalalalala");

            using var response = await Client.SendAsync(request);

            var downloaded = await response.Content.ReadAsByteArrayAsync();

            Assert.Equal(HttpStatusCode.OK, response.StatusCode);
            Assert.True(response.Headers.TryGetValues("ETag", out var values));
            Assert.Equal(content.ETag, values.FirstOrDefault());
            Assert.Equal(bytes, downloaded);
        }
示例#7
0
        public void Can_parse_svg_datauri()
        {
            var dataUri = Svg.GetDataUri(Svg.Icons.Male);
            var content = StaticContent.CreateFromDataUri(dataUri);

            Assert.That(content.MimeType, Is.EqualTo("image/svg+xml"));
            Assert.That(content.Data.FromUtf8().ToString(), Is.EqualTo(Svg.GetImage(Svg.Icons.Male)));
        }
示例#8
0
        public void ETagFormatCorrect()
        {
            const int hash     = 12345;
            var       expected = "\"" + hash.ToString(CultureInfo.InvariantCulture) + "\"";
            var       etag     = StaticContent.FormatETag(hash);

            Assert.Equal(expected, etag);
        }
示例#9
0
 public StaticContentViewModel(StaticContent staticContent)
 {
     Id      = staticContent.Id;
     Name    = staticContent.Name;
     Content = staticContent.Content;
     Order   = staticContent.Order;
     IsShow  = staticContent.IsShow;
 }
示例#10
0
        public void Can_parse_base_datauri()
        {
            var utf8Bytes = "abc".ToUtf8Bytes();
            var dataUri   = "data:image/jpg;base64," + Convert.ToBase64String(utf8Bytes);
            var content   = StaticContent.CreateFromDataUri(dataUri);

            Assert.That(content.MimeType, Is.EqualTo("image/jpg"));
            Assert.That(content.Data.ToArray(), Is.EqualTo(utf8Bytes));
        }
示例#11
0
        public void AreadyCompressedFileDoesNotGetCompressed()
        {
            var bytes   = LoadSampleJpeg();
            var content = new StaticContent(bytes, ContentTypes.ImageJpeg);

            Assert.Same(bytes, content.GetBytes());
            Assert.Equal(ContentTypes.ImageJpeg, content.ContentType);
            Assert.False(content.Compressed);
            Assert.False(string.IsNullOrEmpty(content.ETag));
        }
        public ManualStaticContentTests()
        {
            this.bootstrapper = new ConfigurableBootstrapper(
                configuration =>
            {
                configuration.ApplicationStartup((c, p) => StaticContent.Enable(p));
                configuration.Modules(new Type[] { });
            });

            this.browser = new Browser(bootstrapper);
        }
示例#13
0
        public void Update(string key, LanguageEnum language, string value)
        {
            if (string.IsNullOrEmpty(key))
            {
                throw new ArgumentNullException(nameof(key));
            }

            var entry = this.staticContent.All().FirstOrDefault(x => x.ContentKey == key);

            if (entry == null)
            {
                entry = new StaticContent();

                switch (language)
                {
                case LanguageEnum.En:
                    entry.ContentValueEn = value;
                    break;

                case LanguageEnum.Bg:
                    entry.ContentValueBg = value;
                    break;

                default:
                    throw new ArgumentOutOfRangeException(nameof(language), language, null);
                }

                entry.ContentKey     = key;
                entry.ContentValueEn = entry.ContentValueEn ?? string.Empty;
                entry.ContentValueBg = entry.ContentValueBg ?? string.Empty;

                this.staticContent.Add(entry);
            }
            else
            {
                switch (language)
                {
                case LanguageEnum.En:
                    entry.ContentValueEn = value;
                    break;

                case LanguageEnum.Bg:
                    entry.ContentValueBg = value;
                    break;

                default:
                    throw new ArgumentOutOfRangeException(nameof(language), language, null);
                }

                this.staticContent.Update(entry);
            }
        }
示例#14
0
        public void AlContenidoSeLePuedeAgregarUnTextoEstatico()
        {
            // arrange
            var report = ReportFactory.GetReport();

            // act
            var content = new StaticContent();

            content.Text = "lalalala";
            report.Contents.AddContent(content);

            // assert
            report.Contents.Contents.FirstOrDefault(x => x.Equals(content)).Should().Not.Be.Null();
        }
示例#15
0
 public void Update(StaticContent obj, out OperationResult operationResult)
 {
     lock (Lock)
     {
         if (obj == null)
         {
             operationResult = new OperationResult {
                 Type = OperationResult.ResultType.Warning
             };
             return;
         }
         Common.Instance.Update
             (obj, objs => objs.StaticContentId == obj.StaticContentId && objs.LanguageId == obj.LanguageId, out operationResult);
     }
 }
示例#16
0
        public ActionResult Home()
        {
            ViewBag.WhatWeDeliver = _repo.GetAll <WhatWeDelivered>().ToList();
            ViewBag.Portfolio     = _repo.GetAll <Project>().ToList();
            ViewBag.WhyUs         = _repo.GetQueryWhere <WhyUS>(w => w.IsShow == true).ToList();
            ViewBag.Clients       = _repo.GetQueryWhere <Clients>(c => c.IsShow == true).Take(8).ToList();



            StaticContent staticContent = _repo.GetAll <StaticContent>().FirstOrDefault();

            ViewBag.StaticContent = staticContent;

            return(View());
        }
示例#17
0
 public void Insert(StaticContent obj, out OperationResult operationResult)
 {
     lock (Lock)
     {
         if (obj == null)
         {
             operationResult = new OperationResult {
                 Type = OperationResult.ResultType.Warning
             };
         }
         else
         {
             Common.Instance.Insert(obj, out operationResult);
         }
     }
 }
示例#18
0
        public new async Task icon(ActionContext ac)
        {
            string shopid = ac[typeof(ShopVarWork)];
            string name   = ac[this];

            if (ac.GET)
            {
                using (var dc = ac.NewDbContext())
                {
                    if (dc.Query1("SELECT icon FROM items WHERE shopid = @1 AND name = @2", p => p.Set(shopid).Set(name)))
                    {
                        ArraySegment <byte> byteas;
                        dc.Let(out byteas);
                        if (byteas.Count == 0)
                        {
                            ac.Give(204);                    // no content
                        }
                        else
                        {
                            StaticContent cont = new StaticContent(byteas);
                            ac.Give(200, cont);
                        }
                    }
                    else
                    {
                        ac.Give(404);  // not found
                    }
                }
            }
            else // post
            {
                var frm = await ac.ReadAsync <Form>();

                ArraySegment <byte> icon = frm[nameof(icon)];
                using (var dc = Service.NewDbContext())
                {
                    if (dc.Execute("UPDATE items SET icon = @1 WHERE shopid = @2 AND name = @3", p => p.Set(icon).Set(shopid).Set(name)) > 0)
                    {
                        ac.Give(200); // ok
                    }
                    else
                    {
                        ac.Give(500); // internal server error
                    }
                }
            }
        }
示例#19
0
        public async Task <bool> InsertAsync(StaticContentViewModel viewModel)
        {
            var entity = new StaticContent()
            {
                Id      = viewModel.Id,
                Name    = viewModel.Name,
                Content = viewModel.Content,
                Order   = viewModel.Order,
                IsShow  = viewModel.IsShow,
            };

            await _staticContents.AddAsync(entity);

            var result = await _unitOfWork.SaveChangesAsync();

            return(result != 0);
        }
        public void Save(StaticContent content)
        {
            var oldRecord = _db.StaticContent.FirstOrDefault(x => x.TypeStaticContent == content.TypeStaticContent);

            if (oldRecord != null)
            {
                oldRecord.Body  = content.Body;
                oldRecord.Title = content.Title;

                _db.StaticContent.Attach(oldRecord);
                _db.Entry(oldRecord).State = EntityState.Modified;
                _db.SaveChanges();
                return;
            }

            _db.StaticContent.Add(content);
            _db.SaveChanges();
        }
示例#21
0
        public static ReportDefinition GetReportSinCoordenadas()
        {
            var reportDefinition = new ReportDefinition();
            var staticContent    = new StaticContent();

            staticContent.Text = "pepe";
            reportDefinition.Contents.AddContent(staticContent);

            staticContent      = new StaticContent();
            staticContent.Text = "pepe 2";
            reportDefinition.Contents.AddContent(staticContent);

            staticContent      = new StaticContent();
            staticContent.Text = "pepe 3";
            reportDefinition.Contents.AddContent(staticContent);

            return(reportDefinition);
        }
        public IVisualStudioProject Render <T>(CodeGenSettings settings, object template, IEnumerable <T> collection, IVisualStudioProject projectFile)
        {
            IStaticAsset         asset           = (IStaticAsset)template;
            List <StaticContent> renderedAssests = asset.Render();


            IClassMetadata classmeta = asset;

            string projectNamespace = string.Format("{0}.{1}", settings.SolutionNamespace, classmeta.ProjectNamespace);
            string projectDirectory = string.Format(@"{0}\{1}", settings.CodeGenerationDirectory, projectNamespace);

            projectFile = ClassesLogic.SetProjectProperties(settings, classmeta, projectFile, projectDirectory);

            //create Directory if it doesn't exists
            if (!File.Exists(projectDirectory))
            {
                Directory.CreateDirectory(projectDirectory);
            }

            //Set File properties... optional Namespace, and the full file path.
            string fullProjectNamespace = projectNamespace + ClassesLogic.AddFolderNamespaces(classmeta);


            foreach (StaticContent content in renderedAssests)
            {
                string filePath         = string.Format(@"{0}\{1}{2}", projectDirectory, classmeta.ClassFilePath, content.FileName);
                string projectClassPath = (string.IsNullOrEmpty(classmeta.ClassFilePath)
                               ? content.FileName
                               : classmeta.ClassFilePath + content.FileName);

                ProjectArtifact artifact = new ProjectArtifact(projectClassPath, content.CreateGeneratedCounterpart);
                projectFile.Classes.Add(artifact);

                StaticContent _content = content;
                if (content.SetNamespace)
                {
                    _content.Content = SetNamespaceAndClass(content.Content.ToString(), fullProjectNamespace);
                }

                SaveContent(classmeta, projectDirectory, content, _content, fullProjectNamespace, filePath);
            }

            return(projectFile);
        }
示例#23
0
        public async void RequestWithoutETagReceivesFile()
        {
            var bytes   = LoadSampleJpeg();
            var content = new StaticContent(bytes, ContentTypes.ImageJpeg);

            await Context.Application.Start();

            var address = LaraUI.GetFirstURL(Context.Application.GetHost());

            Context.Application.PublishFile("/", content);
            using var response = await Client.GetAsync(address);

            var downloaded = await response.Content.ReadAsByteArrayAsync();

            Assert.Equal(HttpStatusCode.OK, response.StatusCode);
            Assert.True(response.Headers.TryGetValues("ETag", out var values));
            Assert.Equal(content.ETag, values.FirstOrDefault());
            Assert.Equal(bytes, downloaded);
        }
示例#24
0
        public async void CompressibleFileIsSentCompressed()
        {
            var bytes   = LoadCompressibleBmp();
            var content = new StaticContent(bytes, "image");

            await Context.Application.Start();

            var address = LaraUI.GetFirstURL(Context.Application.GetHost());

            Context.Application.PublishFile("/", content);
            using var response = await Client.GetAsync(address);

            var downloaded = await response.Content.ReadAsByteArrayAsync();

            Assert.Equal(HttpStatusCode.OK, response.StatusCode);
            Assert.True(response.Headers.TryGetValues("ETag", out var values));
            Assert.Equal(content.ETag, values.FirstOrDefault());
            Assert.Equal(bytes, downloaded);
        }
示例#25
0
        public WCFReturnResult Update(WCFAuthInfoVM entity_WCFAuthInfoVM, LoginUserVM entity_LUVM)
        {
            try
            {
                //Retrieve Language And Session
                RetrieveLanguageAndSession(entity_WCFAuthInfoVM);

                WCFReturnResult returnResult = new WCFReturnResult();

                //Contruct Login User Respository
                CoolPrivilegeControlContext dbContext      = CoolPrivilegeControlContext.CreateContext();
                LoginUserRespository        loginUserRespo = new LoginUserRespository(dbContext, entity_BaseSession.ID);

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

                bool ret = false;

                if (StaticContent.LockAdmin())
                {
                    ret = CheckAccPrivilegeWSpID(entity_BaseSession.ID, entity_WCFAuthInfoVM.RequestFunKey, entity_WCFAuthInfoVM.RequestFunTypeKey, entity_LUVM.ID.ToString(), false, ref strList_Error);
                }
                else
                {
                    ret = CheckAccPrivilegeWSpID(entity_BaseSession.ID, entity_WCFAuthInfoVM.RequestFunKey, entity_WCFAuthInfoVM.RequestFunTypeKey, entity_LUVM.ID.ToString(), true, ref strList_Error);
                }

                if (ret)
                {
                    ret = loginUserRespo.Update(entity_LUVM, languageKey, ref strList_Error);
                }

                returnResult.IsSuccess = ret;

                returnResult.StrList_Error = strList_Error;

                return(returnResult);
            }
            catch (Exception ex)
            {
                throw new FaultException <WCFErrorContract>(new WCFErrorContract(ex), ex.Message);
            }
        }
        public WCFReturnResult Delete(WCFAuthInfoVM entity_WCFAuthInfoVM, string str_LUID)
        {
            try
            {
                RetrieveLanguageAndSession(entity_WCFAuthInfoVM);

                WCFReturnResult returnResult = new WCFReturnResult();

                //Contruct Login User Respository
                CoolPrivilegeControlContext dbContext      = CoolPrivilegeControlContext.CreateContext();
                LoginUserRespository        loginUserRespo = new LoginUserRespository(dbContext, entity_BaseSession.ID);

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

                bool ret = false;

                if (StaticContent.LockAdmin())
                {
                    ret = CheckAccPrivilegeWSpID(entity_BaseSession.ID, entity_WCFAuthInfoVM.RequestFunKey, entity_WCFAuthInfoVM.RequestFunTypeKey, str_LUID, false, ref strList_Error);
                }
                else
                {
                    ret = CheckAccPrivilegeWSpID(entity_BaseSession.ID, entity_WCFAuthInfoVM.RequestFunKey, entity_WCFAuthInfoVM.RequestFunTypeKey, str_LUID, true, ref strList_Error);
                }

                if (ret)
                {
                    ret = loginUserRespo.Delete(str_LUID, languageKey, ref strList_Error);
                }

                returnResult.IsSuccess = ret;

                returnResult.StrList_Error = strList_Error;

                return(returnResult);
            }
            catch (Exception ex)
            {
                throw new WebFaultException <WCFErrorContract>(new WCFErrorContract(ex), System.Net.HttpStatusCode.ExpectationFailed);
            }
        }
示例#27
0
        internal void Create()
        {
            RowDefinitions.Add(new RowDefinition {
                Height = new GridLength(100, GridUnitType.Star)
            });
            _collapseableColumn = new ColumnDefinition {
                Width = new GridLength(30, GridUnitType.Auto)
            };
            var staticColumn = new ColumnDefinition {
                Width = new GridLength(70, GridUnitType.Star)
            };

            ColumnDefinitions.Add(_collapseableColumn);
            ColumnDefinitions.Add(staticColumn);

            CollapseableContent.SetValue(ColumnProperty, 0);
            StaticContent.SetValue(ColumnProperty, 1);

            Children.Add(CollapseableContent);
            Children.Add(StaticContent);
        }
示例#28
0
        public new async Task icon(ActionContext ac)
        {
            string id = ac[this];

            if (ac.GET)
            {
                using (var dc = ac.NewDbContext())
                {
                    if (dc.Query1("SELECT icon FROM shops WHERE id = @1", p => p.Set(id)))
                    {
                        ArraySegment <byte> byteas;
                        dc.Let(out byteas);
                        if (byteas.Count == 0)
                        {
                            ac.Give(204);                    // no content
                        }
                        else
                        {
                            StaticContent cont = new StaticContent(byteas);
                            ac.Give(200, cont);
                        }
                    }
                    else
                    {
                        ac.Give(404);  // not found
                    }
                }
            }
            else // post
            {
                var f = await ac.ReadAsync <Form>();

                ArraySegment <byte> icon = f[nameof(icon)];
                using (var dc = ac.NewDbContext())
                {
                    dc.Execute("UPDATE shops SET icon = @1 WHERE id = @2", p => p.Set(icon).Set(id));
                    ac.Give(200); // ok
                }
            }
        }
示例#29
0
        public static StaticContent GetKernelEditorContent()
        {
            StaticContent root = new StaticContent();

            root.InstanceName        = "KernelEditor.StaticContent";
            root.ParentContent       = null;
            root.ContentFriendlyName = "Kernel Editor";
            root.ContentImageSrc     = "folder.gif";
            root.ContentDescription  = "Root node for editing Plugs.Kernel items";

            StaticContent plugs = new StaticContent();

            plugs.InstanceName        = "KernelEditor.StaticContent.Plugs";
            plugs.ParentContent       = root;
            plugs.ContentFriendlyName = "Registered plugs";
            plugs.ContentImageSrc     = "folder.gif";
            plugs.ContentDescription  = "Shown registered in system plugs";
            root.ChildContent.Add(plugs);

            StaticContent locations = new StaticContent();

            locations.InstanceName        = "KernelEditor.StaticContent.Locations";
            locations.ParentContent       = root;
            locations.ContentFriendlyName = "File locations";
            locations.ContentImageSrc     = "folder.gif";
            locations.ContentDescription  = "Shown registered in system locations";
            root.ChildContent.Add(locations);

            StaticContent uis = new StaticContent();

            uis.InstanceName        = "KernelEditor.StaticContent.AbstactUIs";
            uis.ParentContent       = root;
            uis.ContentFriendlyName = "Defined UIs";
            uis.ContentImageSrc     = "folder.gif";
            uis.ContentDescription  = "View and edit UIs";
            root.ChildContent.Add(uis);

            return(root);
        }
示例#30
0
        public IActionResult Post([FromBody] dynamic data)
        {
            try
            {
                if (data == null)
                {
                    return(BadRequest());
                }

                StaticContent staticContent = Utils.ConvertTo <StaticContent>(data);

                staticContent.DateAdded = DateTime.Now;
                //staticContent.Id = Guid.NewGuid();

                _staticContentRepository.InsertOrUpdateContent(staticContent);

                return(Ok());
            }
            catch (Exception e)
            {
                return(BadRequest(e));
            }
        }
示例#31
0
	private void attach_StaticContents(StaticContent entity)
	{
		this.SendPropertyChanging();
		entity.User = this;
	}
示例#32
0
	private void detach_StaticContents(StaticContent entity)
	{
		this.SendPropertyChanging();
		entity.User = null;
	}
示例#33
0
 partial void InsertStaticContent(StaticContent instance);
示例#34
0
 partial void UpdateStaticContent(StaticContent instance);
示例#35
0
 partial void DeleteStaticContent(StaticContent instance);