Esempio n. 1
0
        /// <summary>
        /// Deletes the entire session from the database context.
        /// </summary>
        /// <param name="session">The session to delete.</param>
        /// <returns><c>true</c> if the operation was successful, <c>false</c> otherwise.</returns>
        public static bool DeleteEntireSession(FileSession session)
        {
            try
            {
                var context = ScriptNotepadDbContext.DbContext;

                context.FileSaves.RemoveRange(context.FileSaves.Where(f => f.Session.SessionName == session.SessionName));
                context.MiscellaneousTextEntries.RemoveRange(context.MiscellaneousTextEntries.Where(f => f.Session.SessionName == session.SessionName));
                context.RecentFiles.RemoveRange(context.RecentFiles.Where(f => f.Session.SessionName == session.SessionName));

                session = context.FileSessions.FirstOrDefault(f => f.SessionName == session.SessionName);

                if (session != null)
                {
                    context.FileSessions.Remove(session);
                }

                context.SaveChanges();
                return(true); // success..
            }
            catch (Exception ex)
            {
                // log the exception..
                ExceptionLogAction?.Invoke(ex);
                return(false); // failure..
            }
        }
Esempio n. 2
0
        /// <summary>
        /// Cleans up the closed (history) files from a given session with a given maximum amount to keep.
        /// </summary>
        /// <param name="keepMaximum">The maximum number of file history to keep per session.</param>
        /// <param name="session">The session </param>
        /// <returns><c>true</c> a tuple containing the value whether the clean up was successful and the amount of records deleted.</returns>
        public static (bool success, int count) CleanUpHistoryFiles(int keepMaximum, FileSession session)
        {
            try
            {
                var dbContext      = ScriptNotepadDbContext.DbContext;
                var deleteSavesIds = dbContext.FileSaves
                                     .Where(f => f.Session.SessionName == session.SessionName && f.IsHistory)
                                     .Select(f => new { id = f.Id, modified = f.DatabaseModified });

                var deleteAmount = deleteSavesIds.Count() - keepMaximum;

                if (deleteAmount > 0)
                {
                    deleteSavesIds = deleteSavesIds.Take(deleteAmount);

                    var deleted = dbContext.FileSaves.Count(f => deleteSavesIds.OrderBy(d => d.modified).Any(h => h.id == f.Id));

                    dbContext.FileSaves.RemoveRange(
                        dbContext.FileSaves.Where(f =>
                                                  deleteSavesIds.OrderBy(d => d.modified).Any(h => h.id == f.Id)));

                    dbContext.SaveChanges();

                    return(true, deleted);
                }

                return(true, 0);
            }
            catch (Exception ex)
            {
                // log the exception..
                ExceptionLogAction?.Invoke(ex);
                return(false, 0);
            }
        }
Esempio n. 3
0
		private EditSession GetEditSession(string fileId)
		{
			var sessionId = /*Context.Session.GetString("SessionID");
			if (string.IsNullOrEmpty(sessionId))
			{
				sessionId = Guid.NewGuid().ToString();
				Context.Session.SetString("SessionID", sessionId);
			}
			sessionId += "|" +*/ fileId;
            EditSession editSession = SessionManager.Current.GetSession(sessionId);

			if (editSession == null)
			{
				IWopiFile file = FileProvider.GetWopiFile(fileId);

				//TODO: remove hardcoded action 'Edit'
				if (WopiDiscoverer.RequiresCobalt(file.Extension, WopiActionEnum.Edit))
				{
					editSession = new CobaltSession(file, sessionId);
				}
				else
				{
					editSession = new FileSession(file, sessionId);
				}
				SessionManager.Current.AddSession(editSession);
			}

			return editSession;
		}
Esempio n. 4
0
        private EditSession GetEditSession(string fileId)
        {
            var sessionId           = /*Context.Session.GetString("SessionID");
                                       * if (string.IsNullOrEmpty(sessionId))
                                       * {
                                       * sessionId = Guid.NewGuid().ToString();
                                       * Context.Session.SetString("SessionID", sessionId);
                                       * }
                                       * sessionId += "|" +*/fileId;
            EditSession editSession = SessionManager.Current.GetSession(sessionId);

            if (editSession == null)
            {
                IWopiFile file = FileProvider.GetWopiFile(fileId);

                //TODO: remove hardcoded action 'Edit'
                if (WopiDiscoverer.RequiresCobalt(file.Extension, WopiActionEnum.Edit))
                {
                    editSession = new CobaltSession(file, sessionId);
                }
                else
                {
                    editSession = new FileSession(file, sessionId);
                }
                SessionManager.Current.AddSession(editSession);
            }

            return(editSession);
        }
        public IEnumerable <Label> GetLabels(Topic topic, ImageLabel image)
        {
            #region validation

            if (topic == null)
            {
                throw new ArgumentNullException(nameof(topic));
            }

            if (image == null)
            {
                throw new ArgumentNullException(nameof(image));
            }

            #endregion

            IEnumerable <Label> labels = FileSession.Execute((fileName, filePath) =>
            {
                if (!FileContainer.ExistsFile(fileName, filePath))
                {
                    return(new List <Label>());
                }

                using (Stream labelFileStream = FileContainer.GetFileStream(fileName, filePath))
                {
                    return(LabelStoreUtil.GetLabelsFromStream(labelFileStream));
                }
            }, image.GetLabelFileName(), GetLabelsPath(topic));

            image.SetLabels(labels);
            return(labels);
        }
        public IEnumerable <Label> GetLabels(Topic topic, ImageLabel imageLabel)
        {
            #region validation

            if (topic == null)
            {
                throw new ArgumentNullException(nameof(topic));
            }

            if (imageLabel == null)
            {
                throw new ArgumentNullException(nameof(imageLabel));
            }

            #endregion

            IEnumerable <Label> labels = FileSession.Execute((fileName, filePath) =>
            {
                if (!FileContainer.ExistsFile(fileName, filePath))
                {
                    return(new List <Label>());
                }

                using (StreamReader streamReader = EncodingUtil.GetStreamReader(FileContainer.GetFileStream(fileName, filePath), Encoding.UTF8))
                {
                    string labelContentJson = streamReader.ReadToEnd();
                    return(JsonConvert.DeserializeObject <IEnumerable <Label> >(labelContentJson));
                }
            }, GetLabelFileName(imageLabel.Url), GetLabelsPath(topic));

            imageLabel.SetLabels(labels);
            return(labels);
        }
Esempio n. 7
0
		private async Task<AbstractEditSession> GetEditSessionAsync(string fileId)
		{
			var sessionId = /*Context.Session.GetString("SessionID");
			if (string.IsNullOrEmpty(sessionId))
			{
				sessionId = Guid.NewGuid().ToString();
				Context.Session.SetString("SessionID", sessionId);
			}
			sessionId += "|" +*/ fileId;
			AbstractEditSession editSession = SessionManager.Current.GetSession(sessionId);

			if (editSession == null)
			{
				IWopiFile file = StorageProvider.GetWopiFile(fileId);

				//TODO: remove hardcoded action 'Edit'
				//TODO: handle all requirements in a generic way (requires="cobalt,containers,update")
				//TODO: http://wopi.readthedocs.io/en/latest/discovery.html#action-requirements
				if (await WopiDiscoverer.RequiresCobaltAsync(file.Extension, WopiActionEnum.Edit))
				{
					editSession = new CobaltSession(file, sessionId);
				}
				else
				{
					editSession = new FileSession(file, sessionId);
				}
				SessionManager.Current.AddSession(editSession);
			}

			return editSession;
		}
Esempio n. 8
0
        // <returns>An instance to a <see cref="FileSave"/> class generated from the <see cref="ScintillaTabbedDocument"/> class instance.</returns>

        /// <summary>
        /// Creates a <see cref="FileSave"/> entity from a given <see cref="ScintillaTabbedDocument"/> document.
        /// </summary>
        /// <param name="document">The document to create a file save from.</param>
        /// <param name="encoding">The encoding of the file save.</param>
        /// <param name="fileSession">The file session.</param>
        /// <param name="isHistory">if set to <c>true</c> the resulting <see cref="FileSave"/> instance is marked as a history file.</param>
        /// <returns>An instance to a <see cref="FileSave"/> modified class.</returns>
        public static FileSave CreateFromTabbedDocument(ScintillaTabbedDocument document, Encoding encoding,
                                                        FileSession fileSession, bool isHistory = false)
        {
            var fileSave = new FileSave
            {
                ExistsInFileSystem = File.Exists(document.FileName),
                FileNameFull       = document.FileName,
                FileName           = Path.GetFileName(document.FileName),
                FilePath           = Path.GetDirectoryName(document.FileName),
                FileSystemModified = File.Exists(document.FileName)
                    ? new FileInfo(document.FileName).LastWriteTime
                    : DateTime.MinValue,
                LexerType       = document.LexerType,
                VisibilityOrder = (int)document.FileTabButton.Tag,
                Session         = ScriptNotepadDbContext.DbContext.FileSessions.FirstOrDefault(f =>
                                                                                               f.SessionName == fileSession.SessionName),
                IsActive                = document.FileTabButton.IsActive,
                IsHistory               = isHistory,
                CurrentCaretPosition    = document.Scintilla.CurrentPosition,
                UseSpellChecking        = true,
                EditorZoomPercentage    = document.ZoomPercentage,
                UseFileSystemOnContents = fileSession.UseFileSystemOnContents,
            };

            fileSave.SetDatabaseModified(DateTime.Now);

            fileSave.SetEncoding(encoding);

            fileSave.SetFileContents(encoding.GetBytes(document.Scintilla.Text), true, false, true);

            ScriptNotepadDbContext.DbContext.FileSaves.Add(fileSave);
            ScriptNotepadDbContext.DbContext.SaveChanges();
            return(fileSave);
        }
Esempio n. 9
0
        /// <summary>
        /// Save list of objectclasses in json-file.
        /// </summary>
        /// <param name="topic">Topic of objectclasses</param>
        /// <param name="objectClasses">List of objectclasses to save</param>
        private void SaveObjectClasses(Topic topic, IEnumerable <ObjectClass> objectClasses)
        {
            FileSession.Execute((fileName, filePath) =>
            {
                string objectclassesAsJson = JsonSerializer.Serialize(objectClasses);
                byte[] newFileContent      = EncodingUtil.GetBytes(objectclassesAsJson);
                FileContainer.CreateFile(fileName, newFileContent, filePath);

                return(true);
            }, "objectclasses.json", GetTopicPath(topic));
        }
Esempio n. 10
0
 /// <summary>
 /// Gets the <see cref="SearchAndReplaceHistory"/> entities by a given limit.
 /// </summary>
 /// <param name="searchAndReplaceSearchType">Type of the search and replace search.</param>
 /// <param name="searchAndReplaceType">Type of the search and replace.</param>
 /// <param name="limit">The limit of how many to entities to get.</param>
 /// <param name="fileSession">The file session.</param>
 /// <returns>IEnumerable&lt;SearchAndReplaceHistory&gt;.</returns>
 public static IEnumerable <SearchAndReplaceHistory> GetEntriesByLimit(
     SearchAndReplaceSearchType searchAndReplaceSearchType, SearchAndReplaceType searchAndReplaceType, int limit,
     FileSession fileSession)
 {
     return(ScriptNotepadDbContext.DbContext
            .SearchAndReplaceHistories
            .Where(f => f.Session.SessionName == fileSession.SessionName &&
                   f.SearchAndReplaceSearchType.HasFlag(searchAndReplaceSearchType) &&
                   f.SearchAndReplaceType == searchAndReplaceType).OrderBy(f => f.Added)
            .Take(limit));
 }
Esempio n. 11
0
        public IEnumerable <Topic> GetTopics()
        {
            return(FileSession.Execute((fileName, filePath) =>
            {
                using (StreamReader streamReader = EncodingUtil.GetStreamReader(FileContainer.GetFileStream(fileName, filePath)))
                {
                    string fileContent = streamReader.ReadToEnd();

                    return JsonConvert.DeserializeObject <IEnumerable <Topic> >(fileContent);
                }
            }, TOPICS_FILE_NAME));
        }
Esempio n. 12
0
        /// <summary>
        /// Loads objectclasses from objectclasses.json-file.
        /// If file doesn't exsists, emtpy list will be returned.
        /// </summary>
        /// <param name="topic">Topic of objectclasses</param>
        /// <returns>List of objectclasses</returns>
        private IEnumerable <ObjectClass> LoadObjectClasses(Topic topic)
        {
            if (!FileContainer.ExistsFile("objectclasses.json", GetTopicPath(topic)))
            {
                return(new List <ObjectClass>());
            }

            return(FileSession.Execute((fileName, filePath) =>
            {
                using (StreamReader streamReader = EncodingUtil.GetStreamReader(FileContainer.GetFileStream(fileName, filePath)))
                {
                    string objectclassesContent = streamReader.ReadToEnd();
                    return JsonConvert.DeserializeObject <IEnumerable <ObjectClass> >(objectclassesContent);
                }
            }, "objectclasses.json", GetTopicPath(topic)));
        }
Esempio n. 13
0
        /// <summary>
        /// Cleanups the recent file list by removing older entries from the list by a given number to keep.
        /// </summary>
        /// <param name="keepMaximum">The maximum number of recent files to keep per session.</param>
        /// <param name="session">The session from which to clean the recent file from.</param>
        /// <returns><c>true</c> a tuple containing the value whether the clean up was successful and the amount of records deleted.</returns>
        public static (bool success, int count) CleanupHistoryList(int keepMaximum, FileSession session) // one could probably make this a bit more complicated..
        {
            try
            {
                var dbContext = ScriptNotepadDbContext.DbContext;

                session =
                    dbContext.FileSessions.FirstOrDefault(f => f.SessionName == session.SessionName);

                var closedCount =
                    dbContext.FileSaves.Count(f => f.IsHistory && f.Session.SessionName == session.SessionName);

                var removeFiles = dbContext.FileSaves
                                  .Where(f => !f.IsHistory && f.Session.SessionName == session.SessionName)
                                  .Select(f => f.FileNameFull);

                dbContext.RecentFiles.RemoveRange(dbContext.RecentFiles.Where(f =>
                                                                              f.Session.SessionName == session.SessionName && removeFiles.Contains(f.FileNameFull)));

                var historyRemoveCount = closedCount - keepMaximum;

                if (historyRemoveCount > 0)
                {
                    var deleted = dbContext.RecentFiles
                                  .OrderByDescending(f => f.ClosedDateTime)
                                  .Take(historyRemoveCount).Count();

                    dbContext.RecentFiles.RemoveRange(dbContext.RecentFiles
                                                      .OrderByDescending(f => f.ClosedDateTime)
                                                      .Take(historyRemoveCount));

                    dbContext.SaveChanges();

                    return(true, deleted);
                }

                return(true, 0);
            }
            catch (Exception ex)
            {
                // log the exception..
                ExceptionLogAction?.Invoke(ex);
                return(false, 0);
            }
        }
        private void pbDeleteSelectedSession_Click(object sender, EventArgs e)
        {
            if (cmbSessions.SelectedItem != null)
            {
                FileSession session = (FileSession)cmbSessions.SelectedItem;

                if (session.Id == 1) // Id == 1 is the default..
                {
                    MessageBoxExtended.Show(
                        DBLangEngine.GetMessage("msgDefaultSessionCanNotDelete",
                                                "The default session can not be deleted.|A message informing that the default session can not be deleted."),
                        DBLangEngine.GetMessage("msgInformation", "Information|A message title describing of some kind information."),
                        MessageBoxButtonsExtended.OK, MessageBoxIcon.Information, ExtendedDefaultButtons.Button1);
                }
                else if (session.SessionName == FormSettings.Settings.CurrentSessionEntity.SessionName)
                {
                    MessageBoxExtended.Show(
                        DBLangEngine.GetMessage("msgCurrentSessionCanNotDelete",
                                                "The currently active session can not be deleted.|A message informing that the currently active session can not be deleted."),
                        DBLangEngine.GetMessage("msgInformation", "Information|A message title describing of some kind information."),
                        MessageBoxButtonsExtended.OK, MessageBoxIcon.Information, ExtendedDefaultButtons.Button1);
                }
                else
                {
                    if (MessageBoxExtended.Show(
                            DBLangEngine.GetMessage("msgConfirmDeleteEntireSession",
                                                    "Please confirm you want to delete an entire session '{0}' from the database. This operation can not be undone. Continue?|A confirmation dialog if the user wishes to delete an entire session from the database. (NO POSSIBILITY TO UNDO!).", session.SessionName),
                            DBLangEngine.GetMessage("msgConfirm", "Confirm|A caption text for a confirm dialog."),
                            MessageBoxButtonsExtended.YesNo, MessageBoxIcon.Question, ExtendedDefaultButtons.Button2) == DialogResultExtended.Yes)
                    {
                        if (FileSessionHelper.DeleteEntireSession(session))
                        {
                            MessageBoxExtended.Show(
                                DBLangEngine.GetMessage("msgSessionDeleteSuccess",
                                                        "The session was successfully deleted.|A message indicating a successful session delete."),
                                DBLangEngine.GetMessage("msgSuccess", "Success|A message indicating a successful operation."),
                                MessageBoxButtonsExtended.OK, MessageBoxIcon.Information, ExtendedDefaultButtons.Button1);
                        }
                    }
                }
            }
        }
Esempio n. 15
0
        /// <summary>
        /// Deletes the older entities with a given limit.
        /// </summary>
        /// <param name="searchAndReplaceSearchType">Type of the search and replace search.</param>
        /// <param name="searchAndReplaceType">Type of the search and replace.</param>
        /// <param name="limit">The limit of how many to entities to keep.</param>
        /// <param name="fileSession">The file session.</param>
        /// <returns><c>true</c> if the operation was successful, <c>false</c> otherwise.</returns>
        public static bool DeleteOlderEntries(SearchAndReplaceSearchType searchAndReplaceSearchType, SearchAndReplaceType searchAndReplaceType, int limit,
                                              FileSession fileSession)
        {
            try
            {
                ScriptNotepadDbContext.DbContext.SearchAndReplaceHistories.RemoveRange(
                    ScriptNotepadDbContext.DbContext.SearchAndReplaceHistories.Where(f =>
                                                                                     f.Session.SessionName == fileSession.SessionName &&
                                                                                     f.SearchAndReplaceSearchType.HasFlag(searchAndReplaceSearchType) &&
                                                                                     f.SearchAndReplaceType == searchAndReplaceType)
                    .Except(GetEntriesByLimit(searchAndReplaceSearchType, searchAndReplaceType, limit,
                                              fileSession)));

                return(true); // success..
            }
            catch (Exception ex)
            {
                // log the exception..
                ExceptionLogAction?.Invoke(ex);
                return(false); // failure..
            }
        }
Esempio n. 16
0
        public static string?SetRandomPath(this FileSession fileSession)
        {
            if (fileSession.TemporaryFilePath == null && fileSession.UseFileSystemOnContents)
            {
                var path = Path.Combine(ApplicationDataDirectory, Path.GetRandomFileName());
                if (!Directory.Exists(path))
                {
                    Directory.CreateDirectory(path);
                }

                fileSession.TemporaryFilePath = path;

                return(path);
            }

            if (!fileSession.UseFileSystemOnContents)
            {
                fileSession.TemporaryFilePath = null;
            }

            return(fileSession.TemporaryFilePath);
        }
Esempio n. 17
0
        /// <summary>
        /// Creates the session menu to a given parent tool strip menu item.
        /// </summary>
        /// <param name="parent">The parent tool strip menu item to create the session menu to.</param>
        /// <param name="currentSession">The currently active session.</param>
        public static void CreateSessionMenu(ToolStripMenuItem parent, FileSession currentSession)
        {
            // first dispose the previous menu..
            DisposeSessionMenu();

            foreach (var session in ScriptNotepadDbContext.DbContext.FileSessions)
            {
                var item = new ToolStripMenuItem
                {
                    Text    = session.SessionName,
                    Tag     = session, CheckOnClick = true,
                    Checked = session.SessionName == currentSession.SessionName,
                };

                item.Click  += SessionMenuItem_Click;
                item.Checked = session.SessionName == currentSession.SessionName;

                CurrentMenu.Add(item);

                parent.DropDownItems.Add(item);
            }
        }
        public IEnumerable <Label> AddLabels(Topic topic, ImageLabel image, IEnumerable <Label> labels)
        {
            #region validation

            if (topic == null)
            {
                throw new ArgumentNullException(nameof(topic));
            }

            if (image == null)
            {
                throw new ArgumentNullException(nameof(image));
            }

            if (labels == null)
            {
                throw new ArgumentNullException(nameof(labels));
            }

            #endregion

            // set id for labels
            foreach (Label label in labels)
            {
                label.Id = labels.GetNext(o => o.Id) + 1;
            }

            FileSession.Execute((fileName, filePath) =>
            {
                image.Labels            = labels.ToList();
                byte[] labelFileContent = image.GetLabelsAsByte();
                FileContainer.CreateFile(fileName, labelFileContent, filePath);

                return(true);
            }, image.GetLabelFileName(), GetLabelsPath(topic));

            return(labels);
        }
        public IEnumerable <Label> CreateLabels(Topic topic, ImageLabel imageLabel)
        {
            #region validation

            if (topic == null)
            {
                throw new ArgumentNullException(nameof(topic));
            }

            if (imageLabel == null)
            {
                throw new ArgumentNullException(nameof(imageLabel));
            }

            #endregion

            // set id for undefined label-ids
            // undefined label id will be lower than 0
            foreach (Label label in imageLabel.Labels)
            {
                if (label.Id < 0)
                {
                    label.Id = imageLabel.Labels.GetNext(o => o.Id);
                }
            }

            FileSession.Execute((fileName, filePath) =>
            {
                string labelssAsJson  = JsonConvert.SerializeObject(imageLabel.Labels);
                byte[] newFileContent = EncodingUtil.GetBytes(labelssAsJson, Encoding.UTF8);
                FileContainer.CreateFile(fileName, newFileContent, filePath);

                return(true);
            }, GetLabelFileName(imageLabel.Url), GetLabelsPath(topic));

            return(imageLabel.Labels);
        }
Esempio n. 20
0
        /// <summary>
        /// Loads objectclasses from objectclasses.json-file.
        /// If file doesn't exsists, emtpy list will be returned.
        /// </summary>
        /// <param name="topic">Topic of objectclasses</param>
        /// <returns>List of objectclasses</returns>
        private IEnumerable <ObjectClass> LoadObjectClasses(Topic topic)
        {
            if (!FileContainer.ExistsFile("objectclasses.json", GetTopicPath(topic)))
            {
                return(new List <ObjectClass>());
            }

            var objectClasses = FileSession.Execute((fileName, filePath) =>
            {
                using (StreamReader streamReader = EncodingUtil.GetStreamReader(FileContainer.GetFileStream(fileName, filePath)))
                {
                    string objectclassesContent = streamReader.ReadToEnd();
                    return(JsonSerializer.Deserialize <IEnumerable <ObjectClass> >(objectclassesContent));
                }
            }, "objectclasses.json", GetTopicPath(topic));

            // set topic reference id
            foreach (ObjectClass objectClass in objectClasses)
            {
                objectClass.TopicId = topic.Id;
            }

            return(objectClasses);
        }
Esempio n. 21
0
        /// <summary>
        /// Adds or updates a <see cref="SearchAndReplaceHistory"/> entity.
        /// </summary>
        /// <param name="text">The text used for searching or replacing.</param>
        /// <param name="searchAndReplaceSearchType">Type of the search and replace search.</param>
        /// <param name="searchAndReplaceType">Type of the search and replace.</param>
        /// <param name="caseSensitive">if set to <c>true</c> the search or replace is case sensitive.</param>
        /// <param name="fileSession">The file session.</param>
        /// <returns>SearchAndReplaceHistory.</returns>
        public static SearchAndReplaceHistory AddOrUpdateAndReplaceHistory(string text,
                                                                           SearchAndReplaceSearchType searchAndReplaceSearchType, SearchAndReplaceType searchAndReplaceType,
                                                                           bool caseSensitive, FileSession fileSession)
        {
            try
            {
                var context = ScriptNotepadDbContext.DbContext;

                if (!context.SearchAndReplaceHistories.Any(f =>
                                                           f.SearchOrReplaceText == text &&
                                                           f.SearchAndReplaceSearchType.HasFlag(searchAndReplaceSearchType) &&
                                                           f.SearchAndReplaceType == searchAndReplaceType &&
                                                           f.CaseSensitive == caseSensitive &&
                                                           f.Session.SessionName == fileSession.SessionName))
                {
                    var result = new SearchAndReplaceHistory
                    {
                        SearchOrReplaceText        = text,
                        SearchAndReplaceSearchType = searchAndReplaceSearchType,
                        SearchAndReplaceType       = searchAndReplaceType,
                        CaseSensitive = caseSensitive,
                        Session       = fileSession,
                    };

                    result = context.SearchAndReplaceHistories.Add(result).Entity;
                    context.SaveChanges();
                    return(result);
                }

                return(context.SearchAndReplaceHistories.FirstOrDefault(f =>
                                                                        f.SearchOrReplaceText == text &&
                                                                        f.SearchAndReplaceSearchType.HasFlag(searchAndReplaceSearchType) &&
                                                                        f.SearchAndReplaceType == searchAndReplaceType &&
                                                                        f.CaseSensitive == caseSensitive &&
                                                                        f.Session.SessionName == fileSession.SessionName)); // success..
            }
            catch (Exception ex)
            {
                // log the exception..
                ExceptionLogAction?.Invoke(ex);
                return(null); // failure..
            }
        }
Esempio n. 22
0
        private void ProcessRequest(IAsyncResult result)
        {
            try
            {
                Console.WriteLine("start...");
                HttpListener        listener = (HttpListener)result.AsyncState;
                HttpListenerContext context  = listener.EndGetContext(result);
                try
                {
                    //Console.WriteLine("1111...");
                    Console.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.ffff") + " " + context.Request.HttpMethod + @" " + context.Request.Url.AbsolutePath);
                    var stringarr    = context.Request.Url.AbsolutePath.Split('/');
                    var access_token = context.Request.QueryString["access_token"];

                    if (stringarr.Length < 3 || access_token == null)
                    {
                        Console.WriteLine(@"Invalid request");
                        ErrorResponse(context, @"Invalid request parameter");
                        m_listener.BeginGetContext(ProcessRequest, m_listener);
                        return;
                    }

                    //todo:


                    documentUtil = new DocumentUtil();
                    //string fileId = stringarr[3];
                    var docInfo  = documentUtil.GetInfo(stringarr[3]);
                    var filename = docInfo.fileName;
                    //Stream gridfsStream = GetFileById(fileId);
                    //StreamToFile(gridfsStream, filename);


                    //use filename as session id just test, recommend use file id and lock id as session id
                    EditSession editSession = CobaltSessionManager.Instance.GetSession(filename);
                    if (editSession == null)
                    {
                        //Console.WriteLine("2222...");
                        var fileExt = filename.Substring(filename.LastIndexOf('.') + 1);
                        if (fileExt.ToLower().Contains("xlsx"))
                        {
                            editSession = new FileSession(filename, docInfo.filePath, docInfo.author, docInfo.loginUser,
                                                          docInfo.mail, false);
                        }
                        else
                        {
                            editSession = new CobaltSession(filename, docInfo.filePath,
                                                            docInfo.author, docInfo.loginUser, docInfo.mail, false);
                        }
                        CobaltSessionManager.Instance.AddSession(editSession);
                    }

                    if (stringarr.Length == 4 && context.Request.HttpMethod.Equals(@"GET"))
                    {
                        //Console.WriteLine("4444...");
                        //request of checkfileinfo, will be called first
                        using (var memoryStream = new MemoryStream())
                        {
                            var json = new DataContractJsonSerializer(typeof(WopiCheckFileInfo));
                            json.WriteObject(memoryStream, editSession.GetCheckFileInfo(access_token));
                            memoryStream.Flush();
                            memoryStream.Position = 0;
                            StreamReader streamReader = new StreamReader(memoryStream);
                            var          jsonResponse = Encoding.UTF8.GetBytes(streamReader.ReadToEnd());

                            context.Response.AddHeader("Cache-Control", "no-cache");
                            context.Response.AddHeader("Pragma", "no-cache");
                            context.Response.AddHeader("Expires", "-1");
                            context.Response.ContentType     = @"application/json";
                            context.Response.ContentLength64 = jsonResponse.Length;
                            context.Response.OutputStream.Write(jsonResponse, 0, jsonResponse.Length);
                            context.Response.OutputStream.Flush();
                            context.Response.StatusCode = (int)HttpStatusCode.OK;

                            context.Response.Close();
                        }
                    }
                    else if (stringarr.Length == 5 && stringarr[4].Equals(@"contents"))
                    {
                        //Console.WriteLine("5555...");
                        // get and put file's content, only for xlsx and pptx
                        if (context.Request.HttpMethod.Equals(@"POST"))
                        {
                            var ms = new MemoryStream();
                            context.Request.InputStream.CopyTo(ms);
                            editSession.Save(ms.ToArray());
                            context.Response.ContentLength64 = 0;
                            context.Response.ContentType     = @"text/html";
                        }
                        else
                        {
                            var content = editSession.GetFileContent();
                            context.Response.ContentType     = @"application/octet-stream";
                            context.Response.ContentLength64 = content.Length;
                            context.Response.OutputStream.Write(content, 0, content.Length);
                        }
                        context.Response.StatusCode = (int)HttpStatusCode.OK;
                        context.Response.Close();
                    }
                    else if (context.Request.HttpMethod.Equals(@"POST") &&
                             context.Request.Headers["X-WOPI-Override"].Equals("COBALT"))
                    {
                        //Console.WriteLine("6666...");
                        //cobalt, for docx and pptx
                        var ms = new MemoryStream();
                        context.Request.InputStream.CopyTo(ms);
                        AtomFromByteArray atomRequest  = new AtomFromByteArray(ms.ToArray());
                        RequestBatch      requestBatch = new RequestBatch();

                        Object          ctx;
                        ProtocolVersion protocolVersion;

                        requestBatch.DeserializeInputFromProtocol(atomRequest, out ctx, out protocolVersion);
                        editSession.ExecuteRequestBatch(requestBatch);

                        foreach (Request request in requestBatch.Requests)
                        {
                            if (request.GetType() == typeof(PutChangesRequest) &&
                                request.PartitionId == FilePartitionId.Content)
                            {
                                editSession.Save();
                            }
                        }
                        var response = requestBatch.SerializeOutputToProtocol(protocolVersion);

                        context.Response.Headers.Add("X-WOPI-CorellationID", context.Request.Headers["X-WOPI-CorrelationID"]);
                        context.Response.Headers.Add("request-id", context.Request.Headers["X-WOPI-CorrelationID"]);
                        context.Response.ContentType     = @"application/octet-stream";
                        context.Response.ContentLength64 = response.Length;
                        context.Response.StatusCode      = (int)HttpStatusCode.OK;
                        response.CopyTo(context.Response.OutputStream);
                        context.Response.Close();
                    }
                    else if (context.Request.HttpMethod.Equals(@"POST") &&
                             (context.Request.Headers["X-WOPI-Override"].Equals("LOCK") ||
                              context.Request.Headers["X-WOPI-Override"].Equals("UNLOCK") ||
                              context.Request.Headers["X-WOPI-Override"].Equals("REFRESH_LOCK"))
                             )
                    {
                        //Console.WriteLine("7777...");
                        //lock, for xlsx and pptx
                        context.Response.ContentLength64 = 0;
                        context.Response.ContentType     = @"text/html";
                        context.Response.StatusCode      = (int)HttpStatusCode.OK;
                        context.Response.Close();
                    }
                    else
                    {
                        Console.WriteLine(@"Invalid request parameters");
                        ErrorResponse(context, @"Invalid request cobalt parameter");
                    }

                    Console.WriteLine("ok...");
                }
                catch (Exception ex)
                {
                    Console.WriteLine(@"process request exception:" + ex.Message);
                }
                m_listener.BeginGetContext(ProcessRequest, m_listener);
            }
            catch (Exception ex)
            {
                Console.WriteLine(@"get request context:" + ex.Message);
                return;
            }
        }
Esempio n. 23
0
        /// <summary>
        /// Creates a recent files menu to a given parent menu.
        /// </summary>
        /// <param name="menuItem">The menu item to add the recent files list.</param>
        /// <param name="session">A name of the session to which the history documents belong to.</param>
        /// <param name="maxCount">Maximum count of recent file entries to add to the given <paramref name="menuItem"/>.</param>
        /// <param name="addMenuOpenAll">A flag indicating whether the menu should contain an item to open all recent files.</param>
        /// <param name="hideItems">A list of tool strip items to hide if there are no recent files.</param>
        public static void CreateRecentFilesMenu(ToolStripMenuItem menuItem, FileSession session,
                                                 int maxCount, bool addMenuOpenAll, params ToolStripItem[] hideItems)
        {
            // dispose of the previous menu items..
            DisposeRecentFilesMenu(menuItem);

            // get the recent files from the database..
            var recentFiles = ScriptNotepadDbContext.DbContext.RecentFiles
                              .OrderByDescending(f => f.ClosedDateTime).Where(f =>
                                                                              f.Session.SessionName == session.SessionName && !ScriptNotepadDbContext.DbContext.FileSaves.Any(s =>
                                                                                                                                                                              !s.IsHistory && s.Session.SessionName == f.Session.SessionName &&
                                                                                                                                                                              s.FileNameFull == f.FileNameFull)).Take(maxCount);

            if (addMenuOpenAll)
            {
                List <RecentFile> recentFilesAll = recentFiles.ToList();

                if (recentFilesAll.Count > 1)
                {
                    // create a menu item for all the recent files..
                    DataToolStripMenuItem menuItemRecentFile =
                        new DataToolStripMenuItem(
                            string.IsNullOrWhiteSpace(MenuOpenAllRecentText)
                                ? "Open all recent files..."
                                : MenuOpenAllRecentText)
                    {
                        Data = recentFilesAll
                    };

                    // set the user given additional data for the menu item..

                    // subscribe the click event..
                    menuItemRecentFile.Click += MenuItemRecentFile_Click;

                    // add the menu item to the recent files menu..
                    menuItem.DropDownItems.Add(menuItemRecentFile);

                    // add a separator menu item to the recent files menu..
                    menuItem.DropDownItems.Add(new ToolStripSeparator());
                }
            }

            // loop through the results..
            foreach (var recentFile in recentFiles)
            {
                // create a menu item for the encoding..
                DataToolStripMenuItem menuItemRecentFile =
                    new DataToolStripMenuItem(recentFile.ToString())
                {
                    Data = recentFile
                };

                // set the user given additional data for the menu item..

                // subscribe the click event..
                menuItemRecentFile.Click += MenuItemRecentFile_Click;

                // add the menu item to the recent files menu..
                menuItem.DropDownItems.Add(menuItemRecentFile);
            }

            // the recent file menu should only be visible if there are any drop down items..
            menuItem.Visible = menuItem.DropDownItems.Count > 0;

            // hide or show the items which are "depended" of the visibility of the
            // recent files menu..
            foreach (ToolStripItem item in hideItems)
            {
                item.Visible = menuItem.DropDownItems.Count > 0;
            }
        }
        /// <summary>
        /// Deletes the older <see cref="MiscellaneousTextEntry"/> entries by a given limit to keep.
        /// </summary>
        /// <param name="miscellaneousTextType">Type of the miscellaneous text.</param>
        /// <param name="limit">The limit of how many to entries to keep.</param>
        /// <param name="fileSession">The file session.</param>
        /// <returns><c>true</c> if the operation was successful, <c>false</c> otherwise.</returns>
        public static bool DeleteOlderEntries(MiscellaneousTextType miscellaneousTextType, int limit, FileSession fileSession)
        {
            try
            {
                ScriptNotepadDbContext.DbContext.MiscellaneousTextEntries.RemoveRange(
                    ScriptNotepadDbContext.DbContext.MiscellaneousTextEntries.Where(f => f.Session.SessionName == fileSession.SessionName)
                    .Except(GetEntriesByLimit(miscellaneousTextType, limit, fileSession)));

                return(true); // success..
            }
            catch (Exception ex)
            {
                // log the exception..
                ExceptionLogAction?.Invoke(ex);
                return(false); // failure..
            }
        }
        /// <summary>
        /// Adds an unique miscellaneous text value to the database.
        /// </summary>
        /// <param name="miscText">The misc text.</param>
        /// <param name="miscellaneousTextType">Type of the miscellaneous text.</param>
        /// <param name="fileSession">The file session.</param>
        /// <returns>An instance to a <see cref="MiscellaneousTextEntry"/> if successful, <c>null</c> otherwise.</returns>
        public static MiscellaneousTextEntry AddUniqueMiscellaneousText(string miscText,
                                                                        MiscellaneousTextType miscellaneousTextType, FileSession fileSession)
        {
            try
            {
                var context = ScriptNotepadDbContext.DbContext;

                if (!context.MiscellaneousTextEntries.Any(f =>
                                                          f.TextValue == miscText && f.TextType == miscellaneousTextType && f.Session.SessionName == fileSession.SessionName))
                {
                    var result = new MiscellaneousTextEntry
                    {
                        Session   = fileSession,
                        TextType  = miscellaneousTextType,
                        TextValue = miscText
                    };

                    result = context.MiscellaneousTextEntries.Add(result).Entity;
                    context.SaveChanges();
                    return(result);
                }

                return(context.MiscellaneousTextEntries.FirstOrDefault(f =>
                                                                       f.TextValue == miscText && f.TextType == miscellaneousTextType &&
                                                                       f.Session.SessionName == fileSession.SessionName)); // success..
            }
            catch (Exception ex)
            {
                // log the exception..
                ExceptionLogAction?.Invoke(ex);
                return(null); // failure..
            }
        }
 /// <summary>
 /// Gets the <see cref="MiscellaneousTextEntry"/> entries by a given limit.
 /// </summary>
 /// <param name="miscellaneousTextType">Type of the miscellaneous text.</param>
 /// <param name="limit">The limit of how many to entries to get.</param>
 /// <param name="fileSession">The file session.</param>
 /// <returns>System.Collections.Generic.IEnumerable&lt;ScriptNotepad.Database.Entity.Entities.MiscellaneousTextEntry&gt;.</returns>
 public static IEnumerable <MiscellaneousTextEntry> GetEntriesByLimit(MiscellaneousTextType miscellaneousTextType, int limit, FileSession fileSession)
 {
     return(ScriptNotepadDbContext.DbContext
            .MiscellaneousTextEntries
            .Where(f => f.Session.SessionName == fileSession.SessionName && f.TextType == miscellaneousTextType)
            .OrderBy(f => f.Added)
            .Take(limit));
 }
Esempio n. 27
0
        private void ProcessRequest(IAsyncResult result)
        {
            try
            {
                logger.Info($"监听中......");
                var listener = (HttpListener)result.AsyncState;
                var context  = listener.EndGetContext(result);
                try
                {
                    var listStr = new List <string>();
                    foreach (var item in context.Request.Headers.AllKeys)
                    {
                        listStr.Add(context.Request.Headers[item]);
                    }
                    logger.Info($"监听内容:HTTP请求方法为【{context.Request.HttpMethod}】,HTTP请求绝对路径为【{context.Request.Url.AbsolutePath}】,HTTP请求头为【{JsonConvert.SerializeObject(context.Request.Headers.AllKeys)}】值为【{JsonConvert.SerializeObject(listStr)}】");
                    var stringarr    = context.Request.Url.AbsolutePath.Split('/');
                    var access_token = context.Request.QueryString["access_token"];

                    if (stringarr.Length < 3 || access_token == null)
                    {
                        logger.Info($"请求参数无效,参数为:{stringarr},token参数为:{access_token}");
                        ErrorResponse(context, @"无效的请求参数");
                        m_listener.BeginGetContext(new AsyncCallback(ProcessRequest), m_listener);
                        return;
                    }

                    documentUtil = new DocumentUtil();
                    //string fileId = stringarr[3];
                    var docInfo = documentUtil.GetInfo(stringarr[3]);
                    logger.Info($"文件信息为:{JsonConvert.SerializeObject(docInfo)}");
                    var filename = docInfo.fileName;

                    EditSession editSession = CobaltSessionManager.Instance.GetSession(docInfo.uuid);
                    if (editSession == null)
                    {
                        var fileExt = filename.Substring(filename.LastIndexOf('.') + 1);
                        if (fileExt.ToLower().Contains("xlsx"))
                        {
                            editSession = new FileSession(docInfo.uuid, docInfo.filePath, docInfo.loginUser, docInfo.author, false);
                        }
                        else
                        {
                            editSession = new CobaltSession(docInfo.uuid, docInfo.filePath, docInfo.loginUser, docInfo.author, false);
                        }
                        CobaltSessionManager.Instance.AddSession(editSession);
                    }

                    if (stringarr.Length == 4 && context.Request.HttpMethod.Equals(@"GET"))
                    {
                        using (var memoryStream = new MemoryStream())
                        {
                            var json = new DataContractJsonSerializer(typeof(WopiCheckFileInfo));
                            json.WriteObject(memoryStream, editSession.GetCheckFileInfo(access_token));
                            memoryStream.Flush();
                            memoryStream.Position = 0;
                            StreamReader streamReader = new StreamReader(memoryStream);
                            var          jsonResponse = Encoding.UTF8.GetBytes(streamReader.ReadToEnd());

                            context.Response.AddHeader("Cache-Control", "no-cache");
                            context.Response.AddHeader("Pragma", "no-cache");
                            context.Response.AddHeader("Expires", "-1");
                            context.Response.ContentType     = @"application/json";
                            context.Response.ContentLength64 = jsonResponse.Length;
                            context.Response.OutputStream.Write(jsonResponse, 0, jsonResponse.Length);
                            context.Response.OutputStream.Flush();
                            context.Response.StatusCode = (int)HttpStatusCode.OK;

                            context.Response.Close();
                        }
                    }
                    else if (stringarr.Length == 5 && stringarr[4].Equals(@"contents"))
                    {
                        if (context.Request.HttpMethod.Equals(@"POST"))
                        {
                            logger.Info($"进入contents方法,调用了保存。");

                            var ms = new MemoryStream();
                            context.Request.InputStream.CopyTo(ms);
                            editSession.Save(ms.ToArray());
                            context.Response.ContentLength64 = 0;
                            context.Response.ContentType     = @"text/html";
                            context.Response.StatusCode      = (int)HttpStatusCode.OK;
                        }
                        else
                        {
                            var content = editSession.GetFileContent();
                            context.Response.ContentType     = @"application/octet-stream";
                            context.Response.ContentLength64 = content.Length;
                            context.Response.OutputStream.Write(content, 0, content.Length);
                            context.Response.OutputStream.Flush();
                        }
                        //context.Response.StatusCode = (int)HttpStatusCode.OK;
                        context.Response.Close();
                    }
                    else if (context.Request.HttpMethod.Equals(@"POST") &&
                             context.Request.Headers["X-WOPI-Override"].Equals("COBALT"))
                    {
                        var ms = new MemoryStream();
                        context.Request.InputStream.CopyTo(ms);
                        AtomFromByteArray atomRequest  = new AtomFromByteArray(ms.ToArray());
                        RequestBatch      requestBatch = new RequestBatch();

                        Object          ctx;
                        ProtocolVersion protocolVersion;

                        requestBatch.DeserializeInputFromProtocol(atomRequest, out ctx, out protocolVersion);
                        editSession.ExecuteRequestBatch(requestBatch);

                        foreach (Request request in requestBatch.Requests)
                        {
                            if (request.GetType() == typeof(PutChangesRequest) &&
                                request.PartitionId == FilePartitionId.Content)
                            {
                                editSession.Save();
                                editSession.fileinfo = new FileInfo(docInfo.filePath);
                            }
                        }
                        var response = requestBatch.SerializeOutputToProtocol(protocolVersion);

                        context.Response.Headers.Add("X-WOPI-CorellationID", context.Request.Headers["X-WOPI-CorrelationID"]);
                        context.Response.Headers.Add("request-id", context.Request.Headers["X-WOPI-CorrelationID"]);
                        context.Response.ContentType     = @"application/octet-stream";
                        context.Response.ContentLength64 = response.Length;
                        context.Response.StatusCode      = (int)HttpStatusCode.OK;
                        response.CopyTo(context.Response.OutputStream);
                        context.Response.Close();
                    }
                    else if (context.Request.HttpMethod.Equals(@"POST") &&
                             (context.Request.Headers["X-WOPI-Override"].Equals("LOCK") ||
                              context.Request.Headers["X-WOPI-Override"].Equals("UNLOCK") ||
                              context.Request.Headers["X-WOPI-Override"].Equals("REFRESH_LOCK"))
                             )
                    {
                        context.Response.ContentLength64 = 0;
                        context.Response.ContentType     = @"text/html";
                        context.Response.StatusCode      = (int)HttpStatusCode.OK;
                        context.Response.Close();
                    }
                    else
                    {
                        logger.Info($"请求参数无效,参数为:{stringarr},token参数为:{access_token}");
                        ErrorResponse(context, @"无效的请求参数");
                    }
                    logger.Info($"当前请求处理完成...");
                }
                catch (Exception ex)
                {
                    logger.Error($"请求处理发生异常:{ex.Message}");
                }
                m_listener.BeginGetContext(new AsyncCallback(ProcessRequest), m_listener);
            }
            catch (Exception ex)
            {
                logger.Error($"获取请求时发生异常:{ex.Message}");
                return;
            }
        }