Esempio n. 1
0
        public void CreatesVersionedPathForSemanticVersion()
        {
            var sut = new PathProvider("testapp");

            var expected = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "testapp", "app-1.2.3-beta");
            Assert.AreEqual(expected, sut.GetAppPath(new SemanticVersion(1, 2, 3, "beta")));
        }
Esempio n. 2
0
        public void CacheFolderDefaultsUnderAppBasePath()
        {
            var sut = new PathProvider("testapp");

            var expected = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "testapp", "packages");
            Assert.AreEqual(expected, sut.NuGetCachePath);
        }
Esempio n. 3
0
        public void AppPathDefaultsToUnderLocalAppData()
        {
            var sut = new PathProvider("testapp");

            var expected = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "testapp");
            Assert.AreEqual(expected, sut.AppPathBase);
        }
Esempio n. 4
0
        public void PreservesGivenPath()
        {
            var tempPath = Path.GetTempPath();

            var sut = new PathProvider("testapp", tempPath);

            Assert.AreEqual(tempPath, sut.AppPathBase);
        }
Esempio n. 5
0
        public void CreatesVersionedPathForUpdateInfo()
        {
            var package = new Mock<IPackage>();
            package.SetupGet(p => p.Version).Returns(new SemanticVersion(1, 2, 3, "beta"));

            var sut = new PathProvider("testapp");

            var expected = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "testapp", "app-1.2.3-beta");
            Assert.AreEqual(expected, sut.GetAppPath(new UpdateInfo(package.Object)));
        }
Esempio n. 6
0
 protected override string GetCommand()
 {
     DependencyDownloader.InstallAutoRest();
     return(PathProvider.GetAutoRestPath());
 }
Esempio n. 7
0
        public static IEnumerable <FileEntry> GetEntries(IFolderDao folderDao, IFileDao fileDao, Folder parent, int from, int count, FilterType filter, bool subjectGroup, Guid subjectId, String searchText, bool searchInContent, bool withSubfolders, OrderBy orderBy, out int total)
        {
            total = 0;

            if (parent == null)
            {
                throw new ArgumentNullException("parent", FilesCommonResource.ErrorMassage_FolderNotFound);
            }

            var fileSecurity = Global.GetFilesSecurity();
            var entries      = Enumerable.Empty <FileEntry>();

            searchInContent = searchInContent && filter != FilterType.ByExtension && !Equals(parent.ID, Global.FolderTrash);

            if (parent.FolderType == FolderType.Projects && parent.ID.Equals(Global.FolderProjects))
            {
                var apiServer = new ASC.Api.ApiServer();
                var apiUrl    = string.Format("{0}project/maxlastmodified.json", SetupInfo.WebApiBaseUrl);

                var responseBody = apiServer.GetApiResponse(apiUrl, "GET");
                if (responseBody != null)
                {
                    var responseApi = JObject.Parse(Encoding.UTF8.GetString(Convert.FromBase64String(responseBody)));

                    var          projectLastModified         = responseApi["response"].Value <String>();
                    const string projectLastModifiedCacheKey = "documents/projectFolders/projectLastModified";
                    if (HttpRuntime.Cache.Get(projectLastModifiedCacheKey) == null || !HttpRuntime.Cache.Get(projectLastModifiedCacheKey).Equals(projectLastModified))
                    {
                        HttpRuntime.Cache.Remove(projectLastModifiedCacheKey);
                        HttpRuntime.Cache.Insert(projectLastModifiedCacheKey, projectLastModified);
                    }
                    var projectListCacheKey  = string.Format("documents/projectFolders/{0}", SecurityContext.CurrentAccount.ID);
                    var folderIDProjectTitle = (Dictionary <object, KeyValuePair <int, string> >)HttpRuntime.Cache.Get(projectListCacheKey);

                    if (folderIDProjectTitle == null)
                    {
                        apiUrl = string.Format("{0}project/filter.json?sortBy=title&sortOrder=ascending&status=open&fields=id,title,security,projectFolder", SetupInfo.WebApiBaseUrl);

                        responseApi = JObject.Parse(Encoding.UTF8.GetString(Convert.FromBase64String(apiServer.GetApiResponse(apiUrl, "GET"))));

                        var responseData = responseApi["response"];

                        if (!(responseData is JArray))
                        {
                            return(entries.ToList());
                        }

                        folderIDProjectTitle = new Dictionary <object, KeyValuePair <int, string> >();
                        foreach (JObject projectInfo in responseData.Children())
                        {
                            var projectID    = projectInfo["id"].Value <int>();
                            var projectTitle = Global.ReplaceInvalidCharsAndTruncate(projectInfo["title"].Value <String>());

                            JToken projectSecurityJToken;
                            if (projectInfo.TryGetValue("security", out projectSecurityJToken))
                            {
                                var    projectSecurity = projectInfo["security"].Value <JObject>();
                                JToken projectCanFileReadJToken;
                                if (projectSecurity.TryGetValue("canReadFiles", out projectCanFileReadJToken))
                                {
                                    if (!projectSecurity["canReadFiles"].Value <bool>())
                                    {
                                        continue;
                                    }
                                }
                            }

                            int    projectFolderID;
                            JToken projectFolderIDjToken;
                            if (projectInfo.TryGetValue("projectFolder", out projectFolderIDjToken))
                            {
                                projectFolderID = projectFolderIDjToken.Value <int>();
                            }
                            else
                            {
                                projectFolderID = (int)FilesIntegration.RegisterBunch("projects", "project", projectID.ToString());
                            }

                            if (!folderIDProjectTitle.ContainsKey(projectFolderID))
                            {
                                folderIDProjectTitle.Add(projectFolderID, new KeyValuePair <int, string>(projectID, projectTitle));
                            }

                            AscCache.Default.Remove("documents/folders/" + projectFolderID);
                            AscCache.Default.Insert("documents/folders/" + projectFolderID, projectTitle, TimeSpan.FromMinutes(30));
                        }

                        HttpRuntime.Cache.Remove(projectListCacheKey);
                        HttpRuntime.Cache.Insert(projectListCacheKey, folderIDProjectTitle, new CacheDependency(null, new[] { projectLastModifiedCacheKey }), Cache.NoAbsoluteExpiration, TimeSpan.FromMinutes(15));
                    }

                    var rootKeys = folderIDProjectTitle.Keys.ToArray();
                    if (filter == FilterType.None || filter == FilterType.FoldersOnly)
                    {
                        var folders = folderDao.GetFolders(rootKeys, filter, subjectGroup, subjectId, searchText, withSubfolders, false);

                        var emptyFilter = string.IsNullOrEmpty(searchText) && filter == FilterType.None && subjectId == Guid.Empty;
                        if (!emptyFilter)
                        {
                            var projectFolderIds =
                                folderIDProjectTitle
                                .Where(projectFolder => (projectFolder.Value.Value ?? "").ToLower().Trim().Contains(searchText.ToLower().Trim()))
                                .Select(projectFolder => projectFolder.Key);

                            folders.RemoveAll(folder => rootKeys.Contains(folder.ID));

                            var projectFolders = folderDao.GetFolders(projectFolderIds.ToArray(), filter, subjectGroup, subjectId, null, false, false);
                            folders.AddRange(projectFolders);
                        }

                        folders.ForEach(x =>
                        {
                            x.Title     = folderIDProjectTitle.ContainsKey(x.ID) ? folderIDProjectTitle[x.ID].Value : x.Title;
                            x.FolderUrl = folderIDProjectTitle.ContainsKey(x.ID) ? PathProvider.GetFolderUrl(x, folderIDProjectTitle[x.ID].Key) : string.Empty;
                        });

                        if (withSubfolders)
                        {
                            folders = fileSecurity.FilterRead(folders).ToList();
                        }

                        entries = entries.Concat(folders);
                    }

                    if (filter != FilterType.FoldersOnly && withSubfolders)
                    {
                        var files = fileDao.GetFiles(rootKeys, filter, subjectGroup, subjectId, searchText, searchInContent).ToList();
                        files   = fileSecurity.FilterRead(files).ToList();
                        entries = entries.Concat(files);
                    }
                }

                parent.TotalFiles      = entries.Aggregate(0, (a, f) => a + (f.FileEntryType == FileEntryType.Folder ? ((Folder)f).TotalFiles : 1));
                parent.TotalSubFolders = entries.Aggregate(0, (a, f) => a + (f.FileEntryType == FileEntryType.Folder ? ((Folder)f).TotalSubFolders + 1 : 0));
            }
            else if (parent.FolderType == FolderType.SHARE)
            {
                //share
                var shared = (IEnumerable <FileEntry>)fileSecurity.GetSharesForMe(filter, subjectGroup, subjectId, searchText, searchInContent, withSubfolders);

                entries = entries.Concat(shared);

                parent.TotalFiles      = entries.Aggregate(0, (a, f) => a + (f.FileEntryType == FileEntryType.Folder ? ((Folder)f).TotalFiles : 1));
                parent.TotalSubFolders = entries.Aggregate(0, (a, f) => a + (f.FileEntryType == FileEntryType.Folder ? ((Folder)f).TotalSubFolders + 1 : 0));
            }
            else
            {
                if (parent.FolderType == FolderType.TRASH)
                {
                    withSubfolders = false;
                }

                var folders = folderDao.GetFolders(parent.ID, orderBy, filter, subjectGroup, subjectId, searchText, withSubfolders).Cast <FileEntry>();
                folders = fileSecurity.FilterRead(folders);
                entries = entries.Concat(folders);

                var files = fileDao.GetFiles(parent.ID, orderBy, filter, subjectGroup, subjectId, searchText, searchInContent, withSubfolders).Cast <FileEntry>();
                files   = fileSecurity.FilterRead(files);
                entries = entries.Concat(files);

                if (filter == FilterType.None || filter == FilterType.FoldersOnly)
                {
                    var folderList = GetThirpartyFolders(parent, searchText);

                    var thirdPartyFolder = FilterEntries(folderList, filter, subjectGroup, subjectId, searchText, searchInContent);
                    entries = entries.Concat(thirdPartyFolder);
                }
            }

            if (orderBy.SortedBy != SortedByType.New)
            {
                entries = SortEntries(entries, orderBy);

                total = entries.Count();
                if (0 < from)
                {
                    entries = entries.Skip(from);
                }
                if (0 < count)
                {
                    entries = entries.Take(count);
                }
            }

            entries = FileMarker.SetTagsNew(folderDao, parent, entries);

            //sorting after marking
            if (orderBy.SortedBy == SortedByType.New)
            {
                entries = SortEntries(entries, orderBy);

                total = entries.Count();
                if (0 < from)
                {
                    entries = entries.Skip(from);
                }
                if (0 < count)
                {
                    entries = entries.Take(count);
                }
            }

            SetFileStatus(entries.Where(r => r != null && r.ID != null && r.FileEntryType == FileEntryType.File).Select(r => r as File).ToList());

            return(entries);
        }
Esempio n. 8
0
        protected void ExecIssueDetailsView(int issueID)
        {
            IssueDetailsView cntrlIssueDetailsView = (IssueDetailsView)LoadControl(PathProvider.GetControlVirtualPath("IssueDetailsView.ascx"));

            cntrlIssueDetailsView.Target = Global.EngineFactory.GetIssueEngine().GetIssue(issueID);

            //if (SecurityContext.CheckPermissions(task.ProjectFat, SecurityProvider, AuthorizationConstants.Action_Task_Create))
            SideActionsPanel.Controls.Add(new NavigationItem
            {
                Name = IssueTrackerResource.AddIssue,
                URL  = String.Format("issueTracker.aspx?prjID={0}&id=-1", Project.ID)
            });

            //switch (task.Status)
            //{

            //case TaskStatus.NotAccept:

            //if (SecurityContext.CheckPermissions(task, SecurityProvider, AuthorizationConstants.Action_Task_Update))
            SideActionsPanel.Controls.Add(new NavigationItem
            {
                Name = ProjectsCommonResource.Edit,
                URL  = String.Format("issueTracker.aspx?prjID={0}&id={1}&action=edit", Project.ID, issueID)
            });



            //break;

            //}

            //if (SecurityContext.CheckPermissions(task, SecurityProvider, AuthorizationConstants.Action_Task_Remove))
            SideActionsPanel.Controls.Add(new NavigationItem
            {
                Name = ProjectsCommonResource.Delete,
                URL  = String.Format("javascript:ASC.Projects.IssueTrackerActionPage.execIssueDelete({0}, '{1}')",
                                     issueID, cntrlIssueDetailsView.Target.Title)
            });

            Master.BreadCrumbs.Add(new BreadCrumb
            {
                Caption       = ProjectResource.Projects,
                NavigationUrl = "projects.aspx"
            });

            Master.BreadCrumbs.Add(new BreadCrumb
            {
                Caption       = Project.HtmlTitle.HtmlEncode(),
                NavigationUrl = "projects.aspx?prjID=" + Project.ID
            });

            Master.BreadCrumbs.Add(new BreadCrumb
            {
                Caption       = IssueTrackerResource.AllIssues,
                NavigationUrl = "issueTracker.aspx?prjID=" + Project.ID
            });

            Master.BreadCrumbs.Add(new BreadCrumb
            {
                Caption = cntrlIssueDetailsView.Target.Title
            });

            _content.Controls.Add(cntrlIssueDetailsView);
        }
Esempio n. 9
0
 public VoipModule(PathProvider pathProvider,
                   SetupInfo setupInfo)
 {
     _pathProvider = pathProvider;
     _setupInfo    = setupInfo;
 }
Esempio n. 10
0
 public void Init()
 {
     optionsMock = new Mock <IGeneralOptions>();
     optionsMock.Setup(c => c.NSwagPath).Returns(PathProvider.GetNSwagPath());
     options = optionsMock.Object;
 }
Esempio n. 11
0
 public NSwagStudioCodeGeneratorTests()
 {
     optionsMock = new Mock <IGeneralOptions>();
     optionsMock.Setup(c => c.NSwagPath).Returns(PathProvider.GetNSwagPath());
     options = optionsMock.Object;
 }
Esempio n. 12
0
        public static IEnumerable <FileEntry> GetEntries(IFolderDao folderDao, IFileDao fileDao, Folder parent, FilterType filter, Guid subjectId, OrderBy orderBy, String searchText, int from, int count, out int total)
        {
            total = 0;

            if (parent == null)
            {
                throw new ArgumentNullException("parent", FilesCommonResource.ErrorMassage_FolderNotFound);
            }

            var fileSecurity = Global.GetFilesSecurity();
            var entries      = Enumerable.Empty <FileEntry>();

            if (parent.FolderType == FolderType.Projects && parent.ID.Equals(Global.FolderProjects))
            {
                var apiServer = new ASC.Api.ApiServer();
                var apiUrl    = String.Format("{0}project/maxlastmodified.json", SetupInfo.WebApiBaseUrl);

                var responseBody = apiServer.GetApiResponse(apiUrl, "GET");
                if (responseBody != null)
                {
                    var responseApi = JObject.Parse(Encoding.UTF8.GetString(Convert.FromBase64String(responseBody)));

                    var          projectLastModified         = responseApi["response"].Value <String>();
                    const string projectLastModifiedCacheKey = "documents/projectFolders/projectLastModified";
                    if (HttpRuntime.Cache.Get(projectLastModifiedCacheKey) == null || !HttpRuntime.Cache.Get(projectLastModifiedCacheKey).Equals(projectLastModified))
                    {
                        HttpRuntime.Cache.Remove(projectLastModifiedCacheKey);
                        HttpRuntime.Cache.Insert(projectLastModifiedCacheKey, projectLastModified);
                    }
                    var projectListCacheKey = String.Format("documents/projectFolders/{0}", SecurityContext.CurrentAccount.ID);
                    var fromCache           = HttpRuntime.Cache.Get(projectListCacheKey);

                    if (fromCache == null || !string.IsNullOrEmpty(searchText))
                    {
                        apiUrl = String.Format("{0}project/filter.json?sortBy=title&sortOrder=ascending&status=open", SetupInfo.WebApiBaseUrl);

                        responseApi = JObject.Parse(Encoding.UTF8.GetString(Convert.FromBase64String(apiServer.GetApiResponse(apiUrl, "GET"))));

                        var responseData = responseApi["response"];

                        if (!(responseData is JArray))
                        {
                            return(entries.ToList());
                        }

                        var folderIDProjectTitle = new Dictionary <object, String>();

                        foreach (JObject projectInfo in responseData.Children())
                        {
                            var projectID    = projectInfo["id"].Value <String>();
                            var projectTitle = Global.ReplaceInvalidCharsAndTruncate(projectInfo["title"].Value <String>());
                            int projectFolderID;

                            JToken projectSecurityJToken;
                            if (projectInfo.TryGetValue("security", out projectSecurityJToken))
                            {
                                var    projectSecurity = projectInfo["security"].Value <JObject>();
                                JToken projectCanFileReadJToken;
                                if (projectSecurity.TryGetValue("canReadFiles", out projectCanFileReadJToken))
                                {
                                    if (!projectSecurity["canReadFiles"].Value <bool>())
                                    {
                                        continue;
                                    }
                                }
                            }

                            JToken projectFolderIDJToken;

                            if (projectInfo.TryGetValue("projectFolder", out projectFolderIDJToken))
                            {
                                projectFolderID = projectInfo["projectFolder"].Value <int>();
                            }
                            else
                            {
                                projectFolderID = (int)FilesIntegration.RegisterBunch("projects", "project", projectID);
                            }

                            if (!folderIDProjectTitle.ContainsKey(projectFolderID))
                            {
                                folderIDProjectTitle.Add(projectFolderID, projectTitle);
                            }
                            HttpRuntime.Cache.Remove("documents/folders/" + projectFolderID.ToString());
                            HttpRuntime.Cache.Insert("documents/folders/" + projectFolderID.ToString(), projectTitle, null, Cache.NoAbsoluteExpiration, TimeSpan.FromMinutes(30));
                        }

                        var folders = folderDao.GetFolders(folderIDProjectTitle.Keys.ToArray(), searchText, !string.IsNullOrEmpty(searchText));
                        folders.ForEach(x =>
                        {
                            x.Title     = folderIDProjectTitle.ContainsKey(x.ID) ? folderIDProjectTitle[x.ID] : x.Title;
                            x.FolderUrl = PathProvider.GetFolderUrl(x);
                        });

                        folders = fileSecurity.FilterRead(folders).ToList();

                        entries = entries.Concat(folders);

                        if (!string.IsNullOrEmpty(searchText))
                        {
                            var files = fileDao.GetFiles(folderIDProjectTitle.Keys.ToArray(), searchText, !string.IsNullOrEmpty(searchText)).ToList();
                            files   = fileSecurity.FilterRead(files).ToList();
                            entries = entries.Concat(files);
                        }

                        if (entries.Any() && string.IsNullOrEmpty(searchText))
                        {
                            HttpRuntime.Cache.Remove(projectListCacheKey);
                            HttpRuntime.Cache.Insert(projectListCacheKey, entries, new CacheDependency(null, new[] { projectLastModifiedCacheKey }), Cache.NoAbsoluteExpiration, TimeSpan.FromMinutes(15));
                        }
                    }
                    else
                    {
                        entries = entries.Concat((IEnumerable <FileEntry>)fromCache);
                    }
                }

                entries = FilterEntries(entries, filter, subjectId, searchText);

                parent.TotalFiles      = entries.Aggregate(0, (a, f) => a + (f is Folder ? ((Folder)f).TotalFiles : 1));
                parent.TotalSubFolders = entries.Aggregate(0, (a, f) => a + (f is Folder ? ((Folder)f).TotalSubFolders + 1 : 0));
            }
            else if (parent.FolderType == FolderType.SHARE)
            {
                //share
                var shared = (IEnumerable <FileEntry>)fileSecurity.GetSharesForMe(searchText, !string.IsNullOrEmpty(searchText));
                if (CoreContext.UserManager.GetUsers(SecurityContext.CurrentAccount.ID).IsVisitor())
                {
                    shared = shared.Where(r => !r.ProviderEntry);
                }

                shared = FilterEntries(shared, filter, subjectId, searchText)
                         .Where(f => f.CreateBy != SecurityContext.CurrentAccount.ID && // don't show my files
                                f.RootFolderType == FolderType.USER);                   // don't show common files (common files can read)
                entries = entries.Concat(shared);

                parent.TotalFiles      = entries.Aggregate(0, (a, f) => a + (f is Folder ? ((Folder)f).TotalFiles : 1));
                parent.TotalSubFolders = entries.Aggregate(0, (a, f) => a + (f is Folder ? ((Folder)f).TotalSubFolders + 1 : 0));
            }
            else
            {
                var folders = folderDao.GetFolders(parent.ID, orderBy, filter, subjectId, searchText, !string.IsNullOrEmpty(searchText) && parent.FolderType != FolderType.TRASH).Cast <FileEntry>();
                folders = fileSecurity.FilterRead(folders);
                entries = entries.Concat(folders);

                //TODO:Optimize
                var files = fileDao.GetFiles(parent.ID, orderBy, filter, subjectId, searchText, !string.IsNullOrEmpty(searchText) && parent.FolderType != FolderType.TRASH).Cast <FileEntry>();
                files   = fileSecurity.FilterRead(files);
                entries = entries.Concat(files);

                if (filter == FilterType.None || filter == FilterType.FoldersOnly)
                {
                    var folderList = GetThirpartyFolders(parent, searchText);

                    var thirdPartyFolder = FilterEntries(folderList, filter, subjectId, searchText);
                    entries = entries.Concat(thirdPartyFolder);
                }
            }

            if (orderBy.SortedBy != SortedByType.New)
            {
                entries = SortEntries(entries, orderBy);

                total = entries.Count();
                if (0 < from)
                {
                    entries = entries.Skip(from);
                }
                if (0 < count)
                {
                    entries = entries.Take(count);
                }
            }

            entries = FileMarker.SetTagsNew(folderDao, parent, entries);

            //sorting after marking
            if (orderBy.SortedBy == SortedByType.New)
            {
                entries = SortEntries(entries, orderBy);

                total = entries.Count();
                if (0 < from)
                {
                    entries = entries.Skip(from);
                }
                if (0 < count)
                {
                    entries = entries.Take(count);
                }
            }

            SetFileStatus(entries.Select(r => r as File).Where(r => r != null && r.ID != null));

            return(entries);
        }
        private static void CheckConvertFilesStatus(object _)
        {
            if (Monitor.TryEnter(singleThread))
            {
                try
                {
                    List <File> filesIsConverting;
                    lock (locker)
                    {
                        timer.Change(Timeout.Infinite, Timeout.Infinite);

                        conversionQueue.Where(x => !string.IsNullOrEmpty(x.Value.Processed) &&
                                              (x.Value.Progress == 100 && DateTime.UtcNow - x.Value.StopDateTime > TimeSpan.FromMinutes(1) ||
                                               DateTime.UtcNow - x.Value.StopDateTime > TimeSpan.FromMinutes(10)))
                        .ToList()
                        .ForEach(x =>
                        {
                            conversionQueue.Remove(x);
                            cache.Remove(GetKey(x.Key));
                        });

                        Global.Logger.DebugFormat("Run CheckConvertFilesStatus: count {0}", conversionQueue.Count);

                        if (conversionQueue.Count == 0)
                        {
                            return;
                        }

                        filesIsConverting = conversionQueue
                                            .Where(x => String.IsNullOrEmpty(x.Value.Processed))
                                            .Select(x => x.Key)
                                            .ToList();
                    }

                    var fileSecurity = Global.GetFilesSecurity();
                    foreach (var file in filesIsConverting)
                    {
                        var    fileUri = file.ID.ToString();
                        string convertedFileUrl;
                        int    operationResultProgress;

                        try
                        {
                            int      tenantId;
                            IAccount account;
                            string   password;

                            lock (locker)
                            {
                                if (!conversionQueue.Keys.Contains(file))
                                {
                                    continue;
                                }

                                var operationResult = conversionQueue[file];
                                if (!string.IsNullOrEmpty(operationResult.Processed))
                                {
                                    continue;
                                }

                                operationResult.Processed = "1";
                                tenantId = operationResult.TenantId;
                                account  = operationResult.Account;
                                password = operationResult.Password;

                                if (HttpContext.Current == null && !WorkContext.IsMono)
                                {
                                    HttpContext.Current = new HttpContext(
                                        new HttpRequest("hack", operationResult.Url, string.Empty),
                                        new HttpResponse(new StringWriter()));
                                }

                                cache.Insert(GetKey(file), operationResult, TimeSpan.FromMinutes(10));
                            }

                            CoreContext.TenantManager.SetCurrentTenant(tenantId);
                            SecurityContext.AuthenticateMe(account);

                            var user    = CoreContext.UserManager.GetUsers(account.ID);
                            var culture = string.IsNullOrEmpty(user.CultureName) ? CoreContext.TenantManager.GetCurrentTenant().GetCulture() : CultureInfo.GetCultureInfo(user.CultureName);
                            Thread.CurrentThread.CurrentCulture   = culture;
                            Thread.CurrentThread.CurrentUICulture = culture;

                            if (!fileSecurity.CanRead(file) && file.RootFolderType != FolderType.BUNCH)
                            {
                                //No rights in CRM after upload before attach
                                throw new SecurityException(FilesCommonResource.ErrorMassage_SecurityException_ReadFile);
                            }
                            if (file.ContentLength > SetupInfo.AvailableFileSize)
                            {
                                throw new Exception(string.Format(FilesCommonResource.ErrorMassage_FileSizeConvert, FileSizeComment.FilesSizeToString(SetupInfo.AvailableFileSize)));
                            }

                            fileUri = PathProvider.GetFileStreamUrl(file);

                            var toExtension   = FileUtility.GetInternalExtension(file.Title);
                            var fileExtension = file.ConvertedExtension;
                            var docKey        = DocumentServiceHelper.GetDocKey(file);

                            fileUri = DocumentServiceConnector.ReplaceCommunityAdress(fileUri);
                            operationResultProgress = DocumentServiceConnector.GetConvertedUri(fileUri, fileExtension, toExtension, docKey, password, null, null, true, out convertedFileUrl);
                        }
                        catch (Exception exception)
                        {
                            DocumentService.DocumentServiceException documentServiceException;
                            var password = exception.InnerException != null &&
                                           ((documentServiceException = exception.InnerException as DocumentService.DocumentServiceException) != null) &&
                                           documentServiceException.Code == DocumentService.DocumentServiceException.ErrorCode.ConvertPassword;

                            Global.Logger.Error(string.Format("Error convert {0} with url {1}", file.ID, fileUri), exception);
                            lock (locker)
                            {
                                if (conversionQueue.Keys.Contains(file))
                                {
                                    var operationResult = conversionQueue[file];
                                    if (operationResult.Delete)
                                    {
                                        conversionQueue.Remove(file);
                                        cache.Remove(GetKey(file));
                                    }
                                    else
                                    {
                                        operationResult.Progress     = 100;
                                        operationResult.StopDateTime = DateTime.UtcNow;
                                        operationResult.Error        = exception.Message;
                                        if (password)
                                        {
                                            operationResult.Result = "password";
                                        }
                                        cache.Insert(GetKey(file), operationResult, TimeSpan.FromMinutes(10));
                                    }
                                }
                            }
                            continue;
                        }

                        operationResultProgress = Math.Min(operationResultProgress, 100);
                        if (operationResultProgress < 100)
                        {
                            lock (locker)
                            {
                                if (conversionQueue.Keys.Contains(file))
                                {
                                    var operationResult = conversionQueue[file];

                                    if (DateTime.Now - operationResult.StartDateTime > TimeSpan.FromMinutes(10))
                                    {
                                        operationResult.StopDateTime = DateTime.UtcNow;
                                        operationResult.Error        = FilesCommonResource.ErrorMassage_ConvertTimeout;
                                        Global.Logger.ErrorFormat("CheckConvertFilesStatus timeout: {0} ({1})", file.ID, file.ContentLengthString);
                                    }
                                    else
                                    {
                                        operationResult.Processed = "";
                                    }
                                    operationResult.Progress = operationResultProgress;
                                    cache.Insert(GetKey(file), operationResult, TimeSpan.FromMinutes(10));
                                }
                            }

                            Global.Logger.Debug("CheckConvertFilesStatus iteration continue");
                            continue;
                        }

                        File newFile = null;
                        var  operationResultError = string.Empty;

                        try
                        {
                            newFile = SaveConvertedFile(file, convertedFileUrl);
                        }
                        catch (Exception e)
                        {
                            operationResultError = e.Message;

                            Global.Logger.ErrorFormat("{0} ConvertUrl: {1} fromUrl: {2}: {3}", operationResultError, convertedFileUrl, fileUri, e);
                            continue;
                        }
                        finally
                        {
                            lock (locker)
                            {
                                if (conversionQueue.Keys.Contains(file))
                                {
                                    var operationResult = conversionQueue[file];
                                    if (operationResult.Delete)
                                    {
                                        conversionQueue.Remove(file);
                                        cache.Remove(GetKey(file));
                                    }
                                    else
                                    {
                                        if (newFile != null)
                                        {
                                            using (var folderDao = Global.DaoFactory.GetFolderDao())
                                            {
                                                var folder      = folderDao.GetFolder(newFile.FolderID);
                                                var folderTitle = fileSecurity.CanRead(folder) ? folder.Title : null;
                                                operationResult.Result = FileJsonSerializer(newFile, folderTitle);
                                            }
                                        }

                                        operationResult.Progress     = 100;
                                        operationResult.StopDateTime = DateTime.UtcNow;
                                        operationResult.Processed    = "1";
                                        if (!string.IsNullOrEmpty(operationResultError))
                                        {
                                            operationResult.Error = operationResultError;
                                        }
                                        cache.Insert(GetKey(file), operationResult, TimeSpan.FromMinutes(10));
                                    }
                                }
                            }
                        }

                        Global.Logger.Debug("CheckConvertFilesStatus iteration end");
                    }

                    lock (locker)
                    {
                        timer.Change(TIMER_PERIOD, TIMER_PERIOD);
                    }
                }
                catch (Exception exception)
                {
                    Global.Logger.Error(exception.Message, exception);
                    lock (locker)
                    {
                        timer.Change(Timeout.Infinite, Timeout.Infinite);
                    }
                }
                finally
                {
                    Monitor.Exit(singleThread);
                }
            }
        }
Esempio n. 14
0
 public LogDBFileInstance(SterlingEngine engine, DateTime date, PathProvider pathProvider)
 {
     DBPath = string.Format("logger/{0:yyyyMM}/", date.ToUniversalTime());
     var db = engine.SterlingDatabase;
     Instance = db.RegisterDatabase<LogDB>(new FileSystemDriver(pathProvider, DBPath));
 }
Esempio n. 15
0
        private static void CheckConvertFilesStatus(object _)
        {
            if (Monitor.TryEnter(singleThread))
            {
                try
                {
                    List <File> filesIsConverting;
                    lock (locker)
                    {
                        timer.Change(Timeout.Infinite, Timeout.Infinite);

                        conversionQueue.Where(x => !string.IsNullOrEmpty(x.Value.Processed) &&
                                              (x.Value.Progress == 100 && DateTime.Now - x.Value.StopDateTime > TimeSpan.FromMinutes(1) ||
                                               DateTime.Now - x.Value.StopDateTime > TimeSpan.FromMinutes(30)))
                        .ToList()
                        .ForEach(x =>
                        {
                            conversionQueue.Remove(x);
                            cache.Remove(GetKey(x.Key));
                        });

                        Global.Logger.DebugFormat("Run CheckConvertFilesStatus: count {0}", conversionQueue.Count);

                        if (conversionQueue.Count == 0)
                        {
                            return;
                        }

                        filesIsConverting = conversionQueue
                                            .Where(x => String.IsNullOrEmpty(x.Value.Processed))
                                            .Select(x => x.Key)
                                            .ToList();
                    }

                    foreach (var file in filesIsConverting)
                    {
                        var    fileUri = file.ID.ToString();
                        string convertedFileUrl;
                        int    operationResultProgress;
                        object folderId;
                        var    currentFolder = false;

                        try
                        {
                            int      tenantId;
                            IAccount account;

                            lock (locker)
                            {
                                if (!conversionQueue.Keys.Contains(file))
                                {
                                    continue;
                                }

                                var operationResult = conversionQueue[file];
                                if (!string.IsNullOrEmpty(operationResult.Processed))
                                {
                                    continue;
                                }

                                operationResult.Processed = "1";
                                tenantId = operationResult.TenantId;
                                account  = operationResult.Account;

                                cache.Insert(GetKey(file), operationResult, TimeSpan.FromMinutes(30));
                            }

                            CoreContext.TenantManager.SetCurrentTenant(tenantId);
                            SecurityContext.AuthenticateMe(account);

                            var user    = CoreContext.UserManager.GetUsers(account.ID);
                            var culture = string.IsNullOrEmpty(user.CultureName) ? CoreContext.TenantManager.GetCurrentTenant().GetCulture() : CultureInfo.GetCultureInfo(user.CultureName);
                            Thread.CurrentThread.CurrentCulture   = culture;
                            Thread.CurrentThread.CurrentUICulture = culture;

                            var fileSecurity = Global.GetFilesSecurity();
                            if (!fileSecurity.CanRead(file) && file.RootFolderType != FolderType.BUNCH)
                            {
                                //No rights in CRM after upload before attach
                                throw new SecurityException(FilesCommonResource.ErrorMassage_SecurityException_ReadFile);
                            }
                            if (file.ContentLength > SetupInfo.AvailableFileSize)
                            {
                                throw new Exception(string.Format(FilesCommonResource.ErrorMassage_FileSizeConvert, FileSizeComment.FilesSizeToString(SetupInfo.AvailableFileSize)));
                            }

                            folderId = Global.FolderMy;
                            using (var folderDao = Global.DaoFactory.GetFolderDao())
                            {
                                var parent = folderDao.GetFolder(file.FolderID);
                                if (parent != null &&
                                    fileSecurity.CanCreate(parent))
                                {
                                    folderId      = parent.ID;
                                    currentFolder = true;
                                }
                            }
                            if (Equals(folderId, 0))
                            {
                                throw new SecurityException(FilesCommonResource.ErrorMassage_FolderNotFound);
                            }

                            fileUri = PathProvider.GetFileStreamUrl(file);

                            var toExtension   = FileUtility.GetInternalExtension(file.Title);
                            var fileExtension = file.ConvertedExtension;
                            var docKey        = DocumentServiceHelper.GetDocKey(file.ID, file.Version, file.ModifiedOn);

                            operationResultProgress = DocumentServiceConnector.GetConvertedUri(fileUri, fileExtension, toExtension, docKey, true, out convertedFileUrl);
                            operationResultProgress = Math.Min(operationResultProgress, 100);
                        }
                        catch (Exception exception)
                        {
                            Global.Logger.ErrorFormat("Error convert {0} with url {1}: {2}", file.ID, fileUri, exception);
                            lock (locker)
                            {
                                if (conversionQueue.Keys.Contains(file))
                                {
                                    var operationResult = conversionQueue[file];
                                    if (operationResult.Delete)
                                    {
                                        conversionQueue.Remove(file);
                                        cache.Remove(GetKey(file));
                                    }
                                    else
                                    {
                                        operationResult.Result       = FileJsonSerializer(file);
                                        operationResult.Progress     = 100;
                                        operationResult.StopDateTime = DateTime.Now;
                                        operationResult.Error        = exception.Message;
                                        cache.Insert(GetKey(file), operationResult, TimeSpan.FromMinutes(30));
                                    }
                                }
                            }
                            continue;
                        }

                        if (operationResultProgress < 100)
                        {
                            lock (locker)
                            {
                                if (conversionQueue.Keys.Contains(file))
                                {
                                    var operationResult = conversionQueue[file];
                                    operationResult.Processed = "";
                                    operationResult.Progress  = operationResultProgress;
                                    cache.Insert(GetKey(file), operationResult, TimeSpan.FromMinutes(30));
                                }
                            }
                            continue;
                        }

                        using (var fileDao = Global.DaoFactory.GetFileDao())
                            using (var folderDao = Global.DaoFactory.GetFolderDao())
                            {
                                var newFileTitle = FileUtility.ReplaceFileExtension(file.Title, FileUtility.GetInternalExtension(file.Title));

                                File newFile = null;
                                if (FilesSettings.UpdateIfExist && (!currentFolder || !file.ProviderEntry))
                                {
                                    newFile = fileDao.GetFile(folderId, newFileTitle);
                                    if (newFile != null && Global.GetFilesSecurity().CanEdit(newFile) && !EntryManager.FileLockedForMe(newFile.ID) && !FileTracker.IsEditing(newFile.ID))
                                    {
                                        newFile.Version++;
                                    }
                                    else
                                    {
                                        newFile = null;
                                    }
                                }

                                if (newFile == null)
                                {
                                    newFile = new File {
                                        FolderID = folderId
                                    };
                                }
                                newFile.Title         = newFileTitle;
                                newFile.ConvertedType = null;
                                newFile.Comment       = string.Format(FilesCommonResource.CommentConvert, file.Title);

                                var operationResultError = string.Empty;
                                try
                                {
                                    var req = (HttpWebRequest)WebRequest.Create(convertedFileUrl);

                                    if (WorkContext.IsMono && ServicePointManager.ServerCertificateValidationCallback == null)
                                    {
                                        ServicePointManager.ServerCertificateValidationCallback += (s, c, n, p) => true; //HACK: http://ubuntuforums.org/showthread.php?t=1841740
                                    }

                                    using (var convertedFileStream = new ResponseStream(req.GetResponse()))
                                    {
                                        newFile.ContentLength = convertedFileStream.Length;
                                        newFile = fileDao.SaveFile(newFile, convertedFileStream);
                                    }

                                    FilesMessageService.Send(newFile, MessageInitiator.DocsService, MessageAction.FileConverted, newFile.Title);
                                    FileMarker.MarkAsNew(newFile);

                                    using (var tagDao = Global.DaoFactory.GetTagDao())
                                    {
                                        var tags = tagDao.GetTags(file.ID, FileEntryType.File, TagType.System).ToList();
                                        if (tags.Any())
                                        {
                                            tags.ForEach(r => r.EntryId = newFile.ID);
                                            tagDao.SaveTags(tags.ToArray());
                                        }
                                    }

                                    operationResultProgress = 100;
                                }
                                catch (WebException e)
                                {
                                    using (var response = e.Response)
                                    {
                                        var httpResponse = (HttpWebResponse)response;
                                        var errorString  = String.Format("Error code: {0}", httpResponse.StatusCode);

                                        if (httpResponse.StatusCode != HttpStatusCode.NotFound)
                                        {
                                            using (var data = response.GetResponseStream())
                                            {
                                                var text = new StreamReader(data).ReadToEnd();
                                                errorString += String.Format(" Error message: {0}", text);
                                            }
                                        }

                                        operationResultProgress = 100;
                                        operationResultError    = errorString;

                                        Global.Logger.ErrorFormat("{0} ConvertUrl: {1} fromUrl: {2}: {3}", errorString, convertedFileUrl, fileUri, e);
                                        throw new Exception(errorString);
                                    }
                                }
                                finally
                                {
                                    var fileSecurity   = Global.GetFilesSecurity();
                                    var removeOriginal = !FilesSettings.StoreOriginalFiles && fileSecurity.CanDelete(file) && currentFolder && !EntryManager.FileLockedForMe(file.ID);
                                    var folderTitle    = folderDao.GetFolder(newFile.FolderID).Title;

                                    lock (locker)
                                    {
                                        if (conversionQueue.Keys.Contains(file))
                                        {
                                            var operationResult = conversionQueue[file];
                                            if (operationResult.Delete)
                                            {
                                                conversionQueue.Remove(file);
                                                cache.Remove(GetKey(file));
                                            }
                                            else
                                            {
                                                operationResult.Result       = FileJsonSerializer(newFile, removeOriginal, folderTitle);
                                                operationResult.StopDateTime = DateTime.Now;
                                                operationResult.Processed    = "1";
                                                operationResult.Progress     = operationResultProgress;
                                                if (!string.IsNullOrEmpty(operationResultError))
                                                {
                                                    operationResult.Error = operationResultError;
                                                }
                                                cache.Insert(GetKey(file), operationResult, TimeSpan.FromMinutes(30));
                                            }
                                        }
                                    }

                                    if (removeOriginal)
                                    {
                                        FileMarker.RemoveMarkAsNewForAll(file);
                                        fileDao.DeleteFile(file.ID);
                                    }
                                }
                            }
                    }

                    lock (locker)
                    {
                        timer.Change(TIMER_PERIOD, TIMER_PERIOD);
                    }
                }
                catch (Exception exception)
                {
                    Global.Logger.Error(exception.Message, exception);
                    lock (locker)
                    {
                        timer.Change(Timeout.Infinite, Timeout.Infinite);
                    }
                }
                finally
                {
                    Monitor.Exit(singleThread);
                }
            }
        }
Esempio n. 16
0
 public RepositoryCaballos(PathProvider pathprovider)
 {
     this.pathprovider = pathprovider;
 }
 public DepartamentosController(IRepositoryHospital repo, PathProvider provider)
 {
     this.repo     = repo;
     this.provider = provider;
 }
Esempio n. 18
0
 public RepositoryCochesXML(PathProvider pathprovider)
 {
     this.PathProvider = pathprovider;
     this.path         = this.PathProvider.MapPath("coches.xml", Folders.Documents);
     this.docxml       = XDocument.Load(this.path);
 }
Esempio n. 19
0
        protected override void PageLoad()
        {
            ((IStudioMaster)Master).DisabledSidePanel = true;

            if (!Global.ModuleManager.IsVisible(ModuleType.TimeTracking))
            {
                Response.Redirect(ProjectsCommonResource.StartURL);
            }

            var project = RequestContext.GetCurrentProject(false);

            if (RequestContext.IsInConcreteProject() && project == null)
            {
                Response.Redirect("default.aspx", true);
            }

            ProjectFat = new ProjectFat(project);

            if (!IsTimer)
            {
                if (TaskID <= 0)
                {
                    var advansedFilter = new Studio.Controls.Common.AdvansedFilter {
                        BlockID = "AdvansedFilter"
                    };
                    _filter.Controls.Add(advansedFilter);

                    var emptyScreenControlFilter = new Studio.Controls.Common.EmptyScreenControl
                    {
                        ImgSrc     = WebImageSupplier.GetAbsoluteWebPath("empty-filter.png", ProductEntryPoint.ID),
                        Header     = TimeTrackingResource.NoTimersFilter,
                        Describe   = TimeTrackingResource.DescrEmptyListTimersFilter,
                        ButtonHTML = String.Format("<span class='baseLinkAction clearFilterButton'>{0}</span>", ProjectsFilterResource.ClearFilter)
                    };
                    emptyScreenFilter.Controls.Add(emptyScreenControlFilter);
                }

                InitPage(ProjectFat);

                var emptyScreenControl = new Studio.Controls.Common.EmptyScreenControl
                {
                    ImgSrc   = WebImageSupplier.GetAbsoluteWebPath("empty_screen_time_tracking.png", ProductEntryPoint.ID),
                    Header   = TimeTrackingResource.NoTtimers,
                    Describe = String.Format(TimeTrackingResource.NoTimersNote)
                };

                if (CanCreateTime())
                {
                    emptyScreenControl.ButtonHTML = String.Format("<span class='baseLinkAction addFirstElement'>{0}</span>", TimeTrackingResource.StartTimer);
                }

                emptyScreen.Controls.Add(emptyScreenControl);

                var apiServer = new Api.ApiServer();

                if (TaskID > 0)
                {
                    var timesForFirstRequest = apiServer.GetApiResponse(String.Format("api/1.0/project/task/{0}/time.json", TaskID), "GET");
                    JsonPublisher(timesForFirstRequest, "timesForFirstRequest");
                }


                if (RequestContext.IsInConcreteProject())
                {
                    var projectTeam = apiServer.GetApiResponse(string.Format("api/1.0/project/{0}/team.json?fields={1}", RequestContext.GetCurrentProjectId(), "id,displayName"), "GET");
                    JsonPublisher(projectTeam, "projectTeam");
                }

                TotalTime = TaskID > 0
                                ? Global.EngineFactory.GetTimeTrackingEngine().GetByTask(TaskID).Sum(r => r.Hours)
                                : Global.EngineFactory.GetTimeTrackingEngine().GetByProject(ProjectFat.Project.ID).Sum(r => r.Hours);
            }
            else
            {
                var taskId = TaskID;
                if (taskId > 0)
                {
                    var t = Global.EngineFactory.GetTaskEngine().GetByID(taskId);
                    if (t == null || t.Status == TaskStatus.Closed)
                    {
                        taskId = -1;
                    }
                }
                Master.DisabledSidePanel = true;
                var cntrlTimer = (TimeSpendActionTimer)LoadControl(PathProvider.GetControlVirtualPath("TimeSpendActionTimer.ascx"));

                if (ProjectFat != null)
                {
                    cntrlTimer.Project = ProjectFat.Project;
                }

                cntrlTimer.Target = taskId;
                _phTimeSpendTimer.Controls.Add(cntrlTimer);
                Title = HeaderStringHelper.GetPageTitle(ProjectsCommonResource.AutoTimer, Master.BreadCrumbs);
            }
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            ((BasicTemplate)Master).Master
            .AddStaticStyles(GetStaticStyleSheet())
            .AddStaticBodyScripts(GetStaticJavaScript());

            LoadControls();

            var mobileAppRegistrator = new CachedMobileAppInstallRegistrator(new MobileAppInstallRegistrator());
            var currentUser          = CoreContext.UserManager.GetUsers(SecurityContext.CurrentAccount.ID);

            DisplayAppsBanner =
                SetupInfo.DisplayMobappBanner("files") &&
                !CoreContext.Configuration.Standalone &&
                !TenantExtra.GetTenantQuota().Trial &&
                !mobileAppRegistrator.IsInstallRegistered(currentUser.Email, MobileAppType.IosDocuments);

            if (CoreContext.Configuration.Personal)
            {
                PersonalProcess();
            }


            #region third-party scripts

            if (AddCustomScript)
            {
                using (var streamReader = new StreamReader(HttpContext.Current.Server.MapPath(PathProvider.GetFileControlPath("AnalyticsPersonalFirstVisit.js"))))
                {
                    var yaScriptText = streamReader.ReadToEnd();
                    Page.RegisterInlineScript(yaScriptText);
                }
            }

            #endregion
        }
Esempio n. 21
0
 public RepositoryAlumnos(PathProvider pathprovider)
 {
     this.pathprovider = pathprovider;
     this.path         = this.pathprovider.MapPath("alumnos.xml", Folders.Documents);
     this.docxml       = XDocument.Load(path);
 }
 public DownloadController(DownloadService downloadService, PathProvider pathProvider, DocumentService documentService)
 {
     _downloadService = downloadService;
     _pathProvider    = pathProvider;
     _documentService = documentService;
 }
        public void GetNSwagPath_Exists()
        {
            var path = PathProvider.GetNSwagPath();

            path.Should().NotBeNullOrWhiteSpace();
        }
Esempio n. 24
0
        protected void ExecAddIssueDialogView(int issueID)
        {
            AddIssueDialogView cntrlAddIssueDialogView = (AddIssueDialogView)LoadControl(PathProvider.GetControlVirtualPath("AddIssueDialogView.ascx"));

            cntrlAddIssueDialogView.Participants = Global.EngineFactory.GetProjectEngine().GetTeam(Project.ID);

            if (issueID != -1)
            {
                var issue = Global.EngineFactory.GetIssueEngine().GetIssue(issueID);

                cntrlAddIssueDialogView.Title              = issue.Title;
                cntrlAddIssueDialogView.DetectedInVersion  = issue.DetectedInVersion;
                cntrlAddIssueDialogView.Description        = issue.Description;
                cntrlAddIssueDialogView.CorrectedInVersion = issue.CorrectedInVersion;
                cntrlAddIssueDialogView.Priority           = issue.Priority;
            }
            else
            {
                cntrlAddIssueDialogView.Title              = "";
                cntrlAddIssueDialogView.DetectedInVersion  = "";
                cntrlAddIssueDialogView.Description        = "";
                cntrlAddIssueDialogView.CorrectedInVersion = "";
                cntrlAddIssueDialogView.Priority           = IssuePriority.Normal;
            }

            //if (SecurityContext.CheckPermissions(task.ProjectFat, SecurityProvider, AuthorizationConstants.Action_Task_Create))
            SideActionsPanel.Controls.Add(new NavigationItem
            {
                Name = IssueTrackerResource.AddIssue,
                URL  = String.Format("issueTracker.aspx?prjID={0}&id=-1", Project.ID)
            });

            Master.BreadCrumbs.Add(new BreadCrumb
            {
                Caption       = ProjectResource.Projects,
                NavigationUrl = "projects.aspx"
            });

            Master.BreadCrumbs.Add(new BreadCrumb
            {
                Caption       = Project.HtmlTitle.HtmlEncode(),
                NavigationUrl = "projects.aspx?prjID=" + Project.ID
            });

            Master.BreadCrumbs.Add(new BreadCrumb
            {
                Caption       = IssueTrackerResource.AllIssues,
                NavigationUrl = "issueTracker.aspx?prjID=" + Project.ID
            });

            Master.BreadCrumbs.Add(new BreadCrumb
            {
                Caption = IssueTrackerResource.AddNewIssue
            });

            _content.Controls.Add(cntrlAddIssueDialogView);
        }
 protected override IVirtualDirectory GetDirectoryFromBackingDirectoryOrDefault(string directoryName)
 {
     return(new AzureAppendBlobVirtualDirectory(this.PathProvider, PathProvider.SanitizePath(DirPath.CombineWith(directoryName))));
 }
Esempio n. 26
0
        protected void ExecListIssueTrackerView()
        {
            ListIssueTrackerView cntrlListIssueTrackerView = (ListIssueTrackerView)LoadControl(PathProvider.GetControlVirtualPath("ListIssueTrackerView.ascx"));

            cntrlListIssueTrackerView.Project = Project;

            //if (SecurityContext.CheckPermissions(task.ProjectFat, SecurityProvider, AuthorizationConstants.Action_Task_Create))
            SideActionsPanel.Controls.Add(new NavigationItem
            {
                Name = IssueTrackerResource.AddIssue,
                URL  = String.Format("issueTracker.aspx?prjID={0}&id=-1", Project.ID)
            });

            Master.BreadCrumbs.Add(new BreadCrumb
            {
                Caption       = ProjectResource.Projects,
                NavigationUrl = "projects.aspx"
            });

            Master.BreadCrumbs.Add(new BreadCrumb
            {
                Caption       = Project.HtmlTitle.HtmlEncode(),
                NavigationUrl = "projects.aspx?prjID=" + Project.ID
            });

            Master.BreadCrumbs.Add(new BreadCrumb
            {
                Caption = IssueTrackerResource.AllIssues
            });

            /*if (SecurityContext.CheckPermissions(ProjectFat, SecurityProvider, AuthorizationConstants.Action_Task_Create))
             *  SideActionsPanel.Controls.Add(new NavigationItem
             *  {
             *      Name = TaskResource.AddNewTask,
             *      URL = "javascript:ASC.Projects.TaskActionPage.init(-1, null, null); ASC.Projects.TaskActionPage.show()"
             *  });*/

            _content.Controls.Add(cntrlListIssueTrackerView);
        }
 protected override IVirtualFile GetFileFromBackingDirectoryOrDefault(string fileName)
 {
     fileName = PathProvider.CombineVirtualPath(this.DirPath, PathProvider.SanitizePath(fileName));
     return(PathProvider.GetFile(fileName));
 }
Esempio n. 28
0
        public static File SaveEditing(String fileId, string fileExtension, string downloadUri, Stream stream, String doc, string comment = null, bool checkRight = true, bool encrypted = false)
        {
            var newExtension = string.IsNullOrEmpty(fileExtension)
                              ? FileUtility.GetFileExtension(downloadUri)
                              : fileExtension;

            var app = ThirdPartySelector.GetAppByFileId(fileId);

            if (app != null)
            {
                app.SaveFile(fileId, newExtension, downloadUri, stream);
                return(null);
            }

            File file;

            using (var fileDao = Global.DaoFactory.GetFileDao())
            {
                var editLink = FileShareLink.Check(doc, false, fileDao, out file);
                if (file == null)
                {
                    file = fileDao.GetFile(fileId);
                }

                if (file == null)
                {
                    throw new FileNotFoundException(FilesCommonResource.ErrorMassage_FileNotFound);
                }
                var fileSecurity = Global.GetFilesSecurity();
                if (checkRight && !editLink && (!(fileSecurity.CanEdit(file) || fileSecurity.CanReview(file)) || CoreContext.UserManager.GetUsers(SecurityContext.CurrentAccount.ID).IsVisitor()))
                {
                    throw new SecurityException(FilesCommonResource.ErrorMassage_SecurityException_EditFile);
                }
                if (checkRight && FileLockedForMe(file.ID))
                {
                    throw new Exception(FilesCommonResource.ErrorMassage_LockedFile);
                }
                if (checkRight && FileTracker.IsEditing(file.ID))
                {
                    throw new Exception(FilesCommonResource.ErrorMassage_SecurityException_UpdateEditingFile);
                }
                if (file.RootFolderType == FolderType.TRASH)
                {
                    throw new Exception(FilesCommonResource.ErrorMassage_ViewTrashItem);
                }

                var currentExt = file.ConvertedExtension;
                if (string.IsNullOrEmpty(newExtension))
                {
                    newExtension = FileUtility.GetInternalExtension(file.Title);
                }

                file.Version++;
                if (string.IsNullOrEmpty(comment))
                {
                    comment = FilesCommonResource.CommentEdit;
                }

                file.Encrypted = encrypted;

                file.ConvertedType = FileUtility.GetFileExtension(file.Title) != newExtension ? newExtension : null;

                if (file.ProviderEntry && !newExtension.Equals(currentExt))
                {
                    if (FileUtility.ExtsConvertible.Keys.Contains(newExtension) &&
                        FileUtility.ExtsConvertible[newExtension].Contains(currentExt))
                    {
                        if (stream != null)
                        {
                            downloadUri = PathProvider.GetTempUrl(stream, newExtension);
                            downloadUri = DocumentServiceConnector.ReplaceCommunityAdress(downloadUri);
                        }

                        var key = DocumentServiceConnector.GenerateRevisionId(downloadUri);
                        DocumentServiceConnector.GetConvertedUri(downloadUri, newExtension, currentExt, key, false, out downloadUri);

                        stream = null;
                    }
                    else
                    {
                        file.ID    = null;
                        file.Title = FileUtility.ReplaceFileExtension(file.Title, newExtension);
                    }

                    file.ConvertedType = null;
                }

                using (var tmpStream = new MemoryStream())
                {
                    if (stream != null)
                    {
                        stream.CopyTo(tmpStream);
                    }
                    else
                    {
                        // hack. http://ubuntuforums.org/showthread.php?t=1841740
                        if (WorkContext.IsMono)
                        {
                            ServicePointManager.ServerCertificateValidationCallback += (s, ce, ca, p) => true;
                        }

                        var req = (HttpWebRequest)WebRequest.Create(downloadUri);
                        using (var editedFileStream = new ResponseStream(req.GetResponse()))
                        {
                            editedFileStream.CopyTo(tmpStream);
                        }
                    }
                    tmpStream.Position = 0;

                    file.ContentLength = tmpStream.Length;
                    file.Comment       = string.IsNullOrEmpty(comment) ? null : comment;
                    file = fileDao.SaveFile(file, tmpStream);
                }
            }

            FileMarker.MarkAsNew(file);
            FileMarker.RemoveMarkAsNew(file);
            return(file);
        }
Esempio n. 29
0
 public RepositoryDepartamentosXML(PathProvider provider)
 {
     this.provider = provider;
     this.path     = this.provider.MapPath("departamentos.xml", Folders.Documents);
     this.docxml   = XDocument.Load(path);
 }
Esempio n. 30
0
        public static File ExecDuplicate(File file, string shareLinkKey)
        {
            var toFolderId = file.FolderID;

            using (var fileDao = Global.DaoFactory.GetFileDao())
                using (var folderDao = Global.DaoFactory.GetFolderDao())
                {
                    if (!Global.GetFilesSecurity().CanRead(file))
                    {
                        var readLink = FileShareLink.Check(shareLinkKey, true, fileDao, out file);
                        if (file == null)
                        {
                            throw new ArgumentNullException("file", FilesCommonResource.ErrorMassage_FileNotFound);
                        }
                        if (!readLink)
                        {
                            throw new SecurityException(FilesCommonResource.ErrorMassage_SecurityException_ReadFile);
                        }
                        toFolderId = Global.FolderMy;
                    }
                    if (Global.EnableUploadFilter && !FileUtility.ExtsUploadable.Contains(FileUtility.GetFileExtension(file.Title)))
                    {
                        throw new Exception(FilesCommonResource.ErrorMassage_NotSupportedFormat);
                    }
                    var toFolder = folderDao.GetFolder(toFolderId);
                    if (toFolder == null)
                    {
                        throw new DirectoryNotFoundException(FilesCommonResource.ErrorMassage_FolderNotFound);
                    }
                    if (!Global.GetFilesSecurity().CanCreate(toFolder))
                    {
                        throw new SecurityException(FilesCommonResource.ErrorMassage_SecurityException_Create);
                    }

                    var fileUri       = PathProvider.GetFileStreamUrl(file);
                    var fileExtension = file.ConvertedExtension;
                    var toExtension   = FileUtility.GetInternalExtension(file.Title);
                    var docKey        = DocumentServiceHelper.GetDocKey(file.ID, file.Version, file.ModifiedOn);

                    string convertUri;
                    DocumentServiceConnector.GetConvertedUri(fileUri, fileExtension, toExtension, docKey, false, out convertUri);

                    var newFile = new File
                    {
                        FolderID = toFolder.ID,
                        Title    = FileUtility.ReplaceFileExtension(file.Title, toExtension),
                        Comment  = string.Format(FilesCommonResource.CommentConvert, file.Title),
                    };

                    var req = (HttpWebRequest)WebRequest.Create(convertUri);

                    // hack. http://ubuntuforums.org/showthread.php?t=1841740
                    if (WorkContext.IsMono)
                    {
                        ServicePointManager.ServerCertificateValidationCallback += (s, ce, ca, p) => true;
                    }

                    using (var editedFileStream = new ResponseStream(req.GetResponse()))
                    {
                        newFile.ContentLength = editedFileStream.Length;
                        newFile = fileDao.SaveFile(newFile, editedFileStream);
                    }

                    FileMarker.MarkAsNew(newFile);
                    return(newFile);
                }
        }
Esempio n. 31
0
        public void SaveFile(string fileId, string fileType, string downloadUrl, Stream stream)
        {
            Global.Logger.Debug("GoogleDriveApp: save file stream " + fileId +
                                (stream == null
                                     ? " from - " + downloadUrl
                                     : " from stream"));
            fileId = ThirdPartySelector.GetFileId(fileId);

            var token = Token.GetToken(AppAttr);

            var driveFile = GetDriveFile(fileId, token);

            if (driveFile == null)
            {
                Global.Logger.Error("GoogleDriveApp: file is null");
                throw new Exception("File not found");
            }

            var jsonFile    = JObject.Parse(driveFile);
            var currentType = GetCorrectExt(jsonFile);

            if (!fileType.Equals(currentType))
            {
                try
                {
                    if (stream != null)
                    {
                        downloadUrl = PathProvider.GetTempUrl(stream, fileType);
                        downloadUrl = DocumentServiceConnector.ReplaceCommunityAdress(downloadUrl);
                    }

                    Global.Logger.Debug("GoogleDriveApp: GetConvertedUri from " + fileType + " to " + currentType + " - " + downloadUrl);

                    var key = DocumentServiceConnector.GenerateRevisionId(downloadUrl);
                    DocumentServiceConnector.GetConvertedUri(downloadUrl, fileType, currentType, key, null, false, out downloadUrl);
                    stream = null;
                }
                catch (Exception e)
                {
                    Global.Logger.Error("GoogleDriveApp: Error convert", e);
                }
            }

            var request = (HttpWebRequest)WebRequest.Create(GoogleLoginProvider.GoogleUrlFileUpload + "/{fileId}?uploadType=media".Replace("{fileId}", fileId));

            request.Method = "PATCH";
            request.Headers.Add("Authorization", "Bearer " + token);
            request.ContentType = MimeMapping.GetMimeMapping(currentType);

            if (stream != null)
            {
                request.ContentLength = stream.Length;

                const int bufferSize = 2048;
                var       buffer     = new byte[bufferSize];
                int       readed;
                while ((readed = stream.Read(buffer, 0, bufferSize)) > 0)
                {
                    request.GetRequestStream().Write(buffer, 0, readed);
                }
            }
            else
            {
                var downloadRequest = (HttpWebRequest)WebRequest.Create(downloadUrl);
                using (var downloadStream = new ResponseStream(downloadRequest.GetResponse()))
                {
                    request.ContentLength = downloadStream.Length;

                    const int bufferSize = 2048;
                    var       buffer     = new byte[bufferSize];
                    int       readed;
                    while ((readed = downloadStream.Read(buffer, 0, bufferSize)) > 0)
                    {
                        request.GetRequestStream().Write(buffer, 0, readed);
                    }
                }
            }

            try
            {
                using (var response = request.GetResponse())
                    using (var responseStream = response.GetResponseStream())
                    {
                        string result = null;
                        if (responseStream != null)
                        {
                            using (var readStream = new StreamReader(responseStream))
                            {
                                result = readStream.ReadToEnd();
                            }
                        }

                        Global.Logger.Debug("GoogleDriveApp: save file stream response - " + result);
                    }
            }
            catch (WebException e)
            {
                Global.Logger.Error("GoogleDriveApp: Error save file stream", e);
                request.Abort();
                var httpResponse = (HttpWebResponse)e.Response;
                if (httpResponse.StatusCode == HttpStatusCode.Forbidden || httpResponse.StatusCode == HttpStatusCode.Unauthorized)
                {
                    throw new SecurityException(FilesCommonResource.ErrorMassage_SecurityException, e);
                }
                throw;
            }
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            var currUser   = CoreContext.UserManager.GetUsers(SecurityContext.CurrentAccount.ID);
            var isVisitor  = currUser.IsVisitor();
            var isOutsider = currUser.IsOutsider();

            var strCreateFile =
                !HideAddActions && !isVisitor
                    ? string.Format(@"<div class=""empty-folder-create empty-folder-create-editor"">
<a class=""link dotline plus empty-folder-create-document"">{0}</a>,
<a class=""link dotline empty-folder-create-spreadsheet"">{1}</a>,
<a class=""link dotline empty-folder-create-presentation"">{2}</a>
</div>",
                                    FilesUCResource.ButtonCreateText,
                                    FilesUCResource.ButtonCreateSpreadsheet,
                                    FilesUCResource.ButtonCreatePresentation)
                    : string.Empty;

            var strCreateFolder =
                !HideAddActions && !isOutsider
                    ? string.Format(@"<div class=""empty-folder-create""><a class=""empty-folder-create-folder link dotline plus"">{0}</a></div>", FilesUCResource.ButtonCreateFolder)
                    : string.Empty;

            var strDragDrop =
                !HideAddActions
                    ? string.Format("<div class=\"emptyContainer_dragDrop\" > {0}</div>", FilesUCResource.EmptyScreenDescrDragDrop.HtmlEncode())
                    : string.Empty;

            var strToParent = string.Format("<div><a class=\"empty-folder-toparent link dotline up\" >{0}</a></div>", FilesUCResource.ButtonToParentFolder);

            if (AllContainers)
            {
                //my
                if (!isVisitor)
                {
                    var myButton = new StringBuilder();
                    myButton.Append(strCreateFile);
                    myButton.Append(strCreateFolder);
                    myButton.Append(strToParent);

                    var descrMy = string.Format(FileUtility.ExtsWebEdited.Any() ? FilesUCResource.EmptyScreenDescrMy.HtmlEncode() : FilesUCResource.EmptyScreenDescrMyPoor.HtmlEncode(),
                                                //create
                                                "<span class=\"hintCreate baseLinkAction\" >", "</span>",
                                                //upload
                                                "<span class=\"hintUpload baseLinkAction\" >", "</span>",
                                                //open
                                                "<span class=\"hintOpen baseLinkAction\" >", "</span>",
                                                //edit
                                                "<span class=\"hintEdit baseLinkAction\" >", "</span>"
                                                );
                    descrMy += strDragDrop;

                    EmptyScreenFolder.Controls.Add(new EmptyScreenControl
                    {
                        ID             = "emptyContainer_my",
                        ImgSrc         = PathProvider.GetImagePath("empty_screen_my.png"),
                        Header         = FilesUCResource.MyFiles,
                        HeaderDescribe = FilesUCResource.EmptyScreenHeader,
                        Describe       = descrMy,
                        ButtonHTML     = myButton.ToString()
                    });
                }

                if (!CoreContext.Configuration.Personal)
                {
                    //forme
                    var formeButton = new StringBuilder();
                    formeButton.Append(strCreateFile);
                    formeButton.Append(strCreateFolder);
                    formeButton.Append(strToParent);

                    EmptyScreenFolder.Controls.Add(new EmptyScreenControl
                    {
                        ID             = "emptyContainer_forme",
                        ImgSrc         = PathProvider.GetImagePath("empty_screen_forme.png"),
                        Header         = FilesUCResource.SharedForMe,
                        HeaderDescribe = FilesUCResource.EmptyScreenHeader,
                        Describe       = FilesUCResource.EmptyScreenDescrForme.HtmlEncode(),
                        ButtonHTML     = formeButton.ToString()
                    });

                    //corporate
                    var corporateButton = new StringBuilder();
                    corporateButton.Append(strCreateFile);
                    corporateButton.Append(strCreateFolder);
                    corporateButton.Append(strToParent);

                    EmptyScreenFolder.Controls.Add(new EmptyScreenControl
                    {
                        ID             = "emptyContainer_corporate",
                        ImgSrc         = PathProvider.GetImagePath("empty_screen_corporate.png"),
                        Header         = FilesUCResource.CorporateFiles,
                        HeaderDescribe = FilesUCResource.EmptyScreenHeader,
                        Describe       = FilesUCResource.EmptyScreenDescrCorporate.HtmlEncode() + strDragDrop,
                        ButtonHTML     = corporateButton.ToString()
                    });
                }

                var strGotoMy = !isVisitor?string.Format("<div><a href=\"#{1}\" class=\"empty-folder-goto link dotline up\">{0}</a></div>", FilesUCResource.ButtonGotoMy, Global.FolderMy) : string.Empty;

                //trash
                EmptyScreenFolder.Controls.Add(new EmptyScreenControl
                {
                    ID             = "emptyContainer_trash",
                    ImgSrc         = PathProvider.GetImagePath("empty_screen_trash.png"),
                    Header         = FilesUCResource.Trash,
                    HeaderDescribe = FilesUCResource.EmptyScreenHeader,
                    Describe       = FilesUCResource.EmptyScreenDescrTrash.HtmlEncode(),
                    ButtonHTML     = strGotoMy
                });
            }

            if (!CoreContext.Configuration.Personal)
            {
                //project
                var projectButton = new StringBuilder();
                projectButton.Append(strCreateFile);
                projectButton.Append(strCreateFolder);
                projectButton.Append(strToParent);

                EmptyScreenFolder.Controls.Add(new EmptyScreenControl
                {
                    ID             = "emptyContainer_project",
                    ImgSrc         = PathProvider.GetImagePath("empty_screen_project.png"),
                    Header         = FilesUCResource.ProjectFiles,
                    HeaderDescribe = FilesUCResource.EmptyScreenHeader,
                    Describe       = FilesUCResource.EmptyScreenDescrProject.HtmlEncode() + strDragDrop,
                    ButtonHTML     = projectButton.ToString()
                });
            }

            //Filter
            EmptyScreenFolder.Controls.Add(new EmptyScreenControl
            {
                ID             = "emptyContainer_filter",
                ImgSrc         = PathProvider.GetImagePath("empty_screen_filter.png"),
                Header         = FilesUCResource.Filter,
                HeaderDescribe = FilesUCResource.EmptyScreenFilter,
                Describe       = FilesUCResource.EmptyScreenFilterDescr.HtmlEncode(),
                ButtonHTML     = string.Format("<a id=\"files_clearFilter\" class=\"clearFilterButton link dotline\" >{0}</a>",
                                               FilesUCResource.ButtonClearFilter)
            });
        }
 protected override IVirtualDirectory GetDirectoryFromBackingDirectoryOrDefault(string directoryName)
 {
     return(new S3VirtualDirectory(PathProvider, PathProvider.SanitizePath(DirPath.CombineWith(directoryName)), this));
 }
Esempio n. 34
0
        protected void Page_Load(object sender, EventArgs e)
        {
            if (IsPostBack)
            {
                if (ConvertCheck.Checked)
                {
                    FilesSettings.ConvertNotify = !ConvertCheck.Checked;
                }

                if (IsConvert)
                {
                    Response.Redirect(ThirdPartyAppHandler.HandlerPath
                                      + "?" + FilesLinkUtility.Action + "=convert"
                                      + "&" + FilesLinkUtility.FileId + "=" + HttpUtility.UrlEncode(FileId)
                                      + "&" + ThirdPartySelector.AppAttr + "=" + GoogleDriveApp.AppAttr,
                                      true);
                    return;
                }

                var fileName = string.IsNullOrEmpty(InputName.Text) ? FilesJSResource.TitleNewFileText : InputName.Text;
                fileName = fileName.Substring(0, Math.Min(fileName.Length, Global.MaxTitle - 5));
                fileName = Global.ReplaceInvalidCharsAndTruncate(fileName);
                FileType fileType;
                if (!Enum.TryParse(Request["fileType"], true, out fileType))
                {
                    fileType = FileType.Document;
                }
                var ext = FileUtility.InternalExtension[fileType];
                fileName += ext;
                Response.Redirect(ThirdPartyAppHandler.HandlerPath
                                  + "?" + FilesLinkUtility.Action + "=create"
                                  + "&" + FilesLinkUtility.FolderId + "=" + HttpUtility.UrlEncode(FolderId)
                                  + "&" + FilesLinkUtility.FileTitle + "=" + HttpUtility.UrlEncode(fileName)
                                  + "&" + ThirdPartySelector.AppAttr + "=" + GoogleDriveApp.AppAttr,
                                  true);
                return;
            }

            Master.Master.DisabledSidePanel = true;
            Master.Master.TopStudioPanel.DisableProductNavigation = true;
            Master.Master.TopStudioPanel.DisableUserInfo          = true;
            Master.Master.TopStudioPanel.DisableSearch            = true;
            Master.Master.TopStudioPanel.DisableSettings          = true;
            Master.Master.TopStudioPanel.DisableTariff            = true;

            Page.RegisterStyle(PathProvider.GetFileStaticRelativePath("app.css"));
            Page.RegisterInlineScript(@"
jq("".files-app-create"").trackEvent(""files_app"", ""action-click"", ""create"");
jq("".files-app-convert"").trackEvent(""files_app"", ""action-click"", ""convert"");
");

            if (IsConvert)
            {
                ButtonConvert.Text = FilesCommonResource.AppButtonConvert;
                ConvertCheck.Text  = FilesCommonResource.AppConvertCopyHide;
            }
            else
            {
                ButtonCreate.Text   = FilesCommonResource.AppButtonCreate;
                InputName.MaxLength = Global.MaxTitle;
                InputName.Attributes.Add("placeholder", FilesJSResource.TitleNewFileText);
            }
        }
Esempio n. 35
0
        public void SaveFile(string fileId, string fileType, string downloadUrl, Stream stream)
        {
            Logger.Debug("BoxApp: save file stream " + fileId +
                         (stream == null
                                     ? " from - " + downloadUrl
                                     : " from stream"));
            fileId = ThirdPartySelector.GetFileId(fileId.ToString());

            var token = TokenHelper.GetToken(AppAttr);

            var boxFile = GetBoxFile(fileId.ToString(), token);

            if (boxFile == null)
            {
                Logger.Error("BoxApp: file is null");
                throw new Exception("File not found");
            }

            var jsonFile    = JObject.Parse(boxFile);
            var title       = Global.ReplaceInvalidCharsAndTruncate(jsonFile.Value <string>("name"));
            var currentType = FileUtility.GetFileExtension(title);

            if (!fileType.Equals(currentType))
            {
                try
                {
                    if (stream != null)
                    {
                        downloadUrl = PathProvider.GetTempUrl(stream, fileType);
                        downloadUrl = DocumentServiceConnector.ReplaceCommunityAdress(downloadUrl);
                    }

                    Logger.Debug("BoxApp: GetConvertedUri from " + fileType + " to " + currentType + " - " + downloadUrl);

                    var key = DocumentServiceConnector.GenerateRevisionId(downloadUrl);
                    DocumentServiceConnector.GetConvertedUri(downloadUrl, fileType, currentType, key, null, false, out downloadUrl);
                    stream = null;
                }
                catch (Exception e)
                {
                    Logger.Error("BoxApp: Error convert", e);
                }
            }

            var request = (HttpWebRequest)WebRequest.Create(BoxUrlUpload.Replace("{fileId}", fileId));

            using (var tmpStream = new MemoryStream())
            {
                var boundary = DateTime.UtcNow.Ticks.ToString("x");

                var metadata     = string.Format("Content-Disposition: form-data; name=\"filename\"; filename=\"{0}\"\r\nContent-Type: application/octet-stream\r\n\r\n", title);
                var metadataPart = string.Format("--{0}\r\n{1}", boundary, metadata);
                var bytes        = Encoding.UTF8.GetBytes(metadataPart);
                tmpStream.Write(bytes, 0, bytes.Length);

                if (stream != null)
                {
                    stream.CopyTo(tmpStream);
                }
                else
                {
                    var downloadRequest = (HttpWebRequest)WebRequest.Create(downloadUrl);
                    using var downloadStream = new ResponseStream(downloadRequest.GetResponse());
                    downloadStream.CopyTo(tmpStream);
                }

                var mediaPartEnd = string.Format("\r\n--{0}--\r\n", boundary);
                bytes = Encoding.UTF8.GetBytes(mediaPartEnd);
                tmpStream.Write(bytes, 0, bytes.Length);

                request.Method = "POST";
                request.Headers.Add("Authorization", "Bearer " + token);
                request.ContentType   = "multipart/form-data; boundary=" + boundary;
                request.ContentLength = tmpStream.Length;
                Logger.Debug("BoxApp: save file totalSize - " + tmpStream.Length);

                const int bufferSize = 2048;
                var       buffer     = new byte[bufferSize];
                int       readed;
                tmpStream.Seek(0, SeekOrigin.Begin);
                while ((readed = tmpStream.Read(buffer, 0, bufferSize)) > 0)
                {
                    request.GetRequestStream().Write(buffer, 0, readed);
                }
            }

            try
            {
                using var response       = request.GetResponse();
                using var responseStream = response.GetResponseStream();
                string result = null;
                if (responseStream != null)
                {
                    using var readStream = new StreamReader(responseStream);
                    result = readStream.ReadToEnd();
                }

                Logger.Debug("BoxApp: save file response - " + result);
            }
            catch (WebException e)
            {
                Logger.Error("BoxApp: Error save file", e);
                request.Abort();
                var httpResponse = (HttpWebResponse)e.Response;
                if (httpResponse.StatusCode == HttpStatusCode.Forbidden || httpResponse.StatusCode == HttpStatusCode.Unauthorized)
                {
                    throw new SecurityException(FilesCommonResource.ErrorMassage_SecurityException, e);
                }
                throw;
            }
        }
Esempio n. 36
0
        public async Task <ActionResult> Index(AuthenticationModel model)
        {
            if (ModelState.IsValid)
            {
                try
                {
                    using (var client = await ArmHelper.GetWebSiteManagementClient(model))
                    {
                        //Update web config.
                        var site = client.WebApps.GetSiteOrSlot(model.ResourceGroupName, model.WebAppName, model.SiteSlotName);
                        if (site == null)
                        {
                            ModelState.AddModelError(nameof(model.ResourceGroupName), string.Format("No web app could be found, please validate that Resource Group Name and/or Site Slot Name are correct"));
                            return(View(model));
                        }
                        //Validate that the service plan resource group name is correct, to avoid more issues on this specific problem.
                        var azureServerFarmResourceGroup = site.ServerFarmResourceGroup();
                        if (!string.Equals(azureServerFarmResourceGroup, model.ServicePlanResourceGroupName, StringComparison.InvariantCultureIgnoreCase))
                        {
                            ModelState.AddModelError("ServicePlanResourceGroupName", string.Format("The Service Plan Resource Group registered on the Web App in Azure in the ServerFarmId property '{0}' does not match the value you entered here {1}", azureServerFarmResourceGroup, model.ServicePlanResourceGroupName));
                            return(View(model));
                        }
                        var appServicePlan = client.AppServicePlans.Get(model.ServicePlanResourceGroupName, site.ServerFarmName());
                        if (appServicePlan.Sku.Tier.Equals("Free") || appServicePlan.Sku.Tier.Equals("Shared"))
                        {
                            ModelState.AddModelError("ServicePlanResourceGroupName", $"The Service Plan is using the {appServicePlan.Sku.Tier} which doesn't support SSL certificates");
                            return(View(model));
                        }
                        var path = new PathProvider(model);
                        if (model.RunFromPackage && !await path.IsVirtualDirectorySetup() && !model.UpdateAppSettings)
                        {
                            ModelState.AddModelError("UpdateAppSettings", string.Format("The site is using Run From Package. You need to to allow the site-extension to update app settings to setup the virtual directory."));
                            return(View(model));
                        }
                        var webappsettings = client.WebApps.ListSiteOrSlotAppSettings(model.ResourceGroupName, model.WebAppName, model.SiteSlotName);
                        if (model.UpdateAppSettings)
                        {
                            var newAppSettingsValues = new Dictionary <string, string> {
                                { AppSettingsAuthConfig.clientIdKey, model.ClientId.ToString() },
                                { AppSettingsAuthConfig.clientSecretKey, model.ClientSecret.ToString() },
                                { AppSettingsAuthConfig.subscriptionIdKey, model.SubscriptionId.ToString() },
                                { AppSettingsAuthConfig.tenantKey, model.Tenant },
                                { AppSettingsAuthConfig.resourceGroupNameKey, model.ResourceGroupName },
                                { AppSettingsAuthConfig.siteSlotNameKey, model.SiteSlotName },
                                { AppSettingsAuthConfig.servicePlanResourceGroupNameKey, model.ServicePlanResourceGroupName },
                                { AppSettingsAuthConfig.useIPBasedSSL, model.UseIPBasedSSL.ToString().ToLowerInvariant() }
                            };
                            foreach (var appsetting in newAppSettingsValues)
                            {
                                if (!webappsettings.Properties.ContainsKey(appsetting.Key))
                                {
                                    webappsettings.Properties.Add(appsetting.Key, appsetting.Value);
                                }
                                else
                                {
                                    webappsettings.Properties[appsetting.Key] = appsetting.Value;
                                }
                            }

                            client.WebApps.UpdateSiteOrSlotAppSettings(model.ResourceGroupName, model.WebAppName, model.SiteSlotName, webappsettings);
                            ConfigurationManager.RefreshSection("appSettings");

                            await path.ChallengeDirectory(true);
                        }
                        else
                        {
                            var appSetting = new AppSettingsAuthConfig();
                            if (!ValidateModelVsAppSettings("ClientId", appSetting.ClientId.ToString(), model.ClientId.ToString()) ||
                                !ValidateModelVsAppSettings("ClientSecret", appSetting.ClientSecret, model.ClientSecret) ||
                                !ValidateModelVsAppSettings("ResourceGroupName", appSetting.ResourceGroupName, model.ResourceGroupName) ||
                                !ValidateModelVsAppSettings("SubScriptionId", appSetting.SubscriptionId.ToString(), model.SubscriptionId.ToString()) ||
                                !ValidateModelVsAppSettings("Tenant", appSetting.Tenant, model.Tenant) ||
                                !ValidateModelVsAppSettings("SiteSlotName", appSetting.SiteSlotName, model.SiteSlotName) ||
                                !ValidateModelVsAppSettings("ServicePlanResourceGroupName", appSetting.ServicePlanResourceGroupName, model.ServicePlanResourceGroupName) ||
                                !ValidateModelVsAppSettings("UseIPBasedSSL", appSetting.UseIPBasedSSL.ToString().ToLowerInvariant(), model.UseIPBasedSSL.ToString().ToLowerInvariant()))
                            {
                                model.ErrorMessage = "One or more app settings are different from the values entered, do you want to update the app settings?";
                                return(View(model));
                            }
                        }
                    }
                    return(RedirectToAction("PleaseWait"));
                }
                catch (Exception ex)
                {
                    Trace.TraceError(ex.ToString());
                    model.ErrorMessage = ex.ToString();
                }
            }

            return(View(model));
        }
 public DefaultJsonSourceProvider(PathProvider.PathProvider pathProvider)
 {
     this.PathProvider = pathProvider;
 }