Пример #1
0
        public async Task <IHttpActionResult> AddLinkedProject(Guid linkedProjectId, Guid workProjectId)
        {
            WorkProject workProject = await db.WorkProjects.Include("Project").FirstOrDefaultAsync(item => item.ProjectId == workProjectId);

            if (workProject == null)
            {
                return(NotFound());
            }

            if (ProjectHelper.HasUpdateAccess(workProject.Project) == false)
            {
                throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.Forbidden, "No Access"));
            }

            Project project = await db.Projects.FirstOrDefaultAsync(item => item.Id == linkedProjectId);

            if (project == null)
            {
                return(NotFound());
            }
            if (ProjectHelper.HasUpdateAccess(project) == false)
            {
                throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.Forbidden, "No Access"));
            }

            var fta = db.FTAProjects.FirstOrDefault(item => item.ProjectId == linkedProjectId);

            if (fta != null)
            {
                if (workProject.FTAProjects.FirstOrDefault(item => item.ProjectId == linkedProjectId) == null)
                {
                    workProject.FTAProjects.Add(fta);
                }
            }
            else
            {
                var fmea = db.FMEAProjects.FirstOrDefault(item => item.ProjectId == linkedProjectId);
                if (fmea != null)
                {
                    if (workProject.FMEAProjects.FirstOrDefault(item => item.ProjectId == linkedProjectId) == null)
                    {
                        workProject.FMEAProjects.Add(fmea);
                    }
                }
            }

            db.SaveChanges();

            var model = new WorkProjectViewModel(workProject, db);
            ProjectFilesController pfc = new ProjectFilesController();
            var obj = (OkNegotiatedContentResult <ProjectFolderViewModel>)pfc.GetProjectFiles(workProjectId, "Root", System.IO.SearchOption.AllDirectories).Result;

            model.ProjectFiles = obj.Content;
            return(Ok(model));
        }
Пример #2
0
        public ShqDictionary AddShqDictionary(string groupName, string dictName, string dictValue)
        {
            var row = db.ShqDictionary.FirstOrDefault(item => item.GroupName == groupName && item.DictName == dictName && item.DictValue == dictValue);

            if (row != null)
            {
                row.DictValue = dictValue;
            }
            else
            {
                row = db.ShqDictionary.Add(new ShqDictionary()
                {
                    GroupName = groupName, DictName = dictName, DictValue = dictValue
                });
            }

            db.SaveChanges();

            return(row);
        }
Пример #3
0
        public async Task <IHttpActionResult> AddProject(ProjectRequestViewModel projectView)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            Project pro = await db.Projects.FindAsync(projectView.Id);

            if (pro != null)
            {
                return(Ok("已存在"));
            }

            pro = await db.Projects.FirstOrDefaultAsync(item => item.ProjectName == projectView.Name);

            if (pro != null)
            {
                return(Ok("已存在"));
            }

            Project project = projectView.ToProject();

            project.CreatedById      = db.ShqUsers.Where(u => u.IdentityUser.UserName == HttpContext.Current.User.Identity.Name).FirstOrDefault().IdentityUserId;
            project.LastModifiedById = project.CreatedById;

            db.Projects.Add(project);

            if (project.Type == "FTAProject")
            {
                db.FTAProjects.Add(new FTAProject()
                {
                    Id = Guid.NewGuid(), ProjectId = projectView.Id, CreatedById = project.CreatedById, LastModifiedById = project.LastModifiedById
                });
            }

            if (project.Type == "FMEAProject")
            {
                db.FMEAProjects.Add(new FMEAProject()
                {
                    Id = Guid.NewGuid(), ProjectId = projectView.Id, CreatedById = project.CreatedById, LastModifiedById = project.LastModifiedById
                });
            }

            if (project.Type == "WorkProject")
            {
                var wp = db.WorkProjects.Add(new WorkProject()
                {
                    Id = Guid.NewGuid(), ProjectId = projectView.Id, Level = projectView.Level, CreatedById = project.CreatedById, LastModifiedById = project.LastModifiedById, WorkProjectTemplateId = ShqConstants.DefaultWorkProjectTemplateId
                });
                db.SaveChanges();
                try
                {
                    ProjectFilesController pfc = new ProjectFilesController();
                    await pfc.SyncProjectFiles(wp.ProjectId);
                }
                catch (Exception)
                {
                }
            }

            int i = 0;

            if (projectView.UsersPrivileges.Count > 0)
            {
                i++;
                foreach (var item in projectView.UsersPrivileges)
                {
                    var newAccess = new ProjectShqUsers()
                    {
                        ProjectId        = project.Id,
                        ShqUserId        = db.ShqUsers.Where(u => u.EmailAddress == item.EmailAddress).FirstOrDefault().IdentityUserId,
                        Privilege        = item.Privilege,
                        CreatedById      = project.CreatedById,
                        LastModifiedById = project.CreatedById
                    };
                    newAccess.LastModifiedById = newAccess.CreatedById;
                    db.ProjectShqUsers.Add(newAccess);
                }
            }

            await db.SaveChangesAsync();

            ProjectViewModel result = new ProjectViewModel(project, db);

            result.Description = i.ToString();
            result.Privilege   = ShqConstants.AllowProjectUpdate;

            (new AuditsController()).AddAuditEntry("api/Projects/Add", JsonConvert.SerializeObject(result));
            return(Ok(result));
        }
Пример #4
0
        public HttpResponseMessage Update(string explorerInfo)
        {
            ExplorerInfoViewModel einfo = JsonConvert.DeserializeObject <ExplorerInfoViewModel>(explorerInfo);
            Guid   projectId;
            string folder;

            if (Guid.TryParse(einfo.ProjectId, out projectId) == true)
            {
                folder = ShqConstants.ProjectRootFolder + "\\" + einfo.ParentPath;
            }
            else
            {
                folder = ShqConstants.TemplateRootFolder + "\\" + einfo.ParentPath;
            }
            folder = new DirectoryInfo(Path.Combine(folder, "1b2cd8ab-6d6c-4a05-931b-e40607bd8b19")).Parent.FullName;//to workaround a issue the if path end with \ will fail

            string name    = einfo.Name + "." + einfo.Id.ToString();
            string oldName = einfo.OldName + "." + einfo.Id.ToString();

            switch (einfo.cmd)
            {
            case "createFolder":
            {
                var     fileSystemDriver = new FileSystemDriver();
                IDriver driver           = fileSystemDriver;
                var     root             = new Root(new DirectoryInfo(folder))
                {
                    IsReadOnly        = false,
                    Alias             = "Root",
                    MaxUploadSizeInMb = 500,
                    LockedFolders     = new List <string>()
                };
                fileSystemDriver.AddRoot(root);
                string target = root.VolumeId + Helper.EncodePath(new DirectoryInfo(folder).Name);

                try
                {
                    driver.MakeDir(target, name);
                }
                finally
                {
                    if (Directory.Exists(Path.Combine(folder, name)))
                    {
                        db.ProjectFiles.Add(new ProjectFile
                            {
                                Id               = einfo.Id,
                                Name             = einfo.Name,
                                Level            = einfo.Level,
                                IsFolder         = true,
                                Path             = Path.Combine(folder, name),
                                CreatedById      = db.ShqUsers.Where(u => u.IdentityUser.UserName == HttpContext.Current.User.Identity.Name).FirstOrDefault().IdentityUserId,
                                LastModifiedById = db.ShqUsers.Where(u => u.IdentityUser.UserName == HttpContext.Current.User.Identity.Name).FirstOrDefault().IdentityUserId
                            });
                    }
                }

                break;
            }

            case "delete":
            {
                var     fileSystemDriver = new FileSystemDriver();
                IDriver driver           = fileSystemDriver;
                folder = Path.Combine(folder, name);
                var root = new Root(new DirectoryInfo(folder))
                {
                    IsReadOnly        = false,
                    Alias             = "Root",
                    MaxUploadSizeInMb = 500,
                    LockedFolders     = new List <string>()
                };
                fileSystemDriver.AddRoot(root);
                string target = root.VolumeId + Helper.EncodePath(new DirectoryInfo(folder).Name);

                driver.Remove(new string[] { target });
                var f = db.ProjectFiles.FirstOrDefault(item => item.Id == einfo.Id);
                if (f != null)
                {
                    f.Status           = 1;
                    f.LastModifiedById = db.ShqUsers.Where(u => u.IdentityUser.UserName == HttpContext.Current.User.Identity.Name).FirstOrDefault().IdentityUserId;
                    f.LastModfiedTime  = DateTime.Now;
                }
                break;
            }

            case "rename":
            {
                var     fileSystemDriver = new FileSystemDriver();
                IDriver driver           = fileSystemDriver;
                var     root             = new Root(new DirectoryInfo(folder))
                {
                    IsReadOnly        = false,
                    Alias             = "Root",
                    MaxUploadSizeInMb = 500,
                    LockedFolders     = new List <string>()
                };
                fileSystemDriver.AddRoot(root);
                string target = root.VolumeId + Helper.EncodePath(@"\" + oldName);

                driver.Rename(target, name);
                var f = db.ProjectFiles.FirstOrDefault(item => item.Id == einfo.Id);
                if (f != null)
                {
                    f.Name             = einfo.Name;
                    f.Path             = Path.Combine(Directory.GetParent(folder).FullName, name);
                    f.LastModifiedById = db.ShqUsers.Where(u => u.IdentityUser.UserName == HttpContext.Current.User.Identity.Name).FirstOrDefault().IdentityUserId;
                    f.LastModfiedTime  = DateTime.Now;
                }
                break;
            }

            case "uploadFile":    //https://forums.asp.net/t/2104884.aspx?Uploading+a+file+using+webapi+C+
            {
                var fileSystemDriver = new FileSystemDriver();
                var root             = new Root(new DirectoryInfo(folder))
                {
                    IsReadOnly        = false,
                    Alias             = "Root",
                    MaxUploadSizeInMb = 500,
                    LockedFolders     = new List <string>()
                };
                fileSystemDriver.AddRoot(root);
                string target = root.VolumeId + Helper.EncodePath(new DirectoryInfo(folder).Name);

                var    wrapper  = new HttpRequestWrapper(HttpContext.Current.Request);
                string fileName = wrapper.Files[0].FileName + "." + einfo.Id;
                try
                {
                    fileSystemDriver.Upload(target, wrapper.Files[0], fileName);
                }
                finally
                {
                    if (File.Exists(Path.Combine(folder, fileName)))
                    {
                        db.ProjectFiles.Add(new ProjectFile
                            {
                                Id               = einfo.Id,
                                Name             = wrapper.Files[0].FileName,
                                Level            = einfo.Level,
                                IsFolder         = false,
                                Path             = Path.Combine(folder, fileName),
                                CreatedById      = db.ShqUsers.Where(u => u.IdentityUser.UserName == HttpContext.Current.User.Identity.Name).FirstOrDefault().IdentityUserId,
                                LastModifiedById = db.ShqUsers.Where(u => u.IdentityUser.UserName == HttpContext.Current.User.Identity.Name).FirstOrDefault().IdentityUserId
                            });
                    }
                }

                break;
            }

            case "dowloadFile":
            {
                folder = Path.Combine(folder, einfo.Name);
                if (File.Exists(folder) == false)
                {
                    return(new HttpResponseMessage(HttpStatusCode.NotFound));
                }

                //converting Pdf file into bytes array
                var dataBytes = System.IO.File.ReadAllBytes(folder);
                //adding bytes to memory stream
                var stream = new MemoryStream(dataBytes);

                var result = new HttpResponseMessage(HttpStatusCode.OK)
                {
                    Content = new ByteArrayContent(stream.ToArray())
                };
                result.Content.Headers.ContentDisposition =
                    new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment")
                {
                    FileName = einfo.Name
                };
                result.Content.Headers.ContentType =
                    new MediaTypeHeaderValue("application/octet-stream");

                return(result);
            }
            }

            db.SaveChanges();

            return(new HttpResponseMessage(HttpStatusCode.OK));
        }
        public HttpResponseMessage Update(ExplorerInfoViewModel einfo)
        {
            WorkProject wp = null;
            string      folder;
            var         pro = db.Projects.FirstOrDefault(item => item.Id == einfo.ProjectId);
            Guid?       workProjectId;
            Guid        worktemplateid = Guid.Empty;

            if (pro != null)
            {
                if (ProjectHelper.HasReadAccess(pro) == false)
                {
                    throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.Forbidden, "No Access"));
                }

                if (einfo.cmd != "dowloadFile" && ProjectHelper.HasUpdateAccess(pro) == false)
                {
                    throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.Forbidden, "No Access"));
                }

                folder          = ShqConstants.ProjectRootFolder + "\\" + einfo.ProjectId + "\\" + einfo.TartgetPath;
                wp              = db.WorkProjects.FirstOrDefault(item => item.ProjectId == einfo.ProjectId);
                workProjectId   = wp.Id;
                worktemplateid  = wp.WorkProjectTemplateId;
                einfo.Privilege = 1;
            }
            else if (db.WorkProjectTemplates.FirstOrDefault(item => item.Id == einfo.ProjectId) != null)
            {
                if (HttpContext.Current.User.IsInRole(ShqConstants.AdministratorRole) == false)
                {
                    throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.Forbidden, "No Access"));
                }

                workProjectId   = null;
                worktemplateid  = einfo.ProjectId;
                einfo.Privilege = 0;
                folder          = ShqConstants.TemplateRootFolder + "\\" + worktemplateid + "\\" + einfo.TartgetPath;
            }
            else
            {
                throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.Forbidden, "projectId is not found"));
            }

            folder = new DirectoryInfo(Path.Combine(folder, "1b2cd8ab-6d6c-4a05-931b-e40607bd8b19")).Parent.FullName;//to workaround a issue the if path end with \ will fail

            if (CheckIfParentExistInDb(folder) == false)
            {
                throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.Forbidden, "The parent folder is not found in the db"));
            }

            string name    = einfo.Name + "." + einfo.Id.ToString();
            string oldName = einfo.OldName + "." + einfo.Id.ToString();

            switch (einfo.cmd)
            {
            case "createFolder":
            {
                if (string.IsNullOrEmpty(einfo.Name) == true)
                {
                    break;
                }

                var     fileSystemDriver = new FileSystemDriver();
                IDriver driver           = fileSystemDriver;
                var     root             = new Root(new DirectoryInfo(folder))
                {
                    IsReadOnly        = false,
                    Alias             = "Root",
                    MaxUploadSizeInMb = 500,
                    LockedFolders     = new List <string>()
                };
                fileSystemDriver.AddRoot(root);

                var dbFile = db.ProjectFiles.FirstOrDefault(item => item.WorkProjectId == workProjectId &&
                                                            item.WorkProjectTemplateId == worktemplateid &&
                                                            item.Name == einfo.Name &&
                                                            item.Path == folder + "\\" + einfo.Name + "." + item.Id);

                if (dbFile != null)
                {
                    dbFile.Status           = (int)ShqConstants.FileStatus.Ready;
                    dbFile.LastModifiedById = db.ShqUsers.Where(u => u.IdentityUser.UserName == HttpContext.Current.User.Identity.Name).FirstOrDefault().IdentityUserId;
                    dbFile.LastModfiedTime  = DateTime.Now;
                }
                else
                {
                    dbFile = db.ProjectFiles.Add(new ProjectFile
                        {
                            FileId                = Guid.NewGuid(),
                            Name                  = einfo.Name,
                            Level                 = 0,
                            IsFolder              = true,
                            Path                  = Path.Combine(folder, einfo.Name),
                            WorkProjectId         = workProjectId,
                            WorkProjectTemplateId = worktemplateid,
                            Privilege             = einfo.Privilege,
                            CreatedById           = db.ShqUsers.Where(u => u.IdentityUser.UserName == HttpContext.Current.User.Identity.Name).FirstOrDefault().IdentityUserId,
                            LastModifiedById      = db.ShqUsers.Where(u => u.IdentityUser.UserName == HttpContext.Current.User.Identity.Name).FirstOrDefault().IdentityUserId
                        });

                    if (wp != null)
                    {
                        wp.ProjectFiles.Add(dbFile);
                    }

                    db.SaveChanges();
                }

                name = einfo.Name + "." + dbFile.Id.ToString();
                string target = root.VolumeId + Helper.EncodePath(new DirectoryInfo(folder).Name);

                try
                {
                    driver.MakeDir(target, name);
                }
                finally
                {
                    if (Directory.Exists(Path.Combine(folder, name)))
                    {
                        dbFile.Status = (int)ShqConstants.FileStatus.Ready;
                        dbFile.Path   = Path.Combine(folder, name);
                    }
                    else
                    {
                        dbFile.Status           = (int)ShqConstants.FileStatus.Deleted;
                        dbFile.LastModifiedById = db.ShqUsers.Where(u => u.IdentityUser.UserName == HttpContext.Current.User.Identity.Name).FirstOrDefault().IdentityUserId;
                        dbFile.LastModfiedTime  = DateTime.Now;
                    }
                }
            }

            break;

            case "delete":
            {
                var     fileSystemDriver = new FileSystemDriver();
                IDriver driver           = fileSystemDriver;
                //folder = Path.Combine(folder, name);
                var root = new Root(new DirectoryInfo(folder).Parent)
                {
                    IsReadOnly        = false,
                    Alias             = "Root",
                    MaxUploadSizeInMb = 500,
                    LockedFolders     = new List <string>()
                };
                fileSystemDriver.AddRoot(root);
                string target = root.VolumeId + Helper.EncodePath(@"\" + new DirectoryInfo(folder).Name);

                driver.Remove(new string[] { target });
                if (Directory.Exists(folder) == false && File.Exists(folder) == false)
                {
                    //var f = db.ProjectFiles.FirstOrDefault(item => item.Id == einfo.Id
                    //&& item.WorkProjectId == projectId
                    //&& item.WorkProjectTemplateId == worktemplateid);
                    //if (f != null)
                    //{
                    //    f.Status = 1;
                    //    f.LastModifiedById = db.ShqUsers.Where(u => u.IdentityUser.UserName == HttpContext.Current.User.Identity.Name).FirstOrDefault().IdentityUserId;
                    //    f.LastModfiedTime = DateTime.Now;
                    //}

                    string userId = db.ShqUsers.Where(u => u.IdentityUser.UserName == HttpContext.Current.User.Identity.Name).FirstOrDefault().IdentityUserId;
                    var    fs     = db.ProjectFiles.Where(item => item.Path.Contains(folder) == true &&
                                                          item.WorkProjectId == workProjectId &&
                                                          item.WorkProjectTemplateId == worktemplateid);
                    foreach (var f in fs)
                    {
                        f.Status           = 1;
                        f.LastModifiedById = userId;
                        f.LastModfiedTime  = DateTime.Now;
                    }
                }

                break;
            }

            case "rename":
            {
                var           fileSystemDriver = new FileSystemDriver();
                IDriver       driver           = fileSystemDriver;
                DirectoryInfo rootPath         = new DirectoryInfo(folder).Parent;
                var           root             = new Root(rootPath)
                {
                    IsReadOnly        = false,
                    Alias             = "Root",
                    MaxUploadSizeInMb = 500,
                    LockedFolders     = new List <string>()
                };
                fileSystemDriver.AddRoot(root);
                string target = root.VolumeId + Helper.EncodePath(@"\" + oldName);

                var dbFile = db.ProjectFiles.FirstOrDefault(item => item.WorkProjectId == workProjectId &&
                                                            item.WorkProjectTemplateId == worktemplateid &&
                                                            item.Name == einfo.Name &&
                                                            item.Path == rootPath.FullName + "\\" + einfo.Name + "." + item.Id &&
                                                            item.Status != (int)ShqConstants.FileStatus.Deleted);
                if (dbFile != null && (File.Exists(dbFile.Path) || Directory.Exists(dbFile.Path)))
                {
                    return(new HttpResponseMessage(HttpStatusCode.Conflict));
                }

                driver.Rename(target, name);
                string oldPath = Path.Combine(Directory.GetParent(folder).FullName, oldName);
                string newPath = Path.Combine(Directory.GetParent(folder).FullName, name);

                var userId  = db.ShqUsers.Where(u => u.IdentityUser.UserName == HttpContext.Current.User.Identity.Name).FirstOrDefault().IdentityUserId;
                var wpFiles = db.ProjectFiles.Where(item => item.WorkProjectId == workProjectId &&
                                                    item.WorkProjectTemplateId == worktemplateid &&
                                                    item.Path.Contains(oldPath) == true);
                if (wpFiles != null)
                {
                    foreach (var f in wpFiles)
                    {
                        if (f.Id == einfo.Id)
                        {
                            f.Name = einfo.Name;
                        }
                        f.Path             = f.Path.Replace(oldPath, newPath);
                        f.LastModifiedById = userId;
                        f.LastModfiedTime  = DateTime.Now;
                    }
                }
                break;
            }

            case "uploadFile":    //https://forums.asp.net/t/2104884.aspx?Uploading+a+file+using+webapi+C+
                //https://shazwazza.com/post/uploading-files-and-json-data-in-the-same-request-with-angular-js/
            {
                var fileSystemDriver = new FileSystemDriver();
                var root             = new Root(new DirectoryInfo(folder))
                {
                    IsReadOnly        = false,
                    Alias             = "Root",
                    MaxUploadSizeInMb = 500,
                    LockedFolders     = new List <string>()
                };
                fileSystemDriver.AddRoot(root);

                var dbFile = db.ProjectFiles.FirstOrDefault(item => item.WorkProjectId == workProjectId &&
                                                            item.WorkProjectTemplateId == worktemplateid &&
                                                            item.Name == einfo.Name &&
                                                            item.Path == folder + "\\" + einfo.Name + "." + item.Id);

                if (dbFile == null)
                {
                    dbFile = db.ProjectFiles.Add(new ProjectFile
                        {
                            FileId                = Guid.NewGuid(),
                            Name                  = einfo.Name,
                            Level                 = einfo.Level,
                            IsFolder              = false,
                            Path                  = Path.Combine(folder, name),
                            WorkProjectId         = workProjectId,
                            WorkProjectTemplateId = worktemplateid,
                            Privilege             = einfo.Privilege,
                            CreatedById           = db.ShqUsers.Where(u => u.IdentityUser.UserName == HttpContext.Current.User.Identity.Name).FirstOrDefault().IdentityUserId,
                            LastModifiedById      = db.ShqUsers.Where(u => u.IdentityUser.UserName == HttpContext.Current.User.Identity.Name).FirstOrDefault().IdentityUserId
                        });

                    if (wp != null)
                    {
                        wp.ProjectFiles.Add(dbFile);
                    }

                    db.SaveChanges();
                }
                else
                {
                    dbFile.Status           = (int)ShqConstants.FileStatus.Ready;
                    dbFile.LastModifiedById = db.ShqUsers.Where(u => u.IdentityUser.UserName == HttpContext.Current.User.Identity.Name).FirstOrDefault().IdentityUserId;
                    dbFile.LastModfiedTime  = DateTime.Now;
                }

                name = einfo.Name + "." + dbFile.Id.ToString();
                string target = root.VolumeId + Helper.EncodePath(new DirectoryInfo(folder).Name);

                try
                {
                    byte[] bytes = Convert.FromBase64String(einfo.FileContent);
                    fileSystemDriver.Upload(target, name, bytes);
                }
                finally
                {
                    if (File.Exists(Path.Combine(folder, name)))
                    {
                        if (File.Exists(Path.Combine(folder, name)))
                        {
                            dbFile.Path = Path.Combine(folder, name);
                        }
                        else
                        {
                            db.ProjectFiles.Remove(dbFile);
                        }
                    }
                }

                break;
            }

            case "dowloadFile":
            {
                if (File.Exists(folder) == false)
                {
                    return(new HttpResponseMessage(HttpStatusCode.NotFound));
                }

                //converting Pdf file into bytes array
                var dataBytes = System.IO.File.ReadAllBytes(folder);
                //adding bytes to memory stream
                var stream = new MemoryStream(dataBytes);

                var result = new HttpResponseMessage(HttpStatusCode.OK)
                {
                    Content = new ByteArrayContent(stream.ToArray())
                };
                result.Content.Headers.ContentDisposition =
                    new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment")
                {
                    FileName = einfo.Name
                };
                result.Content.Headers.ContentType =
                    new MediaTypeHeaderValue("application/octet-stream");

                return(result);
            }

            case "newLevel":
            {
                var f = db.ProjectFiles.FirstOrDefault(item => item.Id == einfo.Id && item.WorkProjectId == workProjectId && item.WorkProjectTemplateId == worktemplateid);
                if (f != null)
                {
                    f.Level            = einfo.Level;
                    f.LastModifiedById = db.ShqUsers.Where(u => u.IdentityUser.UserName == HttpContext.Current.User.Identity.Name).FirstOrDefault().IdentityUserId;
                    f.LastModfiedTime  = DateTime.Now;
                }

                break;
            }
            }

            db.SaveChanges();

            return(new HttpResponseMessage(HttpStatusCode.OK));
        }
        public async Task <IHttpActionResult> AnalyzeFTAProjectTree(FTATreeRequestViewModel tree)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            var docs = db.FTAProjects.Include("Project").Where(item => item.ProjectId == tree.ProjectId).FirstOrDefault();

            if (docs == null)
            {
                return(NotFound());
            }

            if (ProjectHelper.HasUpdateAccess(docs.Project) == false)
            {
                throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.Forbidden, "No Access"));
            }

            ShqUser shqUser = await db.ShqUsers.Where(item => item.IdentityUser.UserName == HttpContext.Current.User.Identity.Name).Include("IdentityUser").FirstOrDefaultAsync();

            var tr = docs.FTATrees.Where(item => item.Id == tree.Id).FirstOrDefault();

            if (tr == null)
            {
                FTATree ftaTree = new FTATree()
                {
                    Id = tree.Id, FTAProjectId = docs.Id, AnalysisStatus = 1, FTAProject = docs, Content = tree.Content, CreatedById = shqUser.IdentityUserId, CreatedTime = DateTime.Now, LastModifiedById = shqUser.IdentityUserId, LastModfiedTime = DateTime.Now
                };
                docs.FTATrees.Add(ftaTree);
                db.SaveChanges();

                var     jsonFTATree = JsonConvert.DeserializeObject <JsonFTATree>(tree.Content);
                dynamic jsonSource  = JObject.Parse(tree.Content);

                Analyze(docs, jsonFTATree);
                var result = new FTATreeViewModel(ftaTree, db);

                string exeString = RunPythonAnalysis(docs.Id);
                if (exeString == null)
                {
                    result.AnalysisStatus = "Ok";

                    foreach (var jsNode in jsonSource.nodes)
                    {
                        string jsNodeId = jsNode.id;

                        using (var con = new MySqlConnection(ConfigurationManager.ConnectionStrings["ShqContext"].ConnectionString))
                        {
                            con.Open();
                            var cmd = con.CreateCommand();


                            //var node = db.FTANodes.FirstOrDefault(item => item.FTAProjectId == docs.Id && item.EventId == jsNodeId);
                            //if (node != null)
                            //{
                            //    jsNode.smallFailureRateQ = node.SmallFailureRateQ;
                            //}

                            cmd.CommandText = string.Format("select SmallFailureRateQ,Color from shqdb.ftanodes where FTAProjectId = '{0}' and EventId = '{1}' limit 1;", docs.Id, jsNodeId);
                            using (var rdr = cmd.ExecuteReader(CommandBehavior.SequentialAccess | CommandBehavior.CloseConnection))
                            {
                                while (rdr.Read())
                                {
                                    jsNode.smallFailureRateQ = rdr.GetDouble(0);
                                    jsNode.color             = rdr.GetString(1);
                                }
                            }
                        }
                    }

                    foreach (var jsProperty in jsonSource.attributes)
                    {
                        string jName = jsProperty.name;
                        //var node = db.FTANodeProperties.FirstOrDefault(item => item.FTAProjectId == docs.Id && item.Name == jName);
                        //if (node != null)
                        //{
                        //    jsProperty.failureRateQ = node.FailureRateQ;
                        //    jsProperty.invalidRate = node.InvalidRate;
                        //    jsProperty.failureTime = node.FailureTime;
                        //    jsProperty.dCrf = node.DCrf;
                        //    jsProperty.dClf = node.DClf;
                        //}

                        using (var con = new MySqlConnection(ConfigurationManager.ConnectionStrings["ShqContext"].ConnectionString))
                        {
                            con.Open();
                            var cmd = con.CreateCommand();
                            cmd.CommandText = string.Format("select SmallFailureRateQ,failureRateQ,invalidRate,failureTime,dCrf,dClf from ftanodes as nodes inner join ftanodeproperties as ps on nodes.NodeName = ps.Name where ps.FTAProjectId = '{0}' and ps.Name = '{1}' limit 1;", docs.Id, jName);
                            using (var rdr = cmd.ExecuteReader(CommandBehavior.SequentialAccess | CommandBehavior.CloseConnection))
                            {
                                while (rdr.Read())
                                {
                                    jsProperty.smallFailureRateQ = rdr.GetDouble(0);
                                    jsProperty.failureRateQ      = rdr.GetDouble(1);
                                    jsProperty.invalidRate       = rdr.GetDouble(2);
                                    jsProperty.failureTime       = rdr.GetDouble(3);
                                    jsProperty.dCrf = rdr.GetDouble(4);
                                    jsProperty.dClf = rdr.GetDouble(5);
                                }
                            }
                        }
                    }

                    result.Content  = JsonConvert.SerializeObject(jsonSource);
                    ftaTree.Content = result.Content;
                    db.SaveChanges();

                    //// remove C:\Users\phimath\Source\Repos\sq_analysis\2.service\packages\MySqlConnector.0.47.1\lib\net45\MySqlConnector.dll
                    //using (var con = new MySqlConnection(ConfigurationManager.ConnectionStrings["ShqContext"].ConnectionString))
                    //{
                    //    con.Open();
                    //    var cmd = con.CreateCommand();
                    //    cmd.CommandText = "SELECT ftanodes.eventid as nodeid,ftanodeeventreportsreview.FTAEventTypeId,ftanodeeventreportsreview.FTAFailureTypeId, ftanodeeventreportsreview.EventValue,ftanodeeventreportsreview.EventValueType  FROM ftanodeeventreportsreview inner join ftanodes	on ftanodes.id = ftanodeeventreportsreview.FTANodeId";
                    //    using (var rdr = cmd.ExecuteReader(CommandBehavior.SequentialAccess | CommandBehavior.CloseConnection))
                    //    {
                    //        result.JsonNodeEvents = new List<JsonNodeEvent>();

                    //        while (rdr.Read())
                    //        {
                    //            JsonNodeEvent e = new JsonNodeEvent();
                    //            e.NodeId = rdr.GetString(0);
                    //            e.EventId = rdr.GetInt32(1);
                    //            e.FalureId = rdr.GetInt32(2);
                    //            e.EventValue = rdr.GetDouble(3);
                    //            e.EventValueType = rdr.GetInt32(4);
                    //            result.JsonNodeEvents.Add(e);
                    //        }
                    //    }
                    //}

                    //using (var con = new MySqlConnection(ConfigurationManager.ConnectionStrings["ShqContext"].ConnectionString))
                    //{
                    //    con.Open();
                    //    var cmd = con.CreateCommand();
                    //    cmd.CommandText = string.Format("SELECT FTAEventTypeId,FTAFailureTypeId,FailureRateQ,InvalidRate FROM shqdb.ftaeventreports where ftaprojectid = '{0}'", docs.Id);
                    //    using (var rdr = cmd.ExecuteReader(CommandBehavior.SequentialAccess | CommandBehavior.CloseConnection))
                    //    {
                    //        result.JsonTreeEvents = new List<JsonTreeEvent>();

                    //        while (rdr.Read())
                    //        {
                    //            JsonTreeEvent e = new JsonTreeEvent();
                    //            e.EventId = rdr.GetInt32(0);
                    //            e.FalureId = rdr.GetInt32(1);
                    //            e.FailureRateQ = rdr.GetDouble(2);
                    //            e.InvalidRate = rdr.GetInt32(3);
                    //            result.JsonTreeEvents.Add(e);
                    //        }
                    //    }
                    //}
                }
                else
                {
                    result.AnalysisStatus = "Error:" + exeString;
                }

                (new AuditsController()).AddAuditEntry("api/FTAProjects/AnalyzeTree", JsonConvert.SerializeObject(new ProjectViewModel(docs.Project, db)));
                return(Ok(result));
            }
            else
            {
                return(Conflict());
            }
        }