Esempio n. 1
0
        public IDataBaseContext GetDataBaseDbContext(Type type)
        {
            IDataBaseContext dbContext = null;

            if (_contexts.ContainsKey(type))
            {
                return(_contexts[type]);
            }
            var instance = Activator.CreateInstance(type) as IDataBaseContext;

            if (instance == null)
            {
                throw new Exception($"创建上下文实例发生异常,请检查当前上下文 “{type}”是否实现 IDataBaseContext");
            }
            switch (instance.Type)
            {
            case DataBaseType.SqlServer:
                dbContext = new SqlServerDbContext();
                break;

            case DataBaseType.MySql:
                dbContext = new MySqlDbContext();
                break;

            case DataBaseType.Oracle:
                dbContext = new OracleDbContext();
                break;
            }
            _contexts.TryAdd(type, dbContext);
            return(dbContext);
        }
Esempio n. 2
0
        /// <summary>
        /// 获取指定的数据库上下文
        /// </summary>
        /// <param name="type"></param>
        /// <returns></returns>
        public IDataBaseContext GetDataBaseDbContext(DataBaseType type)
        {
            IDataBaseContext _dbContext = null;

            if (_typecontexts.ContainsKey(type))
            {
                return(_typecontexts[type]);
            }
            switch (type)
            {
            case DataBaseType.SqlServer:
                _dbContext = new SqlServerDbContext();
                break;

            case DataBaseType.MySql:
                _dbContext = new MySqlDbContext();
                break;

            case DataBaseType.Oracle:
                _dbContext = new OracleDbContext();
                break;
            }

            _typecontexts.TryAdd(type, _dbContext);
            return(_dbContext);
        }
 public async Task AddNewDataBaseAsync(IDataBaseContext dataBaseContext, TaskContext context)
 {
     var authentication = context.Authentication;
     var dataBaseName   = RandomUtility.NextIdentifier();
     var comment        = RandomUtility.NextString();
     await dataBaseContext.AddNewDataBaseAsync(authentication, dataBaseName, comment);
 }
Esempio n. 4
0
        public SystemManageModule(
            IDataBaseContext context)
            : base("/systemmanage/")
        {
            this.RequiresAuthentication();
            this.RequiresClaims(new[] { UserRole.Admin.ToString() });

            Get["/"] = prms =>
            {
                return Response.AsRedirect("/systemmanage/user");
            };

            Get["/user"] = prms =>
            {
                var users =
                    context.GetUser(_ => true)
                    .Select(u => this.AddIconFilePath(Request.Url, u))
                    .ToArray();

                return View["Views/SystemManageUser", new { Users = users }];
            };

            Get["/user/add"] = prms =>
            {
                return View["Views/SystemManageUserAdd"];
            };
        }
Esempio n. 5
0
 public DataBaseContextController(
     IEventAggregator eventAgg
     , IDataBaseContext context)
 {
     this.eventAgg = eventAgg;
     this.context = context;
     this.eventAgg.GetEvent<AuthUserEvent>().Subscribe(AuthUser, true);
     this.eventAgg.GetEvent<GetUserEvent>().Subscribe(GetUser, true);
     this.eventAgg.GetEvent<AddUserEvent>().Subscribe(AddUser, true);
     this.eventAgg.GetEvent<DeleteUserEvent>().Subscribe(DeleteUser, true);
     this.eventAgg.GetEvent<AddUserIconEvent>().Subscribe(AddUserIcon, true);
     this.eventAgg.GetEvent<AddProjectEvent>().Subscribe(AddProject, true);
     this.eventAgg.GetEvent<GetProjectEvent>().Subscribe(GetProject, true);
     this.eventAgg.GetEvent<UpdateProjectEvent>().Subscribe(UpdateProject, true);
     this.eventAgg.GetEvent<DeleteProjectEvent>().Subscribe(DeleteProject, true);
     this.eventAgg.GetEvent<GetTaskWithRecordEvent>().Subscribe(GetTaskWithRecord, true);
     this.eventAgg.GetEvent<AddTaskCommentEvent>().Subscribe(AddTaskComment, true);
     this.eventAgg.GetEvent<AddTaskRecordEvent>().Subscribe(AddTaskRecord, true);
     this.eventAgg.GetEvent<DeleteTaskRecordEvent>().Subscribe(DeleteTaskRecord, true);
     this.eventAgg.GetEvent<AddUserToTaskEvent>().Subscribe(AddUserToTask, true);
     this.eventAgg.GetEvent<GetDeleteTaskRecordPermissionEvent>().Subscribe(GetDeleteTaskRecordPermission, true);
     this.eventAgg.GetEvent<GetDeleteProjectPermissionEvent>().Subscribe(GetDeleteProjectPermission, true);
     this.eventAgg.GetEvent<GetDeleteUserPermissionEvent>().Subscribe(GetDeleteUserPermission, true);
     this.eventAgg.GetEvent<UpdateTaskEvent>().Subscribe(UpdateTask, true);
 }
        /// <summary>
        /// 构造Hadnler
        /// </summary>
        /// <param name="Entity">实体类型</param>
        /// <param name="context">上下文对象</param>
        public EntityHandler(T Entity, IDataBaseContext context)
        {
            IORMAdapter Adapter = ORMAdapterCreator.GetORMAdapter(context.ConnectionInfo.DataServerType);

            m_SQLBuilder = Adapter.CreateSQLBuilder(Entity, Adapter);
            m_Handle     = Adapter.GetDbHandler(context);
            m_Entity     = Entity;
        }
 public static Task <IDataBase[]> GetDataBasesAsync(this IDataBaseContext dataBaseContext, DataBaseFlags dataBaseFlags, Func <IDataBase, bool> predicate)
 {
     return(dataBaseContext.Dispatcher.InvokeAsync(() =>
     {
         var query = from item in dataBaseContext
                     where TestFlags(item, dataBaseFlags) && predicate(item)
                     select item;
         return query.ToArray();
     }));
Esempio n. 8
0
        public static async Task ClassInitAsync(TestContext context)
        {
            app = new();
            await app.InitializeAsync(context);

            await app.OpenAsync();

            dataBaseContext = app.GetService(typeof(IDataBaseContext)) as IDataBaseContext;
        }
Esempio n. 9
0
 public DownloadsImporter(
     //IContext context,
     IDataBaseContext dbContext,
     IPackageDownloadsSource downloadsSource,
     ILogger <DownloadsImporter> logger)
 {
     //_context = context ?? throw new ArgumentNullException(nameof(context));
     _downloadsSource = downloadsSource ?? throw new ArgumentNullException(nameof(downloadsSource));
     _logger          = logger ?? throw new ArgumentNullException(nameof(logger));
     _dbContext       = dbContext ?? throw new ArgumentNullException(nameof(dbContext));
 }
Esempio n. 10
0
 /// <summary>
 /// Initializes a new instance of the <see cref="UnitOfWork"/> class.
 /// </summary>
 /// <param name="context">
 /// The context. 
 /// </param>
 public UnitOfWork(IDataBaseContext context)
 {
     this.context = context;
     this.routeRepository = new RouteRepository(context);
     this.stopRepository = new StopRepository(context);
     this.feedbackRepository = new FeedbackRepository(context);
     this.transportTypeRepository = new TransportTypeRepository(context);
     this.languageRepository = new LanguageRepository(context);
     this.placeRepository = new PlaceRepository(context);
     this.buildingRepository = new BuildingRepository(context);
 }
Esempio n. 11
0
        public TaskModule(
            IDataBaseContext context)
            : base("/task/")
        {
            this.RequiresAuthentication();

            Get["/{id}"] = prms =>
            {
                var id = prms.id;

                var task =
                    context.GetTaskRecords(x => x.Id == id).FirstOrDefault();
                (task as TaskWithRecord).Assign = this.AddIconFilePath(Request.Url, task.Assign);

                var project =
                    context.GetProjectFromTask(id);

                var user =
                   context.GetUser(u => u.Id == Context.CurrentUser.UserName).FirstOrDefault();

                return View["Views/ProjectInTask"
                    , new
                    {
                        Auth = user,
                        Task = task,
                        Project = project,
                        Progress = (task.Records.Sum(x=>x.Value) / task.Value) * 100.0,
                        ProgressValue = task.Records.Sum(x => x.Value),
                    }];
            };

            Post["/{id}/assign"] = prms =>
            {
                var id = prms.id;

                var json = this.Request.Body.ToStreamString();
                var jObj = JObject.Parse(json);

                var query =
                    from task in context.GetTaskRecords(x => x.Id == id).FirstOrNothing()
                    from userid in jObj["userid"].Value<string>().ToMaybe()
                    from user in context.GetUser(u => u.Id == userid).FirstOrNothing()
                    select new { task, user };
                query.On(a =>
                {
                    context.AddTaskToUser(a.user, a.task.Id);
                });

                var status = query.Select(_ => HttpStatusCode.OK);

                return Response.AsJson(new { }, status.Return(HttpStatusCode.BadRequest));

            };
        }
Esempio n. 12
0
        /// <summary>
        /// 构造
        /// </summary>
        /// <param name="context"></param>
        /// <param name="Adapter"></param>
        public DataBaseHandler(IDataBaseContext context, IDataBaseAdapter Adapter)
        {
            if (Adapter == null)
            {
                throw new ArgumentException("Adapter is null");
            }
            m_Context       = context;
            m_ConnectString = m_Context.ConnectionInfo.ConnectionString;
            m_DBaseAdapter  = Adapter;
            m__HandlerID    = Guid.NewGuid().ToString();

            m_Hash = new Hashtable();
        }
        public static async Task <IDataBase[]> GenerateDataBasesAsync(this IDataBaseContext dataBaseContext, Authentication authentication, int count)
        {
            var itemList = new List <IDataBase>(count);

            for (var i = 0; i < count; i++)
            {
                var dataBaseName = await dataBaseContext.GenerateNewDataBaseNameAsync(RandomUtility.NextName());

                var comment = RandomUtility.NextString();
                var item    = await dataBaseContext.AddNewDataBaseAsync(authentication, dataBaseName, comment);

                itemList.Add(item);
            }
            return(itemList.ToArray());
        }
Esempio n. 14
0
        public UserModule(
            IDataBaseContext context)
            : base("/user/")
        {
            this.RequiresAuthentication();

            Get["/"] = prms =>
            {
                var userId = this.Context.CurrentUser.UserName;
                var url = string.Format("/user/{0}", userId);
                return Response.AsRedirect(url);
            };

            Get["/{id}"] = prms =>
            {
                var userId = prms.id.ToString();

                var user =
                    context.GetUser(u => u.Id == userId).FirstOrDefault();

                return View["Views/User", this.AddIconFilePath(Request.Url, user)];
            };

            Get["/{id}/edit"] = prms =>
            {
                var userId = prms.id;

                var user =
                    context.GetUser(u => u.Id == userId).FirstOrDefault();

                // 自分でなかったらダメ
                var canEdit =
                    user.Id == this.Context.CurrentUser.UserName
                    || this.Context.CurrentUser.Claims.Contains(UserRole.Admin.ToString());

                if (canEdit)
                {
                    return View["Views/UserEdit", this.AddIconFilePath(Request.Url, user)];
                }
                else
                {
                    var url = string.Format("/user/{0}", user.Id);
                    return Response.AsRedirect(url);
                }

            };
        }
        private void AddSyncState(string login, string filePath, IDataBaseContext dataBase)
        {
            var syncStates = dataBase.SyncStates.ToList().Where(x => x.Login == login && x.FilePath == filePath).ToList();

            if (syncStates.Any())
            {
                return;
            }

            var state = new SyncState()
            {
                Login    = login,
                FilePath = filePath
            };

            dataBase.SyncStates.Add(state);
        }
Esempio n. 16
0
 public DataBaseContextController(
     IEventAggregator eventAgg
     , IDataBaseContext context)
 {
     this.eventAgg = eventAgg;
     this.context  = context;
     this.eventAgg.GetEvent <AuthUserEvent>().Subscribe(AuthUser, true);
     this.eventAgg.GetEvent <GetUserEvent>().Subscribe(GetUser, true);
     this.eventAgg.GetEvent <AddUserEvent>().Subscribe(AddUser, true);
     this.eventAgg.GetEvent <AddUserIconEvent>().Subscribe(AddUserIcon, true);
     this.eventAgg.GetEvent <AddProjectEvent>().Subscribe(AddProject, true);
     this.eventAgg.GetEvent <GetProjectEvent>().Subscribe(GetProject, true);
     this.eventAgg.GetEvent <UpdateProjectEvent>().Subscribe(UpdateProject, true);
     this.eventAgg.GetEvent <GetTaskWithRecordEvent>().Subscribe(GetTaskWithRecord, true);
     this.eventAgg.GetEvent <AddTaskCommentEvent>().Subscribe(AddTaskComment, true);
     this.eventAgg.GetEvent <AddTaskRecordEvent>().Subscribe(AddTaskRecord, true);
     this.eventAgg.GetEvent <AddUserToTaskEvent>().Subscribe(AddUserToTask, true);
 }
Esempio n. 17
0
        public ProjectManageModule(
            IDataBaseContext context
            , [Dependency("workdaySettingFolder")] string workdaySettingFolder)
            : base("/projectmanage/")
        {
            this.RequiresAuthentication();
            this.RequiresClaims(new[] { UserRole.Admin.ToString() });

            Get["/{id}"] = prms =>
            {
                var id = (int)prms.id;
                return Response.AsRedirect(string.Format("/projectmanage/{0}/setupworkdays", id));
            };

            Get["/{id}/setupworkdays"] = prms =>
            {
                var id = (int)prms.id;

                var view =
                    from p in context.GetProjects(x => x.Id == id).Select(p => MyClass.ToWithRecordsProject(context, p)).FirstOrNothing()
                    from workdayContext in MyClass.GetWorkdayContext(workdaySettingFolder, p.Id)
                    let workdays = workdayContext.Load()
                    let json = WorkdayModify.ToJsonText(workdays)
                    select View["Views/ProjectManageWorkdays", new { Project = p, Json = json }] as object;

                return view.Return(() => HttpStatusCode.BadRequest);
            };

            // todo api?
            Post["/{id}/setupworkdays"] = prms =>
            {
                var id = (int)prms.id;
                var query =
                    from p in context.GetProjects(x => x.Id == id).Select(p => MyClass.ToWithRecordsProject(context, p)).FirstOrNothing()
                    from workdayContext in MyClass.GetWorkdayContext(workdaySettingFolder, p.Id)
                    let json = this.Request.Body.ToStreamString()
                    let model = WorkdayModify.ToModel(json)
                    let result = Fn.New(()=> { workdayContext.Save(model); return 0; }).ToExceptional()
                    where result.IsRight
                    select Response.AsJson(new { }, HttpStatusCode.OK);
                return query.Return(() => HttpStatusCode.BadRequest);
            };
        }
        public static async Task ClassInitAsync(TestContext context)
        {
            app = new TestApplication();
            await app.InitializeAsync(context);

            await app.OpenAsync();

            authentication = await app.LoginRandomAsync(Authority.Admin);

            dataBaseContext = app.GetService(typeof(IDataBaseContext)) as IDataBaseContext;
            dataBase        = await dataBaseContext.GetRandomDataBaseAsync(DataBaseFlags.NotLoaded | DataBaseFlags.Public | DataBaseFlags.NotLocked);

            await dataBase.LoadAsync(authentication);

            await dataBase.EnterAsync(authentication);

            await dataBase.InitializeRandomItemsAsync(authentication, DataBaseSettings.Default);

            category = await dataBase.GetRandomTableCategoryAsync(item => item.Parent != null);
        }
Esempio n. 19
0
        public static void GenerateVies(IDataBaseContext context, int month, int year, DeclarConfigModel model)
        {
            Dictionary <string, string> declar = new Dictionary <string, string>();
            var firma = ConfigTempoSinglenton.GetInstance().CurrentFirma;

            declar.Add("data", string.Format("{0:D2}/{1:D4}", month, year));
            declar.Add("firma", firma.Name);
            declar.Add("address", firma.Address);
            declar.Add("tel", firma.Telefon);
            declar.Add("dds", firma.DDSnum);
            declar.Add("iddds", firma.Bulstad);
            declar.Add("city", firma.CityName);
            declar.Add("p", firma.PresentorYN == 1 ? "X" : " ");
            declar.Add("pr", firma.PresentorYN == 0 ? "X" : " ");
            declar.Add("zip", firma.Zip);
            declar.Add("egn", firma.EGN);
            declar.Add("address1", firma.Address2);
            if (firma.PresentorYN == 0)
            {
                declar.Add("mol", firma.NameBoss);
            }
            else
            {
                declar.Add("mol", firma.Names);
            }
            string actual;

            actual = DeklarviewModel.ReturnViesDeclar(declar, context.GetVies(month, year, declar));
            var path = AppDomain.CurrentDomain.BaseDirectory + "Vies1.txt";

            using (StreamWriter sw = new StreamWriter(path))
            {
                sw.Write(actual);
            }
            Process.Start(path);
        }
Esempio n. 20
0
 /// <summary>
 /// Initializes a new instance of the <see cref="FakeUnitOfWork"/> class.
 /// </summary>
 /// <param name="context">
 /// The context. 
 /// </param>
 public FakeUnitOfWork(IDataBaseContext context)
 {
     this.context = context;
 }
Esempio n. 21
0
 public ProductFacad(IDataBaseContext context, IHostingEnvironment environment, IDistributedCache distributedCache)
 {
     _context          = context;
     _environment      = environment;
     _distributedCache = distributedCache;
 }
Esempio n. 22
0
 public RepositoryAsync(IDataBaseContext context)
 {
     this.context = context;
 }
Esempio n. 23
0
 public BaseQuery(IDataBaseContext context)
 {
     _context = context;
 }
 public UnitOfWork(IDataBaseContext dbContext)
 {
     _dbContext = (DataBaseContext)dbContext;
 }
 public StrongHoldDataBase(IDataBaseContext dataBaseContext)
 {
     _dataBaseContext = dataBaseContext;
 }
Esempio n. 26
0
        public static IProject ToWithRecordsProject(IDataBaseContext context, IProject project)
        {
            // hack BindするためにSprintのITaskItemをITaskWithRecordに差し替える。
            var taskWithRecords = context.GetTaskRecords(_ => true).ToArray();
            var getWithTask = Fn.New((ITaskItem t) =>
            {
                var finded = taskWithRecords.FirstOrDefault(x => x.Id == t.Id);
                if (finded == null)
                {
                    return t;
                }
                //(finded as TaskWithRecord).Assign = this.AddIconFilePath(this.Request.Url, finded.Assign);
                return finded;
            });
            var toWithRecords = Fn.New((ISprint s) =>
            {
                var sprint = s as Sprint;
                sprint.Tasks =
                    sprint.Tasks.Select(getWithTask).ToArray();
                return sprint;
            });
            var toWithRecordsProject = Fn.New((IProject p) =>
            {
                p.Sprints = p.Sprints.Select(toWithRecords).ToArray();
                return p;
            });

            return toWithRecordsProject(project);
        }
Esempio n. 27
0
 public Repository(IDataBaseContext databaseContext)
 {
     _databaseContext = databaseContext;
     _dbSet           = (_databaseContext).Set <T>();
 }
Esempio n. 28
0
 public UserValidator(
     IDataBaseContext context)
 {
     this.context = context;
     this.formAuthCache = new Dictionary<string, Guid>();
 }
Esempio n. 29
0
        public DataApiModule(
            IDataBaseContext context
            , [Dependency("workdaySettingFolder")] string workdaySettingFolder)
            : base("/api/")
        {
            this.RequiresAuthentication();

            Get["/users/"] = _ =>
            {
                return
                    Response.AsJson(
                        context.GetUser(p => true)
                        .Select(u => this.AddIconFilePath(this.Request.Url, u))
                        .ToArray());
            };

            Get["/projects/"] = _ =>
            {
                var user =
                    from c in this.Context.CurrentUser.ToMaybe()
                    from name in c.UserName.ToMaybe()
                    from u in context.GetUser(x => x.Id == name).FirstOrNothing()
                    select u;

                if (user.IsNothing)
                    return HttpStatusCode.BadRequest;

                return
                    Response.AsJson(context.GetProjectBelongUser(user.Return())
                        .Select(p => MyClass.ToWithRecordsProject(context, p))
                        .ToArray());
            };

            Get["/project/{id}/report"] = prms =>
            {
                var id = (int)prms.id;
                var left = DateTime.MinValue;
                var right = DateTime.MaxValue;
                var current = DateTime.Now.AddDays(1);
                current = current.Date.AddTicks(-1);    // 現在日付+1から1ミリ秒引いて23:59:59を生成する

                var tryGetRangeDate = Fn.New((DateTime d, string s) => {
                    if (string.IsNullOrWhiteSpace(s))
                    {
                        return d;
                    }
                    var a = DateTime.MinValue;
                    if (DateTime.TryParse(s, out a) == false)
                        return d;
                    return a;
                });
                left = tryGetRangeDate(left, (string)this.Request.Query["startDay"]);
                right = tryGetRangeDate(right, (string)this.Request.Query["endDay"]);
                //if (right != DateTime.MaxValue)
                //{
                //    current = right;
                //}

                var query =
                    from project in context.GetProjects(x => x.Id == id).Select(p => MyClass.ToWithRecordsProject(context, p)).FirstOrNothing()
                    from workdayContext in MyClass.GetWorkdayContext(workdaySettingFolder, id)
                    let sprintToGraphModel = new SprintToGraphModel(workdayContext)
                    select new { project, sprintToGraphModel };
                var view = query.Select(q =>
                {
                    var project = q.project;
                    var sprintToGraphModel = q.sprintToGraphModel;
                    var trendChartModel = MakeTrendChartModel(this.AddIconFilePath(Request.Url,project), sprintToGraphModel);
                    var piChartModel = MakePiChartModel(trendChartModel);
                    var workDaysPV =
                        project.Sprints.Select(sprintToGraphModel.Make)
                        .Aggregate(new GraphModel(), (a, b) => new GraphModel
                        {
                            Pv = sprintToGraphModel.Merge(a.Pv, b.Pv),
                            Ev = sprintToGraphModel.Merge(a.Ev, b.Ev),
                            Ac = sprintToGraphModel.Merge(a.Ac, b.Ac),
                        }).Pv;

                    // workDaysに日付とValueの配列が含まれているので、Valueが0じゃない(非稼働日じゃない)
                    // かつ現在日付以降の日数を計算する
                    var workDays = workDaysPV.Where(x => x.Day > current).Where(x => x.Value != 0).Count();

                    var spi = piChartModel.Item1.Reverse().FirstOrDefault(x => x.Day <= current);
                    var cpi = piChartModel.Item2.Reverse().FirstOrDefault(x => x.Day <= current);
                    var totalValue = project.Sprints.SelectMany(s => s.Tasks).Where(t => t.Value.HasValue).Sum(t => t.Value.Value);
                    var progressValue =
                        project.Sprints.SelectMany(s => s.Tasks)
                        .OfType<ITaskWithRecord>()
                        .SelectMany(t => t.Records)
                        .Where(x => x.Day <= current)
                        .Sum(r => r.Value);
                    var toDayPv =
                        trendChartModel.Pv.Reverse().Where(x => x.Day <= current)
                        .Select(p => p.Value)
                        .FirstOrDefault();
                    var progress = progressValue - toDayPv;
                    var remaining = totalValue - progressValue;
                    var average = (totalValue - progressValue) / workDays;

                    var days = trendChartModel.Pv.Where(x=>left<= x.Day && x.Day <= right).Select(x=> x.Day.ToString("yyyy/MM/dd"));
                    var pvx = trendChartModel.Pv.Where(x=>left<= x.Day && x.Day <= right).Select(x => x.Value);
                    var evx = trendChartModel.Ev.Where(x=>left<= x.Day && x.Day <= right).Select(x => x.Value);
                    var acx = trendChartModel.Ac.Where(x => left <= x.Day && x.Day <= right).Select(x => x.Value);
                    var spix = piChartModel.Item1.Where(x=>left<= x.Day && x.Day <= right).Select(x => x.Value);
                    var cpix = piChartModel.Item2.Where(x => left <= x.Day && x.Day <= right).Select(x => x.Value);

                    return Response.AsJson(
                        new
                        {
                            workDays,
                            spi = spi.Value,
                            cpi = cpi.Value,
                            progress,
                            remaining,
                            average = double.IsInfinity(average) ? remaining : average,
                            days,
                            pvx,
                            evx,
                            acx,
                            spix,
                            cpix,
                        }) as object;
                });
                return
                    view.Return(() => HttpStatusCode.InternalServerError);
            };

            Get["/project/{id}/works"] = prms =>
            {
                var id = (int)prms.id;

                var query =
                    from project in context.GetProjects(x => x.Id == id).Select(p => MyClass.ToWithRecordsProject(context, p)).FirstOrNothing()
                    let records =
                        from sprint in project.Sprints
                        from task in sprint.Tasks.OfType<ITaskWithRecord>()
                        from record in task.Records
                        select record
                    let dx = project.Sprints.SelectMany(x=>new[] { x.Left, x.Right } )
                            .Where(x=>x.HasValue)
                    select new {
                        records,
                        minDay = dx.Min(x=>x.Value),
                        maxDay = dx.Max(x=>x.Value) };
                var view = query.Select(q =>
                {
                    return Response.AsJson(q) as object;
                });
                return
                    view.Return(() => HttpStatusCode.InternalServerError);
            };

            Get["/tasks/"] = _ =>
            {
                return
                    Response.AsJson(
                        context.GetTaskRecords(p => true).Select(t=>
                        {
                            (t as TaskWithRecord).Records = t.Records.Select(r =>
                                {
                                    (r as TaskRecord).Who = this.AddIconFilePath(this.Request.Url, r.Who);
                                    return r;
                                }).ToArray();
                            return t;
                        }).ToArray());
            };

            Post["/users/"] = _ =>
            {
                //var model = this.Bind<User>();
                var model = JsonConvert.DeserializeObject<User>(this.Request.Body.ToStreamString());
                context.AddUser(model);

                return Response.AsJson(new { }, HttpStatusCode.OK);
            };

            Post["/users/withIcon/"] = _ =>
            {
                try
                {

                    //var model = this.Bind<AddUserWithIcon>();
                    var model = JsonConvert.DeserializeObject<AddUserWithIcon>(this.Request.Body.ToStreamString());
                    var targetUser =
                        context.GetUser(p => p.Id == model.UserId).FirstOrDefault();
                    if (targetUser == null)
                    {
                        return HttpStatusCode.BadRequest;
                    }

                    var bytes = Convert.FromBase64String(model.Base64BytesByImage);
                    context.AddUserIcon(targetUser, bytes);

                    return Response.AsJson(new { }, HttpStatusCode.OK);
                }
                catch (Exception)
                {

                    throw;
                }

            };

            Post["/projects/"] = _ =>
            {
                var project =
                    Project.FromJson(this.Request.Body.ToStreamString())
                    .ToMaybe();

                var user =
                    from c in this.Context.CurrentUser.ToMaybe()
                    from name in c.UserName.ToMaybe()
                    from u in context.GetUser(x => x.Id == name).FirstOrNothing()
                    select u;

                project.On(p => context.AddProject(p, user.Return()));

                return Response.AsJson(new { }, project.IsSomething ? HttpStatusCode.OK : HttpStatusCode.InternalServerError);
            };

            Post["/task/comment/"] = _ =>
            {
                //var model = this.Bind<AddTaskComment>();
                var json = this.Request.Body.ToStreamString();
                var model = JsonConvert.DeserializeObject<AddTaskComment>(json);
                var project = context.GetProjectFromTask(model.TaskId);
                var permission = context.GetAccessProjectPermission(project.Id);

                if (!IsEnableUser(context, permission))
                    return HttpStatusCode.Forbidden;

                context.AddTaskComment(model.Comment, model.TaskId);

                return Response.AsJson(json, HttpStatusCode.OK);
            };
            Post["/task/record/"] = _ =>
            {
                var model = JsonConvert.DeserializeObject<AddTaskRecord>(this.Request.Body.ToStreamString());
                var project = context.GetProjectFromTask(model.TaskId);
                var permission = context.GetAccessProjectPermission(project.Id);

                if (!IsEnableUser(context, permission))
                    return HttpStatusCode.Forbidden;

                context.AddTaskRecord(model.Record, model.TaskId);

                return Response.AsJson(new { }, HttpStatusCode.OK);
            };

            Delete["/projects/"] = _ =>
            {
                var res = Response.AsJson(new { }, HttpStatusCode.OK);
                var json = this.Request.Body.ToStreamString();
                var jObj = JObject.Parse(json);
                var projectId = jObj["projectid"].Value<int>();
                var permission =
                    context.GetDeleteProjectPermission();

                if (IsEnableUser(context, permission))
                {
                    var project =
                    context.GetProjects(x => x.Id == projectId)
                        .Select(p => MyClass.ToWithRecordsProject(context, p))
                        .FirstOrNothing();

                    project.On(context.DeleteProject);
                }
                else res = HttpStatusCode.Forbidden;

                return res;
            };

            Delete["/users/"] = _ =>
            {
                var res = Response.AsJson(new { }, HttpStatusCode.OK);
                var json = this.Request.Body.ToStreamString();
                var jObj = JObject.Parse(json);
                var userId = jObj["userid"].Value<string>();
                var permission =
                    context.GetDeleteUserPermission();

                if (IsEnableUser(context, permission))
                {
                    var user =
                        context.GetUser(x => x.Id.Equals(userId)).FirstOrNothing();

                    user.On(context.DeleteUser);
                }
                else res = HttpStatusCode.Forbidden;

                return res;
            };

            Delete["/task/record/"] = _ =>
            {
                var res = Response.AsJson(new { }, HttpStatusCode.OK);
                var model = JsonConvert.DeserializeObject<DeleteTaskRecord>(this.Request.Body.ToStreamString());
                var permission =
                    context.GetDeleteTaskRecordPermission(Tuple.Create(model.TaskId, model.RecordId));

                var taskWithRecord =
                    context.GetTaskRecords(x => x.Id.Equals(model.TaskId)).FirstOrNothing();

                taskWithRecord.On(task =>
                {
                    if (!IsEnableUser(context, permission))
                    {
                        // not permitted
                        res = Response.AsJson(new { }, HttpStatusCode.Forbidden);
                        return;
                    }
                    context.DeleteTaskRecord(task, model.RecordId);
                });

                return res;
            };

            Post["/task/status/save"] = _ =>
            {
                var res = Response.AsJson(new { }, HttpStatusCode.OK);
                var model = JsonConvert.DeserializeObject<SaveTasksStatus>(this.Request.Body.ToStreamString());
                var permission = context.GetAccessProjectPermission(model.ProjectId);

                if (!IsEnableUser(context, permission))
                    return HttpStatusCode.Forbidden;

                var query =
                    from task in context.GetTaskRecords(a => true)
                    from a in model.Tasks
                    where task.Id == a.TaskId
                    where task.StatusCode != a.StatusCode
                    select new { T = task, Status = a.StatusCode };

                // todo database のNameを参照する?
                var toStatusName = Fn.New<int, string>(x => x.ToGuards()
                                                                .When(3, a => "Done")
                                                                .When(2, a => "In Progress")
                                                                .When(1, a => "Ready")
                                                                .Return("Backlog"));
                var user = context.GetUser(x => x.Id.Equals(Context.CurrentUser.UserName)).First();
                var date = DateTime.Now;
                foreach (var item in query)
                {
                    var oldStatus = toStatusName(item.T.StatusCode);
                    var newStatus = toStatusName(item.Status);
                    var message = string.Format("Changed status: {0} -> {1}", oldStatus, newStatus);
                    var comment = new TaskComment()
                    {
                        Who = user,
                        Day = date,
                        Text = message,
                    };
                    context.AddTaskComment(comment, item.T.Id);
                    item.T.StatusCode = item.Status;
                    context.UpdateTask(item.T);
                }

                return res;
            };

            Get["/project/{id}/members"] = prms =>
            {
                var id = (int)prms.id;
                var users =
                    context.GetUserOfProject(id)
                            .Select(u => this.AddIconFilePath(this.Request.Url, u))
                            .ToArray();

                return
                    Response.AsJson(users, HttpStatusCode.OK);
            };

            Post["/project/members/add"] = prms =>
            {
                var json = this.Request.Body.ToStreamString();
                var jObj = JObject.Parse(json);
                var projectId = jObj["projectId"].Value<int>();
                var userId = jObj["userId"].Value<string>();
                var user =
                    context.GetUser(x => x.Id == userId).FirstOrDefault();
                var permission =
                    context.GetAddProjectMemberPermission();

                if (user == default(IUser))
                    return HttpStatusCode.BadRequest;

                if (!IsEnableUser(context, permission))
                    return HttpStatusCode.Forbidden;

                context.AddProjectMember(user, projectId);

                return
                    Response.AsJson(new { }, HttpStatusCode.OK);
            };

            Post["/project/members/delete"] = prms =>
            {
                var json = this.Request.Body.ToStreamString();
                var jObj = JObject.Parse(json);
                var projectId = jObj["projectId"].Value<int>();
                var userId = jObj["userId"].Value<string>();
                var user =
                    context.GetUser(x => x.Id == userId).FirstOrDefault();
                var permission =
                    context.GetDeleteProjectMemberPermission();

                if (user == default(IUser))
                    return HttpStatusCode.BadRequest;

                if (!IsEnableUser(context, permission))
                    return HttpStatusCode.Forbidden;

                context.DeleteProjectMember(user, projectId);

                return
                    Response.AsJson(new { }, HttpStatusCode.OK);
            };
        }
Esempio n. 30
0
        public ProjectModule(
            IDataBaseContext context
            , ITaskToTextFactory taskToText)
            : base("/project/")
        {
            this.RequiresAuthentication();

            Get["/create"] = prms =>
            {
                return View["Views/CreateProject"];
            };

            Get["/{id}"] = prms =>
            {
                var id = prms.id;

                var project =
                    context.GetProjects(x => x.Id == id).Select(p => MyClass.ToWithRecordsProject(context, p)).FirstOrDefault();

                var permission = context.GetAccessProjectPermission(project.Id);

                if (!IsEnableUser(context, permission))
                    return HttpStatusCode.Forbidden;

                var withRecord = this.AddIconFilePath(Request.Url,project);

                var user =
                   context.GetUser(u => u.Id == Context.CurrentUser.UserName).FirstOrDefault();

                return View["Views/Project", new { Auth = user, Project = withRecord }];
            };

            Get["/{id}/board"] = prms =>
            {
                var a = "/project/" + prms.id as string;
                return
                    Response.AsRedirect(a);
            };

            Get["/{id}/edit"] = prms =>
            {
                var id = prms.id;

                var project =
                    context.GetProjects(x => x.Id == id).Select(p => MyClass.ToWithRecordsProject(context, p)).FirstOrDefault();

                var permission = context.GetAccessProjectPermission(project.Id);

                if (!IsEnableUser(context, permission))
                    return HttpStatusCode.Forbidden;

                var sprintText = taskToText.Make(project.Sprints);

                var user =
                   context.GetUser(u => u.Id == Context.CurrentUser.UserName).FirstOrDefault();

                return View["Views/ProjectEdit"
                    , new
                    {
                        Auth = user
                        , Project = project
                        , SprintText = sprintText
                    }];
            };

            // todo APIに移動すべき
            Post["/{id}/save"] = prms =>
            {
                var id = prms.id;

                var user =
                    from c in this.Context.CurrentUser.ToMaybe()
                    from name in c.UserName.ToMaybe()
                    from u in context.GetUser(x => x.Id == name).FirstOrNothing()
                    select u;

                var project =
                    context.GetProjects(x => x.Id == id).Select(p => MyClass.ToWithRecordsProject(context, p)).FirstOrDefault();

                var permission = context.GetAccessProjectPermission(project.Id);

                if (!IsEnableUser(context, permission))
                    return HttpStatusCode.Forbidden;

                // todo 競合や削除の警告

                var json = this.Request.Body.ToStreamString();
                var jObj = JObject.Parse(json);
                var sprints = taskToText.Make(jObj["edittext"].Value<string>());

                project.Sprints = sprints;
                context.AddProject(project, user.Return());

                //var user =
                //   eventAgg.GetEvent<GetUserEvent>().Get(u => u.Id == Context.CurrentUser.UserName).FirstOrDefault();
                return
                    Response.AsJson(json, HttpStatusCode.OK);
            };

            Get["/{id}/report"] = prms =>
            {
                var id = (int)prms.id;

                var permission = context.GetAccessProjectPermission(id);

                if (!IsEnableUser(context, permission))
                    return HttpStatusCode.Forbidden;

                var view =
                    from project in context.GetProjects(x => x.Id == id).Select(p => MyClass.ToWithRecordsProject(context, p)).FirstOrNothing()
                    select View["Views/ProjectReport", new { Project = project }] as object;

                return view.Return(() => Response.AsRedirect("/project/" + id));
            };

            Get["/{id}/works"] = prms =>
            {
                var id = (int)prms.id;

                var permission = context.GetAccessProjectPermission(id);

                if (!IsEnableUser(context, permission))
                    return HttpStatusCode.Forbidden;

                var view =
                    from project in context.GetProjects(x => x.Id == id).Select(p => MyClass.ToWithRecordsProject(context, p)).FirstOrNothing()
                    select View["Views/ProjectWorks", new { Project = project }] as object;

                return view.Return(() => Response.AsRedirect("/project/" + id));
            };

            Get["/{id}/kanban"] = prms =>
            {
                // projectid
                var id = (int)prms.id;

                var permission = context.GetAccessProjectPermission(id);

                if (!IsEnableUser(context, permission))
                    return HttpStatusCode.Forbidden;

                var view =
                    from project in context.GetProjects(x => x.Id == id).Select(p => MyClass.ToWithRecordsProject(context, p)).FirstOrNothing()
                    let withrecord = this.AddIconFilePath(Request.Url, project)
                let tasks =
                        from sprint in withrecord.Sprints
                        from task in sprint.Tasks
                        select task as ITaskWithRecord
                    let backlogTasks =
                        from task in tasks
                        where task.StatusCode == 0
                        select task
                    let readyTasks =
                        from task in tasks
                        where task.StatusCode == 1
                        select task
                    let inProgressTasks =
                        from task in tasks
                        where task.StatusCode == 2
                        select task
                    let doneTasks =
                        from task in tasks
                        where task.StatusCode == 3
                        select task
                    select View["Views/Kanban", new { Project = withrecord, BacklogTasks = backlogTasks.ToArray(), ReadyTasks = readyTasks.ToArray(), InProgressTasks = inProgressTasks.ToArray(), DoneTasks = doneTasks.ToArray()}] as object;

                return view.Return(() => Response.AsRedirect("/project/" + id));
            };

            Get["/{id}/member"] = prms =>
            {
                var id = (int)prms.id;

                var permission = context.GetAccessProjectPermission(id);

                if (!IsEnableUser(context, permission))
                    return HttpStatusCode.Forbidden;

                var view =
                    from project in context.GetProjects(x => x.Id == id).Select(p => MyClass.ToWithRecordsProject(context, p)).FirstOrNothing()
                    select View["Views/ProjectMember", new { Project = project }] as object;

                return view.Return(() => Response.AsRedirect("/project/" + id));
            };
        }
Esempio n. 31
0
        public LoginModule(
            IDataBaseContext context
            , IUserMapper mapper)
        {
            Get["/"] = prms =>
            {
                // ログイン情報がある場合ホーム画面にリダイレクト
                var query =
                    from user in this.Context.CurrentUser.ToMaybe()
                    where context.GetUser(x => user.UserName.Equals(x.Id)).Any()
                    select user;

                if (query.IsSomething)
                    return Response.AsRedirect("/home/");

                // ログイン情報がないor不正な場合はログイン画面へ
                return View["Views/Login"];
            };

            Post["/"] = prms =>
            {
                var id = (string)this.Request.Form["userId"];
                var pass = (string)this.Request.Form["password"];
                var redirect = (string)this.Request.Query["returnUrl"] ?? "/home/";

                var findId =
                    (from u in context.GetUser(_ => true)
                     where u.Id == id
                     where u.Password == pass
                     select (mapper as UserValidator).ToGuid(u)).FirstOrNothing();

                if (findId.IsNothing)
                {
                    return Response.AsRedirect("/");
                }

                return
                    this.LoginAndRedirect(findId.Return(), DateTime.Now.AddDays(7), redirect);
            };

            Get["/logout"] = prms =>
            {
                return this.LogoutAndRedirect("/");
            };

            // todo apiへ
            Get["/login/{id}/pass/{pass}"] = prms =>
            {
                var id = (string)prms.id;
                var pass = (string)prms.pass;

                var findId =
                    (from u in context.GetUser(_ => true)
                     where u.Id == id
                     where u.Password == pass
                     select (mapper as UserValidator).ToGuid(u)).FirstOrNothing();

                if (findId.IsNothing)
                {
                    return Response.AsRedirect("/");
                }

                return
                    this.Login(findId.Return(), DateTime.Now.AddDays(7));
            };
        }
Esempio n. 32
0
        private bool IsEnableUser(IDataBaseContext context, IPermission permission)
        {
            var query =
                from current in this.Context.CurrentUser.ToMaybe()
                from name in current.UserName.ToMaybe()
                from user in
                    (from u in context.GetUser(x => x.Id.Equals(name))
                     select u).FirstOrNothing()
                where permission.IsPermittedUser(user)
                select true;

            return
                query.IsSomething;
        }
Esempio n. 33
0
        public LoginApiModule(IDataBaseContext context)
            : base("/api/")
        {
            Post["/login/"] = _ =>
            {
                var model = this.Bind<User>();

                var user =
                    context.GetUser(u => u.Id == model.Id && u.Password == model.Password)
                    .FirstOrDefault();

                return
                    Response.AsJson(this.AddIconFilePath(Request.Url, user), HttpStatusCode.OK);
            };
        }
Esempio n. 34
0
 public GetUsersService(IDataBaseContext context, IDistributedCache distributedCache)
 {
     _context          = context;
     _distributedCache = distributedCache;
 }
 public GetMenuItemService(IDataBaseContext context)
 {
     _context = context;
 }
Esempio n. 36
0
 public NewGetChatroomDetailByUsernameService(IDataBaseContext context)
 {
     _context = context;
 }
Esempio n. 37
0
 public GetCategoriesService(IDataBaseContext context)
 {
     _context = context;
 }
Esempio n. 38
0
 public GetSearchCategoryService(IDataBaseContext context)
 {
     _context = context;
 }
 public void SetUp()
 {
     this.dataBaseContext = new FakeDbContext();
 }
 public GetChatroomGuidByJoinGuidService(IDataBaseContext context)
 {
     _context = context;
 }
Esempio n. 41
0
 public GetUserIdByPVGuidService(IDataBaseContext context)
 {
     _context = context;
 }
 /// <summary>
 /// 构造
 /// </summary>
 /// <param name="context"></param>
 /// <param name="Adapter"></param>
 public DataBaseHandlerEx(IDataBaseContext context, IDataBaseAdapter Adapter)
     : base(context, Adapter)
 {
 }
Esempio n. 43
0
 /// <summary>
 /// 获取IDataBaseHandler
 /// </summary>
 /// <param name="Context"></param>
 /// <returns></returns>
 public override IDataBaseHandler GetDbHandler(IDataBaseContext Context)
 {
     return(new DataBaseHandler(Context, this));
 }
 public GetProductForSiteService(IDataBaseContext context, IMemoryCache memoryCache)
 {
     _context     = context;
     _memoryCache = memoryCache;
 }
Esempio n. 45
0
 public MessagesFacad(IDataBaseContext context)
 {
     _context = context;
 }
 public MembershipService(IDataBaseContext dbContext)
 {
    _dbContext = dbContext;
 }
Esempio n. 47
0
 public SellerService(IDataBaseContext context)
 {
     _context = context;
 }