public dynamic GetGlobalModel() { string globalModelPath = Path.Combine(_rootPathProvider.GetRootPath(), _settings.ModelsPath, Conventions.GlobalModelFile); if (File.Exists(globalModelPath) == false) { return(null); } var bodyStream = new StreamReader(globalModelPath); try { var json = bodyStream.ReadToEnd(); dynamic globalModel = JsonHelpers.ParseJsonObject(json); return(globalModel); } catch (Exception ex) { throw new ApplicationException("Error while parsing global model", ex); } finally { if (bodyStream != null) { bodyStream.Dispose(); } } }
private static Func<NancyContext, Response> GetStitchResponse(IEnumerable<ICompile> compilers, IRootPathProvider rootPathProvider, IStitchConfiguration configuration) { return ctx => { if (ctx.Request == null) return null; if (compilers == null) return null; if (rootPathProvider == null) return null; if (ctx.Request.Uri.ToLowerInvariant().EndsWith(".stitch")) { Package package = null; if (configuration.Files != null) { var file = configuration.Files.Where(f => f.Name.Equals(ctx.Request.Uri, StringComparison.InvariantCultureIgnoreCase)).FirstOrDefault(); if (file != null) { package = new Package( rootPathProvider.GetRootPath(), file.Paths, file.Dependencies, file.Identifier ?? configuration.Identifier ?? "require", compilers); } } if (package == null) { package = new Package( rootPathProvider.GetRootPath(), configuration.Paths, configuration.Dependencies, configuration.Identifier ?? "require", compilers); } var response = new Response { StatusCode = HttpStatusCode.OK, ContentType = "application/x-javascript", Contents = s => { using (var writer = new StreamWriter(s)) { writer.Write(package.Compile()); writer.Flush(); } } }; return response; } return null; }; }
public EnvironmentPathProvider(IRootPathProvider rootPathProvider) { _rootPath = rootPathProvider.GetRootPath(); _rootUrl = "http://*****:*****@"Data"); _applicationContentDataPath = Path.Combine(rootPathProvider.GetRootPath(), @"Content"); }
public Image GetImage(string imageKey) { var imagePath = Path.Combine(_rootPathProvider.GetRootPath(), ImageFolder, string.Format(ImageFileNameFormat, imageKey)); if (!File.Exists(imagePath)) { return(null); } return(Image.FromFile(imagePath)); }
public HomeModule(IRootPathProvider path) { this.RequiresAuthentication(); Get["/"] = r => { var os = System.Environment.OSVersion; var p = path.GetRootPath(); var user = Context.CurrentUser.UserName; return("Hello Nancy<br/> System:" + os.VersionString + "<br/>" + p + "<br/>" + user); }; Get["/blog/{name}"] = r => { return("blog name " + r.name); }; Get["/mvc/{controller}/{action}/{id}"] = r => { StringBuilder mvc = new StringBuilder(); mvc.AppendLine("controller :" + r.controller + "<br/>"); mvc.AppendLine("action :" + r.action + "<br/>"); mvc.AppendLine("id :" + r.id + "<br/>"); return(mvc.ToString()); }; Get["/json"] = r => { JavaScriptSerializer js = new JavaScriptSerializer(); return(js.Serialize(new { status = 200, message = "this json" })); }; Post["/file"] = r => { var uploadDirectory = Path.Combine(path.GetRootPath(), "uploads"); if (!Directory.Exists(uploadDirectory)) { Directory.CreateDirectory(uploadDirectory); } foreach (var file in Request.Files) { var filename = Path.Combine(uploadDirectory, file.Name); using (FileStream fileStream = new FileStream(filename, FileMode.Create)) { file.Value.CopyTo(fileStream); } } return(HttpStatusCode.OK); }; }
public ScriptModule(IRootPathProvider root, ScriptBuilder scriptBuilder) { Get["/js/debug"] = _ => { return(Response.AsText(scriptBuilder.GetScripts(root.GetRootPath(), false), "application/javascript")); }; Get["/js/min"] = _ => { //Maybe some server side caching could be great //In the future, when retrieving scripts becomes relative to the user role, the cache could map roles and relevant scripts together return(Response.AsText(scriptBuilder.GetScripts(root.GetRootPath(), true), "application/javascript")); }; }
public ScriptModule(IRootPathProvider root, ScriptBuilder scriptBuilder) { Get["/js/debug"] = _ => { return Response.AsText(scriptBuilder.GetScripts(root.GetRootPath(), false), "application/javascript"); }; Get["/js/min"] = _ => { //Maybe some server side caching could be great //In the future, when retrieving scripts becomes relative to the user role, the cache could map roles and relevant scripts together return Response.AsText(scriptBuilder.GetScripts(root.GetRootPath(), true), "application/javascript"); }; }
public LessModule(IRootPathProvider root) { var urlPrefix = System.Configuration.ConfigurationManager.AppSettings["app:UrlPrefix"] ?? string.Empty; Get[urlPrefix + "/less/desktop"] = _ => { var manifest = System.Configuration.ConfigurationManager.AppSettings["app:LessManifest"]; if (manifest.StartsWith("/")) { manifest = manifest.Substring(1); } manifest = manifest.Replace("/", "\\"); var lessFile = Path.Combine(root.GetRootPath(), manifest); if (!File.Exists(lessFile)) { throw new FileNotFoundException("Less manifest was not found"); } var less = File.ReadAllText(lessFile); var config = dotless.Core.configuration.DotlessConfiguration.GetDefaultWeb(); config.Logger = typeof(dotless.Core.Loggers.AspResponseLogger); config.CacheEnabled = false; config.MinifyOutput = true; var css = dotless.Core.LessWeb.Parse(less, config); return Response.AsText(css, "text/css"); }; }
public void Handle(HttpStatusCode statusCode, NancyContext context) { try { if (context.ResolvedRoute.Description.Path.StartsWith("/webui/")) { context.Response.Contents = stream => { var filename = Path.Combine(_rootPathProvider.GetRootPath(), @"webui\\index.html"); using (var file = File.OpenRead(filename)) { file.CopyTo(stream); } }; } else { context.Response = @"<html><body>File not Found (404)</body></html>"; } } catch { context.Response = @"<html><body>Internal Error: #$%^&*(</body></html>"; } }
public LessModule(IRootPathProvider root) { var urlPrefix = System.Configuration.ConfigurationManager.AppSettings["app:UrlPrefix"] ?? string.Empty; Get[urlPrefix + "/less/desktop"] = _ => { var manifest = System.Configuration.ConfigurationManager.AppSettings["app:LessManifest"]; if (manifest.StartsWith("/")) { manifest = manifest.Substring(1); } manifest = manifest.Replace("/", "\\"); var lessFile = Path.Combine(root.GetRootPath(), manifest); if (!File.Exists(lessFile)) { throw new FileNotFoundException("Less manifest was not found"); } var less = File.ReadAllText(lessFile); var config = dotless.Core.configuration.DotlessConfiguration.GetDefaultWeb(); config.Logger = typeof(dotless.Core.Loggers.AspResponseLogger); config.CacheEnabled = false; config.MinifyOutput = true; var css = dotless.Core.LessWeb.Parse(less, config); return(Response.AsText(css, "text/css")); }; }
// note the async is required otherwise messing with Task.FromResult<dynamic> is just painful #pragma warning disable 1998 private async Task <dynamic> GetStaticResourceForSlug(string slug) #pragma warning restore 1998 { var path = Path.Combine(_rootPathProvider.GetRootPath(), _configuration.WikiSourcePath, slug); return(File.Exists(path) ? Response.AsFile(path) : null); }
public static string GetPostsPath(IRootPathProvider rootPathProvider) { var rootPath = rootPathProvider.GetRootPath(); var requiredPath = Path.Combine(rootPath, "Posts"); return(requiredPath); }
public static void RenderExternalJavascript(Stream responseStream, IRootPathProvider rootPath) { using (var js = new FileStream(Path.Combine(rootPath.GetRootPath(), "content/external.js"), FileMode.Open)) { js.CopyTo(responseStream); } }
private object PatchFile(dynamic p) { var path = Path.Combine(pathProvider.GetRootPath(), p.path); string tempPath; string etag; using (var file = File.Open(path, FileMode.Open, FileAccess.Read, FileShare.Delete)) { using (var tempFile = OpenTempFile(path, out tempPath)) { var patchJob = new DeltaReadJob(Request.Body, new PatchProcessor(file, tempFile)); patchJob.Run(); } using (var tempFile = File.Open(tempPath, FileMode.Open, FileAccess.Read)) { etag = GetETag(tempFile); } } if (!MoveFileEx(tempPath, path, MoveFileFlags.ReplaceExisting)) { throw new Win32Exception(); } var response = new Response(); response.StatusCode = HttpStatusCode.NoContent; response.Headers.Add("ETag", "\"" + etag + "\""); return(response); }
public Response ProcessRequest(NancyContext context, string path) { path = path.Substring(PathPrefix.Length); var match = Regex.Match(path, @"^(?<filename>.*)-[a-z0-9]+\.(?<extension>[a-z]+)$", RegexOptions.IgnoreCase); if (match.Success == false) { logger.Error("ProcessRequest : Invalid file path in URL '{0}'", path); return(new HtmlResponse(HttpStatusCode.InternalServerError)); } var extension = match.Groups["extension"].Value; var filePath = string.Concat(rootPathProvider.GetRootPath(), @"\", match.Groups["filename"].Value.Replace('/', '\\'), ".", match.Groups["extension"].Value); filePath = Regex.Replace(filePath, @"\\{2,}", @"\"); if (!File.Exists(filePath)) { logger.Warn("ProcessRequest : File does not exist '{0}'", filePath); return(new HtmlResponse(HttpStatusCode.NotFound)); } logger.Info("ProcessRequest : File '{0}' returned", path); return(new StreamResponse(() => File.OpenRead(filePath), MimeTypes.GetMimeType(filePath))); }
public InfoModule(IRootPathProvider rootPathProvider, NancyInternalConfiguration configuration) : base("/info") { Get["/"] = _ => View["Info"]; Get["/data"] = _ => { dynamic data = new ExpandoObject(); data.Nancy = new ExpandoObject(); data.Nancy.Version = string.Format("v{0}", this.GetType().Assembly.GetName().Version.ToString()); data.Nancy.CachesDisabled = StaticConfiguration.DisableCaches; data.Nancy.TracesDisabled = StaticConfiguration.DisableErrorTraces; data.Nancy.CaseSensitivity = StaticConfiguration.CaseSensitive ? "Sensitive" : "Insensitive"; data.Nancy.RootPath = rootPathProvider.GetRootPath(); data.Nancy.Hosting = this.GetHosting(); data.Nancy.BootstrapperContainer = this.GetBootstrapperContainer(); data.Nancy.LocatedBootstrapper = NancyBootstrapperLocator.Bootstrapper.GetType().ToString(); data.Nancy.LoadedViewEngines = GetViewEngines(); data.Configuration = new Dictionary <string, object>(); foreach (var propertyInfo in configuration.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public)) { var value = propertyInfo.GetValue(configuration, null); data.Configuration[propertyInfo.Name] = (!typeof(IEnumerable).IsAssignableFrom(value.GetType())) ? new[] { value.ToString() } : ((IEnumerable <object>)value).Select(x => x.ToString()); } return(Response.AsJson((object)data)); }; }
public ConnectionManager(IRootPathProvider rootPathProvider) { this.factory = DbProviderFactories.GetFactory("System.Data.SQLite"); this.databaseName = Path.Combine(rootPathProvider.GetRootPath(), "data.db"); CreateDatabase(); }
public void Handle(HttpStatusCode statusCode, NancyContext context) { context.Response.Contents = stream => { try { var filename = Path.Combine(_rootPathProvider.GetRootPath(), @"webui", "index.html"); using (var file = File.OpenRead(filename)) { file.CopyTo(stream); } } catch (Exception) { try { StreamWriter writer = new StreamWriter(stream, Encoding.Unicode, 128, true); writer.Write(@"<html><body>File not Found (404)</body></html>"); writer.Flush(); writer.Close(); } catch {} } }; }
private static byte[] LocateIconOnFileSystem() { if (rootPathProvider == null) { return(null); } byte[] icon = null; var extensions = new[] { "ico", "png" }; var locatedFavIcons = extensions.SelectMany(extension => Directory .EnumerateFiles(rootPathProvider.GetRootPath(), string.Concat("favicon.", extension), SearchOption.AllDirectories)) .ToArray(); if (locatedFavIcons.Any()) { var image = Image.FromFile(locatedFavIcons.First()); var converter = new ImageConverter(); icon = (byte[])converter.ConvertTo(image, typeof(byte[])); } return(icon); }
private static IEnumerable <string> EnumerateFiles(string extension) { var rootPath = rootPathProvider.GetRootPath(); var fileName = string.Concat("favicon.", extension); return(Directory.EnumerateFiles(rootPath, fileName, SearchOption.AllDirectories)); }
public MainModules(IRootPathProvider pathProvider) { Get[@"/"] = parameters => { return(Response.AsFile("src/index.html", "text/html")); }; Get[@"/{file*}"] = (parameters) => { if (Path.HasExtension(parameters.file)) { var path = Path.Combine(pathProvider.GetRootPath(), "src", ((string)parameters.file).Replace('/', '\\')); if (File.Exists(path)) { return(Response.AsFile(Path.Combine("src", (string)parameters.file))); } else { return(HttpStatusCode.NotFound); } } return(Response.AsFile("src/index.html", "text/html")); }; }
public ConnectionManager(IRootPathProvider rootPathProvider) { this.factory = DbProviderFactories.GetFactory("System.Data.SQLite"); this.databaseName = Path.Combine(rootPathProvider.GetRootPath(), "data.db"); CreateDatabase(); }
public InfoModule(IRootPathProvider rootPathProvider, NancyInternalConfiguration configuration) : base("/info") { Get["/"] = _ => View["Info"]; Get["/data"] = _ => { dynamic data = new ExpandoObject(); data.Nancy = new ExpandoObject(); data.Nancy.Version = string.Format("v{0}", this.GetType().Assembly.GetName().Version.ToString()); data.Nancy.CachesDisabled = StaticConfiguration.DisableCaches; data.Nancy.TracesDisabled = StaticConfiguration.DisableErrorTraces; data.Nancy.CaseSensitivity = StaticConfiguration.CaseSensitive ? "Sensitive" : "Insensitive"; data.Nancy.RootPath = rootPathProvider.GetRootPath(); data.Nancy.Hosting = this.GetHosting(); data.Nancy.BootstrapperContainer = this.GetBootstrapperContainer(); data.Nancy.LocatedBootstrapper = NancyBootstrapperLocator.Bootstrapper.GetType().ToString(); data.Nancy.LoadedViewEngines = GetViewEngines(); data.Configuration = new Dictionary<string, object>(); foreach (var propertyInfo in configuration.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public)) { var value = propertyInfo.GetValue(configuration, null); data.Configuration[propertyInfo.Name] = (!typeof(IEnumerable).IsAssignableFrom(value.GetType())) ? new[] { value.ToString() } : ((IEnumerable<object>) value).Select(x => x.ToString()); } return Response.AsJson((object)data); }; }
public string Html() { try { var path = Path.Combine(_rootPathProvider.GetRootPath(), "App_Data/Elmah"); var info = new DirectoryInfo(path); var logs = info.GetFiles("*.xml") .OrderByDescending(f => f.CreationTime) .Select(f => { using (var xmlReader = XmlReader.Create(new StreamReader(f.FullName))) { var error = ErrorXml.Decode(xmlReader); return($"\n--- {f.Name}\n{XmlErrorToString(error)}"); } }) .Take(20); return($"<pre>{string.Join("\n", logs)}</pre>"); } catch (Exception ex) { ErrorSignal.FromCurrentContext().Raise(ex); return($"<pre>{ex.Message}</pre>"); } }
public IndexModule(IRootPathProvider pathProvider)//:base("product") { var uploadDirectory = Path.Combine(pathProvider.GetRootPath(), "Content", "uploads"); //Before += ctx => { // int i = 1; // return "22";//null 不做处理 //}; Get["/"] = _ => View["index2"]; Get["/up2"] = _ => View["indexup"]; Post["/logic"] = _ => { var t = Request.Files; foreach (var file in Request.Files) { var filename = Path.Combine(uploadDirectory, file.Name); using (FileStream fileStream = new FileStream(filename, FileMode.Create)) { file.Value.CopyTo(fileStream); } } return("22"); }; Get["/aa.jpg"] = _ => { // return Response.AsFile("Content/uploads/b.jpg"); return(Response.AsFile("Content/uploads/aa.jpg")); }; Get["/down/{name}"] = _ => { string fileName = _.name; var relatePath = @"Content\uploads\" + fileName; return(Response.AsFile(relatePath)); }; Get["/one"] = _ => View["one"]; Get["/two"] = _ => View["two"]; Post["/three"] = _ => { Student stu = this.Bind(); Student stu2 = new Student(); return(Response.AsJson(stu)); }; Get["/pic"] = _ => { return(""); }; Get["/four"] = _ => View["four"]; // Get["/"] = parameters => "Hello World"; Post["/login", (ctx) => ctx.Request.Form.remember] = _ => { return("true"); }; Post["/login", (ctx) => !ctx.Request.Form.remember] = _ => { return("Handling code when remember is false!"); }; Get["/intConstraint/{value:int}"] = _ => "Value " + _.value + " is an integer.";//路由约束 }
public ImageFileManager( IImageFileProcessor imageFileProcessor, IRootPathProvider rootPathProvider, IImageFolderConfigAccessor folderConfigAccessor) { _imageFileProcessor = imageFileProcessor; _rootPathProvider = rootPathProvider; _imageFolders = folderConfigAccessor.GetFolderConfigs(); _rootPath = _rootPathProvider.GetRootPath(); }
private string GetBigJsonPath() { var path = "big.json"; if (!File.Exists(path)) { path = _rpp.GetRootPath() + @"\bin\big.json"; } return(path); }
private void ConfigureTimesheetModules(IRootPathProvider pathProvider) { var configPath = Path.Combine(pathProvider.GetRootPath(), "timesheet.config"); config = new TimesheetConfig(); using (var timesheetStream = new StreamReader(configPath)) { var configXml = new XmlSerializer(typeof(TimesheetConfig)); config = (TimesheetConfig)configXml.Deserialize(timesheetStream); timesheetStream.Close(); } timesheetLog = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "Timesheet.log"); timesheetPythonModulesPath = Path.Combine(pathProvider.GetRootPath(), config.Module.Relativepath); estimatedHoursScript = Path.Combine(timesheetPythonModulesPath, config.WeeksFeed.Filename); spreadsheetGeneratorScript = Path.Combine(timesheetPythonModulesPath, config.SpreadsheetGenerator.Filename); timesheetWriterType = config.WriterType.Type ?? string.Empty; }
private static dynamic BuildFileDownloadResponse(IRootPathProvider pathProvider, string fileName) { var mimeType = MimeTypes.GetMimeType(fileName); var path = Path.Combine(pathProvider.GetRootPath(), fileName); Func<Stream> file = () => new FileStream(path, FileMode.Open); var response = new StreamResponse(file, mimeType); var fileInfo = new FileInfo(path); return response.AsAttachment(fileInfo.Name); }
public ApplicationModule(IRootPathProvider pathProvider) { Get["/"] = Get[@"/(.*)"] = x => { var file = pathProvider.GetRootPath(); file = Path.Combine(file, "index.html"); return(Response.AsText(File.ReadAllText(file), "text/html")); }; }
private static dynamic BuildFileDownloadResponse(IRootPathProvider pathProvider, string fileName) { var mimeType = MimeTypes.GetMimeType(fileName); var path = Path.Combine(pathProvider.GetRootPath(), fileName); Func <Stream> file = () => new FileStream(path, FileMode.Open); var response = new StreamResponse(file, mimeType); var fileInfo = new FileInfo(path); return(response.AsAttachment(fileInfo.Name)); }
private string GetUploadDirectory() { var uploadDirectory = Path.Combine(rootPathProvider.GetRootPath(), path); if (!Directory.Exists(uploadDirectory)) { Directory.CreateDirectory(uploadDirectory); } return(uploadDirectory); }
public CassetteStartup(IRootPathProvider rootPathProvider) { this.rootPathProvider = rootPathProvider; // This will trigger creation of the Cassette infrastructure at the time of the first request. // The virtual directory is not known until that point, and the virtual directory is required for creation. this.getApplication = InitializeApplication; CassetteApplicationContainer.SetApplicationAccessor(() => getApplication()); routeGenerator = new CassetteRouteGenerator(rootPathProvider.GetRootPath(), GetCurrentContext); }
private dynamic UploadFile(HttpFile file) { string filePath = Path.Combine(_rootPath.GetRootPath(), "uploads", "images", file.Name); using (var fileStream = File.Create(filePath)) { file.Value.CopyTo(fileStream); } return(View["FileUploaded", file.Name]); }
/// <summary> /// Perform any initialisation tasks /// </summary> public void Initialize(IApplicationPipelines pipelines) { var item = new PipelineItem <Func <NancyContext, Response> >("Static content", ctx => { return(conventions .Select(convention => convention.Invoke(ctx, rootPathProvider.GetRootPath())) .FirstOrDefault(response => response != null)); }); pipelines.BeforeRequest.AddItemToStartOfPipeline(item); }
public void Handle(HttpStatusCode statusCode, NancyContext context) { context.Response.Contents = stream => { var filename = Path.Combine(_rootPathProvider.GetRootPath(), "content/PageNotFound.html"); using (var file = File.OpenRead(filename)) { file.CopyTo(stream); } }; }
public CassetteStartup(IRootPathProvider rootPathProvider) { this.rootPathProvider = rootPathProvider; // This will trigger creation of the Cassette infrastructure at the time of the first request. // The virtual directory is not known until that point, and the virtual directory is required for creation. this.getApplication = InitializeApplication; CassetteApplicationContainer.SetApplicationAccessor(() => getApplication()); routeGenerator = new CassetteRouteGenerator(rootPathProvider.GetRootPath(), GetCurrentContext); }
// TODO Move to separate service. private string GetUploadDirectory() { var uploadDirectory = Path.Combine(rootPathProvider.GetRootPath(), applicationSettings.FileUploadDirectory); if (!Directory.Exists(uploadDirectory)) { Directory.CreateDirectory(uploadDirectory); } return(uploadDirectory); }
private void InitUploadDirectory() { var uploadDirectory = Path.Combine(_rootPathProvider.GetRootPath(), _applicationSettings["UploadDirectory"]); if (!Directory.Exists(uploadDirectory)) { Directory.CreateDirectory(uploadDirectory); } UploadDirectory = uploadDirectory; }
public HelpApi(IRootPathProvider pathProvider):base("/help") { var xmlDocPath = Path.Combine(pathProvider.GetRootPath(), ConfigurationManager.AppSettings["xmlDocumentationFile"]); _apiExplorer = new DefaultApiExplorer(ModulePath, xmlDocPath); Get["/"] = q => View["RouteCatelog.cshtml", _apiExplorer.ModuleRouteCatelog]; Get["/{api*}"] = context => { var model = _apiExplorer.GetRouteDetail(Request.Path); return View["RouteDetail.cshtml", model]; }; Get["/resourceModel/{modelName}"] = context => View["ResourceModel.cshtml", _apiExplorer.GetResourceDetail(Request.Path)]; }
protected string SaveFile(HttpFile file, IRootPathProvider pathProvider) { var uploadDirectory = Path.Combine(pathProvider.GetRootPath(), "Content", "uploads"); if (!Directory.Exists(uploadDirectory)) { Directory.CreateDirectory(uploadDirectory); } var filename = Path.Combine(uploadDirectory, System.Guid.NewGuid().ToString() + file.Name); //HACK creates a unique file name by prepending a Guid using (FileStream fileStream = new FileStream(filename, FileMode.Create)) { file.Value.CopyTo(fileStream); } return filename; }
public static IEnumerable<string> TransformJSX(IRootPathProvider pathProvider) { var outputFiles = new List<string>(); bool useHarmony = false; bool stripTypes = false; var config = React.AssemblyRegistration.Container.Resolve<IReactSiteConfiguration>(); config .SetReuseJavaScriptEngines(false) .SetUseHarmony(useHarmony) .SetStripTypes(stripTypes); var environment = React.AssemblyRegistration.Container.Resolve<IReactEnvironment>(); string root = pathProvider.GetRootPath(); var files = Directory.EnumerateFiles(root + "Scripts", "*.jsx", SearchOption.AllDirectories); foreach (var path in files) { outputFiles.Add(environment.JsxTransformer.TransformAndSaveJsxFile("~/" + path.Replace(root, string.Empty))); } return outputFiles; }
public HomeModule( IMarkdownRepository markdownRepository, IMembershipOrganisationRepository membershipOrganisationRepository, IPaymentMethodRepository paymentMethodRepository, RegistrationViewModel registrationViewModel, IRootPathProvider rootPathProvider ) { // todo: do I really need / and /{page}? Get["/"] = parameters => { return PageView(markdownRepository.GetMarkdown("home")); }; Get["/registration"] = parameters => { var isDeveloperMachine = rootPathProvider.GetRootPath().StartsWith(@"C:\Users\Tim\Code\"); return View["registration", new { isDeveloperMachine }]; }; Post["/registration"] = parameters => { this.BindTo(registrationViewModel); var validation = this.Validate(registrationViewModel); if (!validation.IsValid) { return View["registration", registrationViewModel]; } throw new System.NotImplementedException("post valid viewmodel"); }; Get["/{page}", ctx => markdownRepository.MarkdownExists(ctx.Request.Path)] = parameters => { return PageView(markdownRepository.GetMarkdown(parameters.page)); }; }
public UsersModule(UserService userService, IRootPathProvider pathProvider) { this.RequiresAuthentication(); Get["/users"] = parameters => View[new UsersModel() {Users = userService.GetUsers()}]; Get["/users/{Id}"] = parameters => { Guid result; var isInteger = Guid.TryParse(parameters.id, out result); var user = userService.GetById(result); if (isInteger && user != null) { return View[user]; } else { return HttpStatusCode.NotFound; } }; Get["/users/userimageupload/{Id}"] = parameters => { Guid result; var isGuid = Guid.TryParse(parameters.id, out result); var user = userService.GetById(result); if (isGuid && user != null) { return View["UploadUserImage",user]; } return HttpStatusCode.NotFound; }; Post["/users/userimageupload/{Id}"] = parameters => { Guid result; var isGuid = Guid.TryParse(parameters.Id, out result); var user = userService.GetById(result); var file = this.Request.Files.FirstOrDefault(); if (isGuid && user != null && file != null) { var fileDetails = string.Format("{3} - {0} ({1}) {2}bytes", file.Name, file.ContentType, file.Value.Length, file.Key); user.FileDetails = fileDetails; var filename = Path.Combine(pathProvider.GetRootPath(), "Images", user.Id + ".jpeg"); using (var fileStream = new FileStream(filename, FileMode.Create)) { file.Value.CopyTo(fileStream); } return View[user]; } return HttpStatusCode.NotFound; }; Get["/users/getimage/{Id}"] = parameters => { Guid result; var isGuid = Guid.TryParse(parameters.Id, out result); var filename = Path.Combine(pathProvider.GetRootPath(), "Images", result.ToString() + ".jpeg"); if (!File.Exists(filename)) filename = Path.Combine(pathProvider.GetRootPath(), "Images", "emptyuser.jpeg"); var stream = new FileStream(filename, FileMode.Open); return Response.FromStream(stream, "image/jpeg"); }; }
/// <summary> /// Initializes a new instance of the <see cref="FileSystemViewLocationProvider"/> class. /// </summary> /// <param name="rootPathProvider">A <see cref="IRootPathProvider"/> instance..</param> public FileSystemViewLocationProvider(IRootPathProvider rootPathProvider) { this.rootPath = rootPathProvider.GetRootPath(); }
/// <summary> /// Initializes a new instance of the <see cref="RootPathStartup"/> class. /// </summary> /// <param name="rootPathProvider">An <see cref="IRootPathProvider"/> instance.</param> public RootPathStartup(IRootPathProvider rootPathProvider) { GenericFileResponse.RootPath = rootPathProvider.GetRootPath(); }
public LoginModule(IRootPathProvider pathProvider) { Before += ctx => { if (ctx.Request.Cookies.ContainsKey("flex")) { var myId = ctx.Request.Cookies["flex"]; var id_user = new EncryptHelper(AppConfig.Provider, Xmlconfig.get( "cryptokey", pathProvider.GetRootPath()).Value).decrypt(myId); if (!string.IsNullOrEmpty(id_user)) { return Response.AsRedirect("/slides"); //redirects to items } } return null; //it means you can carry on!!!! }; Get["/login"] = _ => { var model = new { title = "Mobile Day 2014 - Reveal.js - The HTML Presentation Framework" }; return View["login", model]; }; Post["/login"] = _ => { dynamic model = null; var us = new User { UserName = Request.Form.username, Password = Request.Form.password, }; //first of all validate data if (string.IsNullOrEmpty(us.UserName) || string.IsNullOrEmpty(us.Password)) { model = new { title = "Mobile Day 2014 - Reveal.js - The HTML Presentation Framework", user = us, success = false, messages = new List<string> { "Please, provide username and password" } }; } else { us.Password = new EncryptHelper(AppConfig.Provider, Xmlconfig.get("cryptokey", pathProvider.GetRootPath()).Value).encrypt(us.Password); //real_password var ut_res = UsersRepository.authenticate(us); if (ut_res != null) { var myEncryptedId = new EncryptHelper(AppConfig.Provider, Xmlconfig.get("cryptokey", pathProvider.GetRootPath()).Value).encrypt(ut_res.Id.ToString() ); //encrypt 4 cookie //create cookie, http only with encrypted id user and add it to the current response var mc = new NancyCookie("flex", myEncryptedId, true); var res = Response.AsRedirect("/slides"); res.WithCookie(mc); return res; } else { model = new { title = "Mobile Day 2014 - Reveal.js - The HTML Presentation Framework", user = us, success = false, messages = new List<string> { "Wrong username or password" } }; } } return View["login", model]; }; }
public IndexModule(IRootPathProvider rootPathProvider, IUserRepository userRepository, IDeploymentRepository deploymentRepository) { Post["/"] = parameters => { var payloadModel = this.Bind<GithubHookModel.RootObject>(); //Check if user is registered var githubhookfromUsername = payloadModel.repository.owner.name; var githubhookfromRepo = payloadModel.repository.url; if (!userRepository.UserRegistered(githubhookfromUsername, githubhookfromRepo)) return HttpStatusCode.Forbidden; var gitLocation = ConfigurationManager.AppSettings["GitLocation"]; var repoPath = rootPathProvider.GetRootPath() + ".git"; if (!Directory.Exists(repoPath)) { var cloneProcess = Process.Start(gitLocation + " clone " + payloadModel.repository.url + " " + repoPath); if (cloneProcess != null) cloneProcess.WaitForExit(); } else { //Shell out to git.exe as LibGit2Sharp doesnt support Merge yet var pullProcess = Process.Start(gitLocation + " --git-dir=\"" + repoPath + "\" pull upstream master"); if (pullProcess != null) pullProcess.WaitForExit(); } //Run the PreCompiler var addProcess = Process.Start(gitLocation + " --git-dir=\"" + repoPath + "\" add -A"); if (addProcess != null) addProcess.WaitForExit(); var commitProcess = Process.Start(gitLocation + " --git-dir=\"" + repoPath + "\" commit -a -m \"Static Content Regenerated\""); if (commitProcess != null) commitProcess.WaitForExit(); var pushProcess = Process.Start("C:\\Program Files (x86)\\Git\bin\\git.exe --git-dir=\"" + repoPath + "\" push upstream master"); if (pushProcess != null) pushProcess.WaitForExit(); return 200; }; Get["/"] = parameters => { return View["Index"]; }; Get["/repos"] = parameters => { return View["Repos"]; }; Get["getrepodata/{githubuser}"] = parameters => { var githubUser = (string)parameters.githubuser; var client = new RestClient("https://api.github.com"); var request = new RestRequest("users/" + githubUser + "/repos"); request.AddHeader("Accept", "application/json"); var response = client.Execute<List<GithubUserRepos.RootObject>>(request); var repoDetail = response.Data .Where(x => x.fork == false) .Select( x => new RepoDetail { Name = x.name, AvatarUrl = x.owner.avatar_url, Description = x.description, HtmlUrl = x.html_url, UpdatedAt = DateTime.Parse(x.pushed_at).ToRelativeTime(), CloneUrl = x.clone_url }); var viewModel = new RepoModel { Username = githubUser, Repos = repoDetail }; return viewModel; }; Post["initializedeployment"] = parameters => { var model = this.BindAndValidate<DeploymentModel>(); if (!this.ModelValidationResult.IsValid) { } return "deployed"; }; Post["/alreadyregistered"] = parameters => { string repo = (string) Request.Form.repo; var alreadyRegistered = deploymentRepository.IsUserAndRepoRegistered(); return alreadyRegistered; }; }
/// <summary> /// Initializes a new instance of the <see cref="RootPathApplicationStartup"/> class. /// </summary> /// <param name="rootPathProvider">An <see cref="IRootPathProvider"/> instance.</param> public RootPathApplicationStartup(IRootPathProvider rootPathProvider) { GenericFileResponse.SafePaths.Add(rootPathProvider.GetRootPath()); }
public ItemModule(IRootPathProvider pathProvider) { User me = null; //add the user as a property to the model :) Before += ctx => { if (ctx.Request.Cookies.ContainsKey("flex")) { var myId = ctx.Request.Cookies["flex"]; var id_user = new EncryptHelper(AppConfig.Provider, Xmlconfig.get( "cryptokey", pathProvider.GetRootPath()).Value).decrypt(myId); if (!string.IsNullOrEmpty(id_user)) { me = UsersRepository.getById(Convert.ToInt32(id_user)); return null; //it means you can carry on!!!! } } var res = new Response(); res.StatusCode = HttpStatusCode.Forbidden; return res; }; Get["/items"] = _ => { var model = new { title = "Son Quattro CMS", items = ItemsRepository.Items, me = me }; return View["items", model]; }; Get[@"/items/(?<order>[0-3])"] = parameters => { //*important byte order = parameters.order; //I'm forcing the right conversion var model = new { title = "Son Quattro CMS", item = ItemsRepository.getByOrder(order), me = me }; return View["single_item", model]; }; Post["/items/(?<order>[0-3])"] = parameters => { byte order = parameters.order; Item it = null; //check if you're only changing other then the pix if (Request.Form.title != null) { it = new Item { Order = parameters.order, Title = Request.Form["title"], Description = Request.Form["description"], Image = Request.Form["image"] }; } else { int x1 = Request.Form.x1; int y1 = Request.Form.y1; int x2 = Request.Form.x2; int y2 = Request.Form.y2; int w = Request.Form.w; int h = Request.Form.h; string image_file = Guid.NewGuid() + ".png"; string image_file_raw = Request.Form.b64_img; var image_b64 = image_file_raw.Replace("data:image/jpeg;base64,", "").Replace("data:image/png;base64,", "").Replace("data:image/gif;base64,", ""); var rimg = ImageHelper.b64ToImage(image_b64); var ratio = Convert.ToDecimal(rimg.Width) / Convert.ToDecimal(528); var rect = ImageHelper.ratioRectangle(new Rectangle(x1, y1, w, h), ratio); var n_img = ImageHelper.cropImage(rimg, rect); //at the end resize 840x540 var r_img = ImageHelper.resize(n_img, 840); r_img.Save(pathProvider.GetRootPath() + @"images\" + image_file); it = ItemsRepository.getByOrder(order); it.Image = image_file; } dynamic model = null; var result = ItemsRepository.insert(order, it); if (result != null) { model = new { title = "Son Quattro CMS", item = result, success = true, messages = new List<string> { "The item has been successfull modified" }, me = me }; } else { model = new { title = "Son Quattro Items CRUD", item = it, //I'm going to return back the one given success = false, messages = new List<string> { "The item could not be modified" }, me = me }; } return View["single_item", model]; }; }
public CompareModule(IRootPathProvider rootPathProvider, IBus bus, NuGetBrowser nuGetBrowser) { Get["/compare/{nugetpackageid}/{leftversion}...{rightversion}"] = ctx => { var nugetPackageId = (string)ctx.nugetpackageid; SemanticVersion leftVersion; SemanticVersion rightVersion; var redirectToExactComparison = false; try { if (TryExpandVersion(nuGetBrowser, nugetPackageId, ctx.leftversion, out leftVersion)) { redirectToExactComparison = true; } if (TryExpandVersion(nuGetBrowser, nugetPackageId, ctx.rightversion, out rightVersion)) { redirectToExactComparison = true; } } catch (NotFoundException ex) //for now { return new NotFoundResponse { ReasonPhrase = ex.Message }; } if (redirectToExactComparison) { return Response.AsRedirect(string.Format("/compare/{0}/{1}...{2}", nugetPackageId, leftVersion, rightVersion)); } var pathToAlreadyRenderedComparison = string.Format("./Comparisons/{0}-{1}...{2}.html", nugetPackageId, leftVersion, rightVersion); if (File.Exists(Path.Combine(rootPathProvider.GetRootPath(), pathToAlreadyRenderedComparison))) { return new GenericFileResponse(pathToAlreadyRenderedComparison, "text/html"); } var pathToWorkingToken = string.Format("./Comparisons/{0}-{1}...{2}.running.html", nugetPackageId, leftVersion, rightVersion); var fullPathToWorkingToken = Path.Combine(rootPathProvider.GetRootPath(), pathToWorkingToken); if (File.Exists(fullPathToWorkingToken)) { return new GenericFileResponse(pathToWorkingToken, "text/html"); } logger.DebugFormat("Sending command to backend to process '{0}' package versions '{1}' and '{2}'.", nugetPackageId, leftVersion, rightVersion); bus.Send(new CompareNugetPackage(nugetPackageId, leftVersion.ToString(), rightVersion.ToString())); var fullPathToTemplate = Path.Combine(rootPathProvider.GetRootPath(), "./Comparisons/CompareRunning.html"); File.Copy(fullPathToTemplate, fullPathToWorkingToken); var template = File.ReadAllText(fullPathToWorkingToken); var content = template.Replace(@"{packageid}", nugetPackageId) .Replace(@"{leftversion}", leftVersion.ToString()) .Replace(@"{rightversion}", rightVersion.ToString()); File.WriteAllText(fullPathToWorkingToken, content); return new GenericFileResponse(pathToWorkingToken, "text/html"); }; }
public IndexModule(IGithubUserRepository githubUserRepository, IDeploymentRepository deploymentRepository, IRootPathProvider rootPathProvider) { this.githubUserRepository = githubUserRepository; this.rootPathProvider = rootPathProvider; this.snowPreCompilerPath = rootPathProvider.GetRootPath() + "PreCompiler\\Sandra.Snow.Precompiler.exe"; Post["/"] = parameters => { var payloadModel = this.Bind<GithubHookModel.RootObject>(); //Check if user is registered var githubhookfromUsername = payloadModel.repository.owner.name; var githubhookfromRepo = payloadModel.repository.url; if (!githubUserRepository.UserRegistered(githubhookfromUsername, githubhookfromRepo)) return HttpStatusCode.Forbidden; var deploymentModel = deploymentRepository.GetDeployment(githubhookfromUsername); DeployBlog(deploymentModel); return 200; }; Get["/"] = parameters => { return View["Index"]; }; Get["/repos"] = parameters => { return View["Repos"]; }; Get["getrepodata/{githubuser}"] = parameters => { var githubUser = (string)parameters.githubuser; var client = new RestClient("https://api.github.com"); var request = new RestRequest("users/" + githubUser + "/repos"); request.AddHeader("Accept", "application/json"); var response = client.Execute<List<GithubUserRepos.RootObject>>(request); var repoDetail = response.Data //.Where(x => x.fork == false) .Select( x => new RepoDetail { Name = x.name, AvatarUrl = x.owner.avatar_url, Description = x.description, HtmlUrl = x.html_url, UpdatedAt = DateTime.Parse(x.pushed_at).ToRelativeTime(), CloneUrl = x.clone_url }); var viewModel = new RepoModel { Username = githubUser, Repos = repoDetail }; return viewModel; }; Post["initializedeployment"] = parameters => { var model = this.BindAndValidate<DeploymentModel>(); if (!this.ModelValidationResult.IsValid) { return 400; } DeployBlog(model); deploymentRepository.AddDeployment(model); Thread.Sleep(2500); return "deployed"; }; Post["/alreadyregistered"] = parameters => { var model = this.Bind<AlreadyRegisteredModel>(); var alreadyRegistered = deploymentRepository.IsUserAndRepoRegistered(model.AzureDeployment, model.Repo, model.Username); var keys = new List<string>(); keys.Add(model.AzureDeployment ? "azurerepo" : "ftpserver"); return new { isValid = !alreadyRegistered, keys = keys }; }; }
private void ConfigureTimesheetModules(IRootPathProvider pathProvider) { var configPath = Path.Combine(pathProvider.GetRootPath(), "timesheet.config"); config = new TimesheetConfig(); using (var timesheetStream = new StreamReader(configPath)) { var configXml = new XmlSerializer(typeof(TimesheetConfig)); config = (TimesheetConfig)configXml.Deserialize(timesheetStream); timesheetStream.Close(); } timesheetLog = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "Timesheet.log"); timesheetPythonModulesPath = Path.Combine(pathProvider.GetRootPath(), config.Module.Relativepath); estimatedHoursScript = Path.Combine(timesheetPythonModulesPath, config.WeeksFeed.Filename); spreadsheetGeneratorScript = Path.Combine(timesheetPythonModulesPath, config.SpreadsheetGenerator.Filename); timesheetWriterType = config.WriterType.Type ?? string.Empty; }
public EventsModule(IRootPathProvider pathProvider) : base("api/events") { Get["/"] = _ => { var db = DbRepository.GetDb(); var events = db.UseOnceTo().Query<Event>().ToArray(); var thinEvents = events.Select(p => new { p.Id, p.Title }); return Response.AsJson(thinEvents); }; Get["/{id:int}"] = _ => { var id = (int)_.id.Value; var db = DbRepository.GetDb(); var eventEntry = db.UseOnceTo().GetById<Event>(id); eventEntry.HaxballLeague = null; return Response.AsJson(eventEntry); }; Post["/"] = _ => { var eventEntry = this.Bind<Event>(); var db = DbRepository.GetDb(); db.UseOnceTo().Insert(eventEntry); return HttpStatusCode.Created; }; Post["/{id:int}"] = _ => { var id = (int)_.id.Value; var db = DbRepository.GetDb(); var eventEntry = db.UseOnceTo().GetById<Event>(id); this.BindTo(eventEntry, ReflectionHelper.GetPropertyName<Event>(p => p.HaxballLeague)); db.UseOnceTo().Update(eventEntry); return HttpStatusCode.OK; }; Post["/imageupload/{Id:int}"] = _ => { var id = (int)_.id.Value; var file = this.Request.Files.FirstOrDefault(); if (file != null) { var filename = Path.Combine(pathProvider.GetRootPath(), "HolidayImages", id + ".png"); DirectoryUtils.EnsureDirectoryExistst(filename); using (var fileStream = new FileStream(filename, FileMode.Create)) { file.Value.CopyTo(fileStream); } return Response.AsRedirect("/admin/events/"); } return HttpStatusCode.NotFound; }; Delete["/{id:int}"] = parameters => { int eventId = (int)parameters.id.Value; var db = DbRepository.GetDb(); db.UseOnceTo().DeleteById<Event>(eventId); return HttpStatusCode.NoContent; }; }
public ArticleLocator(IRootPathProvider rootPathProvider) { _rootPath = rootPathProvider.GetRootPath() + "/views"; }
public NotifyHook(IRootPathProvider rootPathProvider) { Post["/notify"] = x => { var rootPath = rootPathProvider.GetRootPath(); bool skipEmail; bool.TryParse(Request.Query["skipEmail"], out skipEmail); PushData pushData = JsonConvert.DeserializeObject<PushData>(Request.Form["payload"]); var oldestCommit = pushData.Commits.OrderBy(c => c.Timestamp).First(); var oldestCommitMsgFirstLine = oldestCommit.Message.Split('\n')[0]; var subject = string.Format("[{0}/{1}, {2}] ({3}) {4}", pushData.Repository.Owner.Name, pushData.Repository.Name, pushData.Branch, oldestCommit.Author.Username, oldestCommitMsgFirstLine); var template = File.ReadAllText(Path.Combine(rootPath, @"Views", @"Notify.cshtml")); var body = Razor.Parse(template, pushData); if (skipEmail) return body; var from = ConfigurationManager.AppSettings["EmailsFrom"]; var fromName = ConfigurationManager.AppSettings["EmailsFromName"]; var mailMessage = new MailMessage { From = new MailAddress(from, (string.IsNullOrEmpty(fromName) ? from : fromName)), Subject = subject, Body = body, IsBodyHtml = true }; var replyTo = ConfigurationManager.AppSettings["EmailsReplyTo"]; var replyToName = ConfigurationManager.AppSettings["EmailsReplyToName"]; if (!string.IsNullOrEmpty(replyTo)) mailMessage.ReplyToList.Add(new MailAddress(replyTo, (string.IsNullOrEmpty(replyToName) ? replyTo : replyToName))); mailMessage.Headers.Add("gh-repo", pushData.Repository.Name); mailMessage.To.Add(ConfigurationManager.AppSettings["EmailsTo"]); new SmtpClient().Send(mailMessage); return "email sent"; }; }
/// <summary> /// Initializes a new instance of the <see cref="FileSystemViewLocationProvider"/> class. /// </summary> /// <param name="rootPathProvider">A <see cref="IRootPathProvider"/> instance.</param> /// <param name="fileSystemReader">An <see cref="IFileSystemReader"/> instance that should be used when retrieving view information from the file system.</param> public FileSystemViewLocationProvider(IRootPathProvider rootPathProvider, IFileSystemReader fileSystemReader) { this.fileSystemReader = fileSystemReader; this.rootPath = rootPathProvider.GetRootPath(); }
public TimeRegistrationModule(IProjectRepository projectRepository, IClientRepository clientRepository, ITimeRegistrationRepository timeRegistrationRepository, IIdGenerator idGenerator, IAggregateRootRepository aggregateRootRepository, IRootPathProvider rootPathProvider, IExcelService excelService) : base("/timeregistration") { this.RequiresAuthentication(); Get["/"] = _ => View["Index"]; Get["/overview"] = _ => View["Overview"]; Get["/report"] = _ => View["Report"]; Get["/import"] = _ => View["Import"]; Post["/importupload"] = _ => { var fileName = Guid.NewGuid().ToString("N").Substring(0, 4) + "_" + Path.GetFileName((string)Request.Files.First().Name); var path = Path.Combine(rootPathProvider.GetRootPath(), "App_Data", "Uploads", fileName); using (var fileStream = new FileStream(path, FileMode.Create)) { Request.Files.First().Value.CopyTo(fileStream); } return Response.AsRedirect("~/timeregistration/importmap/" + HttpUtility.UrlEncode(fileName)); }; Get["/importmap/{url*}"] = parameters => { var viewModel = new ImportViewModel(); viewModel.ServerFile = Path.Combine(rootPathProvider.GetRootPath(), "App_Data", "Uploads", parameters.url); var excelPackage = new ExcelPackage(new FileInfo(viewModel.ServerFile)); var worksheet = excelPackage.Workbook.Worksheets.First(); viewModel.ColumnNames = new List<ImportViewModel.ColumnInfo>(); foreach (var firstRowCell in worksheet.Cells[worksheet.Dimension.Start.Row, worksheet.Dimension.Start.Column, 1, worksheet.Dimension.End.Column]) viewModel.ColumnNames.Add(new ImportViewModel.ColumnInfo { Column = firstRowCell.Start.Column, Name = firstRowCell.Text }); return View["ImportMap", viewModel]; }; Post["/import"] = _ => { var viewModel = this.Bind<ImportViewModel>(); var result = excelService.Import(viewModel.ServerFile, viewModel.ProjectIdColumn, viewModel.TaskColumn, viewModel.DateColumn, viewModel.FromColumn, viewModel.ToColumn, viewModel.RateColumn, viewModel.DescriptionColumn); return View["ImportResult", result]; }; Get["/export/{fromDate}/{toDate}"] = parameters => { var min = ((DateTime)parameters.fromDate).GetNumericValue(); var max = ((DateTime)parameters.toDate).AddDays(1).GetNumericValue(); var items = timeRegistrationRepository .Where(t => t.Date.Numeric >= min && t.Date.Numeric < max) .OrderBy(t => t.Date.Numeric) .ThenBy(t => t.From.Numeric) .ToList(); return Response.AsExcel(items); }; }
public VerificationEmailTemplate(IRootPathProvider rootPathProvider) { _html = File.ReadAllText(rootPathProvider.GetRootPath() + "/EmailTemplates/verificationEmail.html"); }
public UserModule(IRootPathProvider pathProvider) { User me = null; //add the user as a property to the model :) Before += ctx => { if (ctx.Request.Cookies.ContainsKey("flex")) { var myId = ctx.Request.Cookies["flex"]; var id_u = new EncryptHelper(AppConfig.Provider, Xmlconfig.get( "cryptokey", pathProvider.GetRootPath()).Value).decrypt(myId); if (!string.IsNullOrEmpty(id_u)) { me = UsersRepository.getById(Convert.ToInt32(id_u)); if (me != null) { return null; //it means you can carry on!!!! } } } var res = new Response(); res.StatusCode = HttpStatusCode.Forbidden; return res; }; Get["/users"] = _ => { var model = new { title = "Son Quattro CMS", users = UsersRepository.getOrderedByName(), me = me }; if (!me.IsAdmin) //check if I am an admin { var res = new Response(); res.StatusCode = HttpStatusCode.Forbidden; return res; } else return View["users", model]; }; Get[@"/users/{id:int}"] = parameters => { //*important int id = parameters.id; //I'm forcing the right conversion var puser = UsersRepository.getById(id); if (puser == null) //the user does not exists { var res = new Response(); res.StatusCode = HttpStatusCode.NotFound; return res; } var model = new { title = "Son Quattro CMS", user = puser, me = me }; if ((me.Id != id) && !me.IsAdmin) //check if I am not an admin and I'm changing someone's else profile { var res = new Response(); res.StatusCode = HttpStatusCode.Forbidden; return res; } return View["single_user", model]; }; Post["/users/{id:int}"] = parameters => { //*important int id = parameters.id; dynamic model = null; //check first if I'm a simple editor, not an Admin and I want to change someone's else profile if ((me.Id != id) && !me.IsAdmin) { var res = new Response(); res.StatusCode = HttpStatusCode.Forbidden; return res; } var us = new User { Id = id, UserName = Request.Form.username, Password = Request.Form.password, SimpleRoles = Request.Form.hr }; if ((me.Id == id) && me.IsAdmin && !us.SimpleRoles.Contains("0")) { model = new { title = "Son Quattro CMS", user = us, me = me, success = false, messages = new List<string> { "You can't quit being an admin!" } }; } else { var rip_password = Request.Form.repeate_password; //first of all validate data if ((us.Password != rip_password) && (!string.IsNullOrEmpty(us.Password))) { model = new { title = "Son Quattro CMS", user = us, me = me, success = false, messages = new List<string> { "Please, the passwords must match" } }; } else { //first of all validate data if (string.IsNullOrEmpty(us.UserName) || (string.IsNullOrEmpty(us.SimpleRoles) && me.IsAdmin)) { model = new { title = "Son Quattro CMS", user = us, me = me, success = false, messages = new List<string> { "Please, provide username and at least one role." } }; } else { var isChangePassword = false; //Am I trying to change the password? if (!string.IsNullOrEmpty(us.Password)) { us.Password = new EncryptHelper(AppConfig.Provider, Xmlconfig.get("cryptokey", pathProvider.GetRootPath()).Value).encrypt(us.Password); //real_password isChangePassword = true; } if (me.IsAdmin) //only an admin can change the roles { us = UsersRepository.insertIfAdmin(us, isChangePassword); } else { us = UsersRepository.insert(us, isChangePassword); } if (us != null) { model = new { title = "Son Quattro CMS", user = us, me = me, success = true, messages = new List<string> { "User modified succesfully" } }; } else { model = new { title = "Son Quattro CMS", user = us, me = me, success = false, messages = new List<string> { "Sorry, we couldn't find the user specified!" } }; } } } } return View["single_user", model]; }; }