Пример #1
0
        /// <summary>
        /// React on the event that a view has been closed
        /// </summary>
        /// <param name="sender">The view that has been closed.</param>
        /// <param name="e">The event's arguments.</param>
        public void OnViewClosed(IView sender, EventArgs e)
        {
            try
            {
                if (sender != null && this.viewCollection.Contains(sender))
                {
                    // the view belongs to this document!
                    this.viewCollection.Remove(sender);
                    this.viewControllerList.Remove(sender.ViewController);
                    if (this.viewCollection.Count == 0)
                    {
                        // the last view has been closed
                        // let this document and all associated data vanish
                        sender.Close();
                        System.Diagnostics.Debug.Assert(this.viewControllerList.Count == 0, "No Views in the List");
                        this.viewCollection     = null;
                        this.viewControllerList = null;
                        AppContext.DocumentList.Remove(this);
                        AppContext.ViewClosed -= this.OnViewClosed;
                        this.docContent        = null;
                        this.docObjects        = null;
                        this.selectedObjects   = null;
                        this.docName           = string.Empty;
                        this.fileName          = string.Empty;

                        GC.Collect(); // this a justifiable use of GC.Collect() since the last view of an document is closed and rather big amounts of data being freed.
                    }
                }
            }
            catch (Exception ex)
            {
                Util.ReportException(ex);
            }
        }
Пример #2
0
        private void Setup()
        {
            SessionhasAdminRights = IsUserAdministrator();

            try {
                AutoUpdater.ParseUpdateInfoEvent += AutoUpdaterOnParseUpdateInfoEvent;
                AutoUpdater.Start("https://mappingtools.seira.moe/current/updater.json");
            }
            catch (Exception ex) {
                Console.WriteLine(ex.Message);
            }

            try {
                Directory.CreateDirectory(AppDataPath);
                Directory.CreateDirectory(ExportPath);
            }
            catch (Exception ex) {
                ex.Show();
            }

            Views = new ViewCollection(); // Make a ViewCollection object
            ToolsMenu.ItemsSource = ViewCollection.GetAllToolTypes().Where(o => o.GetCustomAttribute <HiddenToolAttribute>() == null).Select(o => {
                var name = ViewCollection.GetName(o);
                var item = new MenuItem {
                    Header = "_" + name, ToolTip = $"Open {name}."
                };
                item.Click += ViewSelectMenuItemOnClick;
                return(item);
            }).OrderBy(o => o.Header);
        }
Пример #3
0
        private ViewCollection ReadViewCollection()
        {
            var viewFile = new FileInfo(Path.Combine(StateFile.Directory.FullName, ViewDefinitionFile));

            using (var reader = new StreamReader(viewFile.FullName, Encoding.UTF8))
                return(ViewCollection.FromJson(reader.ReadToEnd()));
        }
        /// <summary>
        /// Configure XML Code of List View Web Part
        /// </summary>
        /// <param name="sitePageLib">SharePoint List of matter library</param>
        /// <param name="clientContext">SharePoint Client Context</param>
        /// <param name="objFileInfo">Object of FileCreationInformation</param>
        /// <param name="client">Client object containing Client data</param>
        /// <param name="matter">Matter object containing Matter data</param>
        /// <param name="titleUrl">Segment of URL</param>
        /// <returns>Configured ListView Web Part</returns>
        internal static string ConfigureListViewWebPart(List sitePageLib, ClientContext clientContext, FileCreationInformation objFileInfo, Client client, Matter matter, string titleUrl)
        {
            string listViewWebPart = Constants.ListviewWebpart;

            Uri            uri      = new Uri(client.ClientUrl);
            ViewCollection viewColl = sitePageLib.Views;

            clientContext.Load(
                viewColl,
                views => views.Include(
                    view => view.Title,
                    view => view.Id));
            clientContext.ExecuteQuery();
            string viewName = string.Empty;

            foreach (View view in viewColl)
            {
                viewName = view.Id.ToString();
                break;
            }

            viewName = string.Format(CultureInfo.InvariantCulture, "{0}{1}{2}", Constants.OpeningCurlyBrace, viewName, Constants.ClosingCurlyBrace);

            listViewWebPart = string.Format(CultureInfo.InvariantCulture, listViewWebPart, sitePageLib.Id.ToString(), titleUrl, string.Format(CultureInfo.InvariantCulture, "{0}{1}{2}", Constants.OpeningCurlyBrace, sitePageLib.Id.ToString(), Constants.ClosingCurlyBrace), viewName, string.Format(CultureInfo.InvariantCulture, "{0}{1}{2}{3}{4}", uri.AbsolutePath, Constants.Backslash, matter.MatterName, Constants.Backslash, objFileInfo.Url));

            return(listViewWebPart);
        }
Пример #5
0
        [InlineData(10000)] // expected failure: same time and length
        public void GetOrAdd_UsesFilesFromCache_IfTimestampDiffers_ButContentAndLengthAreTheSame(long fileTimeUTC)
        {
            // Arrange
            var instance   = new RuntimeCompileIdentical();
            var length     = Encoding.UTF8.GetByteCount(instance.Content);
            var collection = new ViewCollection();
            var fileSystem = new TestFileSystem();
            var cache      = new CompilerCache(new[] { new ViewCollection() }, fileSystem);

            var fileInfo = new TestFileInfo
            {
                Length       = length,
                LastModified = DateTime.FromFileTimeUtc(fileTimeUTC),
                Content      = instance.Content
            };

            var runtimeFileInfo = new RelativeFileInfo(fileInfo, "ab");

            var precompiledContent = new PreCompile().Content;
            var razorFileInfo      = new RazorFileInfo
            {
                FullTypeName = typeof(PreCompile).FullName,
                Hash         = RazorFileHash.GetHash(GetMemoryStream(precompiledContent)),
                LastModified = DateTime.FromFileTimeUtc(10000),
                Length       = Encoding.UTF8.GetByteCount(precompiledContent),
                RelativePath = "ab",
            };

            // Act
            var actual = cache.GetOrAdd(runtimeFileInfo,
                                        compile: _ => { throw new Exception("Shouldn't be called."); });

            // Assert
            Assert.Equal(typeof(PreCompile), actual.CompiledType);
        }
Пример #6
0
        public void GetOrAdd_IgnoresCachedValue_IfGlobalFileWasChangedSinceCacheWasCreated(
            RazorFileInfo viewStartRazorFileInfo, IFileInfo globalFileInfo)
        {
            // Arrange
            var expectedType          = typeof(RuntimeCompileDifferent);
            var lastModified          = DateTime.UtcNow;
            var viewStartLastModified = DateTime.UtcNow;
            var content  = "some content";
            var fileInfo = new TestFileInfo
            {
                Length       = 1020,
                Content      = content,
                LastModified = lastModified,
                PhysicalPath = "Views\\home\\index.cshtml"
            };

            var fileProvider = new TestFileProvider();

            fileProvider.AddFile(fileInfo.PhysicalPath, fileInfo);
            fileProvider.AddFile(viewStartRazorFileInfo.RelativePath, globalFileInfo);
            var viewCollection = new ViewCollection();
            var cache          = new CompilerCache(new[] { viewCollection }, TestLoadContext, fileProvider);

            // Act
            var result = cache.GetOrAdd(fileInfo.PhysicalPath,
                                        compile: _ => CompilationResult.Successful(expectedType));

            // Assert
            Assert.NotSame(CompilerCacheResult.FileNotFound, result);
            var actual = result.CompilationResult;

            Assert.NotNull(actual);
            Assert.Equal(expectedType, actual.CompiledType);
        }
Пример #7
0
        private void AddContainerViews()
        {
            FrameLayout v = new FrameLayout(Context);

            ViewCollection.Add(v);
            AddView(v);
        }
        /// <summary>
        /// Process views.
        /// </summary>
        /// <param name="views">Object to process.</param>
        public void Process(ViewCollection views)
        {
            new { views }.AsArg().Must().NotBeNull();

            if (views.Count > 0)
            {
                this.documentGenerator.AddEntry("VIEWS", 16, true);
            }

            this.documentGenerator.Indent();
            foreach (View view in views)
            {
                if (!view.IsSystemObject)
                {
                    string viewName = view.Name;
                    this.databaseDocumenter.Document(view);
                    ScriptAndWriteToFile(view, this.viewPath, FileExtensionView);

                    this.Process(view.Columns, viewName);
                    this.Process(view.Indexes, viewName, this.viewPath);
                    this.Process(view.Triggers, viewName, this.viewPath);
                }
            }

            this.documentGenerator.Undent();
        }
Пример #9
0
 public PackageController(IThreadDispatcher threadDispatcher, ICommandDispatcher commandDispatcher, IQueryDispatcher queryDispatcher, ViewCollection views)
 {
     _views = views;
     _views.SetController(this);
     _commandDispatcher = commandDispatcher;
     _queryDispatcher   = queryDispatcher;
     _threadDispatcher  = threadDispatcher;
 }
Пример #10
0
        /// <summary>
        /// Constructs a new instance of <see cref="HttpReceiverContext"/>
        /// with the default settings.
        /// </summary>
        public HttpReceiverContext()
        {
            HttpsPort = 443;

            Views              = new ViewCollection();
            MimeTypes          = MimeTypeDictionary.CreateDefault();
            ContentDirectories = new List <ContentDirectory>();
        }
Пример #11
0
		public View ()
		{
			_subviews = new ViewCollection (this);
			_readOnlySubviews = new ReadOnlyCollection<View> (_subviews);

			BackgroundColor = Color.Transparent;
			IsVisible = true;
		}
Пример #12
0
        public override void InitializeControl()
        {
            base.InitializeControl();
            //Init banded view and make it the main view
            BandedGridView bandedView = InitializeBandedGridView(GridViewMain);

            MainView = bandedView;
            ViewCollection.AddRange(new BaseView[] { bandedView });
        }
Пример #13
0
        public void GetOrAdd_IgnoresCachedValueIfFileIsIdentical_ButViewStartWasDeletedSinceCacheWasCreated()
        {
            // Arrange
            var expectedType = typeof(RuntimeCompileDifferent);
            var lastModified = DateTime.UtcNow;
            var fileSystem   = new TestFileSystem();

            var viewCollection  = new ViewCollection();
            var precompiledView = viewCollection.FileInfos[0];

            precompiledView.RelativePath = "Views\\Index.cshtml";
            var viewFileInfo = new TestFileInfo
            {
                Content      = new PreCompile().Content,
                LastModified = precompiledView.LastModified,
                PhysicalPath = precompiledView.RelativePath
            };

            fileSystem.AddFile(viewFileInfo.PhysicalPath, viewFileInfo);

            var viewStartFileInfo = new TestFileInfo
            {
                PhysicalPath = "Views\\_ViewStart.cshtml",
                Content      = "viewstart-content",
                LastModified = lastModified
            };
            var viewStart = new RazorFileInfo
            {
                FullTypeName = typeof(RuntimeCompileIdentical).FullName,
                RelativePath = viewStartFileInfo.PhysicalPath,
                LastModified = viewStartFileInfo.LastModified,
                Hash         = RazorFileHash.GetHash(viewStartFileInfo),
                Length       = viewStartFileInfo.Length
            };

            fileSystem.AddFile(viewStartFileInfo.PhysicalPath, viewStartFileInfo);

            viewCollection.Add(viewStart);
            var cache    = new CompilerCache(new[] { viewCollection }, fileSystem);
            var fileInfo = new RelativeFileInfo(viewFileInfo, viewFileInfo.PhysicalPath);

            // Act 1
            var actual1 = cache.GetOrAdd(fileInfo,
                                         compile: _ => { throw new Exception("should not be called"); });

            // Assert 1
            Assert.Equal(typeof(PreCompile), actual1.CompiledType);

            // Act 2
            fileSystem.DeleteFile(viewStartFileInfo.PhysicalPath);
            var actual2 = cache.GetOrAdd(fileInfo,
                                         compile: _ => CompilationResult.Successful(expectedType));

            // Assert 2
            Assert.Equal(expectedType, actual2.CompiledType);
        }
Пример #14
0
        public HtmlEngine(ViewCollection views)
        {
            this.views = views;

            RemoveComments           = true;
            VariableNotFoundBehavior = VariableNotFoundBehavior.Source;

            conditionalBlock = new ConditionalBlock(this);
            eachBlock        = new EachBlock(this);
        }
Пример #15
0
        private void Setup()
        {
            SessionhasAdminRights = IsUserAdministrator();

            try {
                Task.Run(async() => {
                    var hasUpdate = await _updateManager.FetchUpdateAsync();

                    if (!hasUpdate)
                    {
                        return;
                    }

                    var thread = new Thread(() => {
                        var updaterWindow = new UpdaterWindow(_updateManager)
                        {
                            ShowActivated = true
                        };

                        updaterWindow.Show();

                        updaterWindow.StartUpdateProcess();

                        System.Windows.Threading.Dispatcher.Run();
                    });

                    thread.SetApartmentState(ApartmentState.STA);
                    thread.Start();
                });
            }

            catch (Exception ex) {
                Console.WriteLine(ex.Message);
            }

            try {
                Directory.CreateDirectory(AppDataPath);
                Directory.CreateDirectory(ExportPath);
            }

            catch (Exception ex) {
                ex.Show();
            }

            Views = new ViewCollection(); // Make a ViewCollection object

            ToolsMenu.ItemsSource = ViewCollection.GetAllToolTypes().Where(o => o.GetCustomAttribute <HiddenToolAttribute>() == null).Select(o => {
                var name = ViewCollection.GetName(o);
                var item = new MenuItem {
                    Header = "_" + name, ToolTip = $"Open {name}."
                };
                item.Click += ViewSelectMenuItemOnClick;
                return(item);
            }).OrderBy(o => o.Header);
        }
Пример #16
0
 /// <summary>
 /// Initializes a new instance of the <see cref="Document"/> class
 /// </summary>
 /// <remarks>
 /// Creates a new document.
 /// </remarks>
 public Document()
 {
     this.docObjects         = new BaseObjectList();
     this.viewCollection     = new ViewCollection();
     this.viewControllerList = new ViewControllerList();
     this.selectedObjects    = new BaseObjectList();
     this.docName            = string.Empty;
     this.fileName           = string.Empty;
     this.docGuid            = Guid.NewGuid();
     AppContext.ViewClosed  += this.OnViewClosed;
 }
Пример #17
0
        public async Task <ViewCollection> CreateCollectionAsync([FromBody] CreateCollection createCollection)
        {
            var collection = createCollection.GetModel();

            _context.Collections.Add(collection);
            await _context.SaveChangesAsync();

            _logger.LogInformation($"Created collection #{collection.Id}.");

            return(ViewCollection.Create(collection));
        }
Пример #18
0
        public override void InitializeControl()
        {
            base.InitializeControl();
            //Init banded view and make it the main view
            BandedGridView bandedView = InitializeBandedGridView(GridViewMain);

            MainView = bandedView;
            ViewCollection.AddRange(new BaseView[] { bandedView });
            ShowOnlyPredefinedDetails = true;
            UseEmbeddedNavigator      = false;
        }
 protected void Page_Init(object sender, EventArgs e)
 {
     // Instantiate view if multiview not populated
     if(views == null)
         views = new ViewCollection(mvUserMultiview);
     // Populate multiview
     for (int i = 0; i < views.Count; i++)
     {
         mvUserMultiview.Views.Add(views[i]);
     }
 }
Пример #20
0
        /// <summary>
        /// Overloaded Opens the document specified by the given <paramref name="fileName"/>
        /// and uses the specified  <paramref name="loader"/>.
        /// </summary>
        /// <param name="fileName">The document to be opened.</param>
        /// <param name="loader">The loader associated with the file type.</param>
        /// <param name="roiObjects">list of RegionOfInterest to add to the ImageView</param>
        /// <returns>A <see cref="bool"/> value indicating the success of the attempt to open a document.</returns>
        internal bool OpenDocument(string fileName, ISpecFileLoader loader, List <RegionOfInterest> roiObjects)
        {
            if (loader == null || string.IsNullOrEmpty(fileName))
            {
                return(false);
            }

            ISpecFileContent specFileContent = loader.Load(fileName);

            if (specFileContent == null)
            {
                return(false);
            }

            Document doc = specFileContent.Document;

            if (doc == null)
            {
                return(false);
            }

            AppContext.DocumentList.Add(doc);

            ViewCollection views = specFileContent.GetContentViews(doc);

            if (views != null)
            {
                foreach (ViewImage view in views)
                {
                    // Add in the ImageDataObject to each of the roiObjects
                    // Probably not the best place to put this.. but will do for now.
                    foreach (RegionOfInterest regionofinterest in roiObjects)
                    {
                        regionofinterest.ImageData = view.GetImagingData();
                    }

                    view.RoiObjects = roiObjects;
                    view.RoiInitialSetup();
                }

                foreach (IView view in views)
                {
                    AppContext.Application.AddView(view);
                    doc.ViewCollection.Add(view);
                }
            }
            else
            {
                return(false);
            }

            return(true);
        }
Пример #21
0
        /// <summary>
        /// Create the views of this content.
        /// </summary>
        /// <param name="doc">The <see cref="Document"/> object this content is associated with.</param>
        /// <returns>A <see cref="ViewCollection"/> object containing the views.</returns>
        public ViewCollection GetContentViews(Document doc)
        {
            var views = new ViewCollection();

            foreach (Imaging dataSet in this.contentList)
            {
                var view = new ViewImage(doc, dataSet, dataSet.Name, dataSet.ExperimentType);
                views.Add(view);
            }

            return(views);
        }
Пример #22
0
        /// <summary>
        /// Create the views of this content.
        /// </summary>
        /// <param name="doc">The <see cref="Document"/> object this content is associated with.</param>
        /// <returns>A <see cref="ViewCollection"/> object containing the views.</returns>
        public ViewCollection GetContentViews(Document doc)
        {
            ViewCollection views = new ViewCollection();

            foreach (Imaging dataSet in contentList)
            {
                ViewImage           view     = new ViewImage(doc, dataSet, dataSet.Name);
                ViewImageController viewCtrl = new ViewImageController(doc, view);
                views.Add(view);
            }

            return(views);
        }
Пример #23
0
        public void GetOrAdd_UsesValueFromCache_IfGlobalHasNotChanged()
        {
            // Arrange
            var instance     = new PreCompile();
            var length       = Encoding.UTF8.GetByteCount(instance.Content);
            var fileProvider = new TestFileProvider();

            var lastModified = DateTime.UtcNow;

            var fileInfo = new TestFileInfo
            {
                Length       = length,
                LastModified = lastModified,
                Content      = instance.Content
            };

            fileProvider.AddFile(ViewPath, fileInfo);

            var globalContent  = "global-content";
            var globalFileInfo = new TestFileInfo
            {
                Content      = globalContent,
                LastModified = DateTime.UtcNow
            };

            fileProvider.AddFile("_ViewImports.cshtml", globalFileInfo);
            var globalRazorFileInfo = new RazorFileInfo
            {
                Hash = Crc32.Calculate(GetMemoryStream(globalContent)).ToString(CultureInfo.InvariantCulture),
                HashAlgorithmVersion = 1,
                LastModified         = globalFileInfo.LastModified,
                Length       = globalFileInfo.Length,
                RelativePath = "_ViewImports.cshtml",
                FullTypeName = typeof(RuntimeCompileIdentical).FullName
            };
            var precompiledViews = new ViewCollection();

            precompiledViews.Add(globalRazorFileInfo);
            var cache = new CompilerCache(new[] { precompiledViews }, TestLoadContext, fileProvider);

            // Act
            var result = cache.GetOrAdd(ViewPath,
                                        compile: _ => { throw new Exception("shouldn't be invoked"); });

            // Assert
            Assert.NotSame(CompilerCacheResult.FileNotFound, result);
            var actual = result.CompilationResult;

            Assert.NotNull(actual);
            Assert.Equal(typeof(PreCompile), actual.CompiledType);
        }
Пример #24
0
        public PreferencesView()
        {
            InitializeComponent();
            DataContext = SettingsManager.Settings;

            var views = MainWindow.AppWindow.Views;

            NoneQuickRunBox.ItemsSource = new[] { "<Current Tool>" }.Concat(
                ViewCollection.GetNames(ViewCollection.GetAllQuickRunTypesWithTargets(SmartQuickRunTargets.NoSelection)));
            SingleQuickRunBox.ItemsSource = new[] { "<Current Tool>" }.Concat(
                ViewCollection.GetNames(ViewCollection.GetAllQuickRunTypesWithTargets(SmartQuickRunTargets.SingleSelection)));
            MultipleQuickRunBox.ItemsSource = new[] { "<Current Tool>" }.Concat(
                ViewCollection.GetNames(ViewCollection.GetAllQuickRunTypesWithTargets(SmartQuickRunTargets.MultipleSelection)));
        }
Пример #25
0
        public override void InitializeControl()
        {
            GridViewMain = new GridView();
            this.EmbeddedNavigator.Buttons.CustomButtons.Clear();
            base.InitializeControl();
            //Init banded view and make it the main view
            BandedGridView bandedView = InitializeBandedGridView(GridViewMain);

            MainView = bandedView;
            ViewCollection.AddRange(new BaseView[] { bandedView });
            ShowOnlyPredefinedDetails = false;
            WorkingShiftList          = (List <ADWorkingShiftsInfo>)objWorkingShiftsController.GetListFromDataSet(objWorkingShiftsController.GetAllObjects());
            //UseEmbeddedNavigator = false;
        }
Пример #26
0
        public static View GetDefaultView(this List lst)
        {
            ViewCollection views = lst.Views;

            lst.Context.Load(views, v => v.Include(vw => vw.DefaultView, vw => vw.ViewFields));
            lst.Context.ExecuteQuery();
            foreach (View vw in views)
            {
                if (vw.DefaultView)
                {
                    return(vw);
                }
            }
            return(null);
        }
Пример #27
0
        public void GetOrAdd_ReturnsFileNotFoundResult_IfPrecompiledViewWasRemovedFromFileSystem()
        {
            // Arrange
            var precompiledViews = new ViewCollection();
            var fileProvider     = new TestFileProvider();
            var cache            = new CompilerCache(new[] { precompiledViews }, TestLoadContext, fileProvider);

            // Act
            var result = cache.GetOrAdd(ViewPath,
                                        compile: _ => { throw new Exception("shouldn't be invoked"); });

            // Assert
            Assert.Same(CompilerCacheResult.FileNotFound, result);
            Assert.Null(result.CompilationResult);
        }
Пример #28
0
        /// <summary>
        /// Sets the content type.
        /// </summary>
        /// <param name="clientContext">SP client context</param>
        /// <param name="list">Name of the list</param>
        /// <param name="usersMySite">My Site URL of the user</param>
        internal static void SetContentType(ClientContext clientContext, List list, string usersMySite)
        {
            bool flag = false;

            try
            {
                CreateBriefcaseIfNotExists(clientContext, list, usersMySite);
                // Get Matter Center for OneDrive content type
                ContentType oneDriveContentType = clientContext.Web.ContentTypes.Where(item => item.Name == ServiceConstantStrings.OneDriveContentTypeName).FirstOrDefault();
                if (null != oneDriveContentType)
                {
                    list.ContentTypes.AddExistingContentType(oneDriveContentType); // Associate content type with list (Documents)
                    list.Update();
                    clientContext.ExecuteQuery();
                }
                ContentTypeCollection currentContentTypeOrder = list.ContentTypes;
                clientContext.Load(currentContentTypeOrder);
                clientContext.ExecuteQuery();
                foreach (ContentType contentType in currentContentTypeOrder)
                {
                    if (contentType.Name.Equals(ServiceConstantStrings.OneDriveContentTypeName))
                    {
                        flag = true;
                    }
                }
                List <string> contentTypes = new List <string>()
                {
                    ServiceConstantStrings.OneDriveContentTypeName
                };
                if (flag == false)
                {
                    IList <ContentType> contentTypeCollection = SharePointHelper.GetContentTypeData(clientContext, contentTypes);
                    if (null != contentTypeCollection)
                    {
                        ViewCollection views = list.Views;
                        clientContext.Load(views);
                        FieldCollection fields = ProvisionHelperFunctions.GetContentType(clientContext, contentTypeCollection, list);
                        fields.GetByInternalNameOrTitle(ServiceConstantStrings.OneDriveSiteColumn).SetShowInEditForm(false);
                        fields.GetByInternalNameOrTitle(ServiceConstantStrings.OneDriveSiteColumn).SetShowInNewForm(false);
                        fields.GetByInternalNameOrTitle(ServiceConstantStrings.OneDriveSiteColumn).Update();
                    }
                }
            }
            catch (Exception exception)
            {
                Logger.LogError(exception, MethodBase.GetCurrentMethod().DeclaringType.Name, MethodBase.GetCurrentMethod().Name, ServiceConstantStrings.LogTableName);
            }
        }
Пример #29
0
 /// <summary>
 /// 生成视图
 /// </summary>
 /// <param name="views">视图</param>
 /// <param name="fileName">文件名路径</param>
 /// <returns>是否成功</returns>
 public bool GenerateViewScripts(string fileName)
 {
     try
     {
         ViewCollection views = _Database.Views;
         using (Stream stream = new FileStream(fileName, FileMode.Append, FileAccess.Write, FileShare.None))
         {
             //声明统一资源名称集合对象
             UrnCollection collection = null;
             //声明字符串集合对象:存储collection中的所有string对象(在这里其中有3个string对象)
             StringCollection sqls = null;
             collection = new UrnCollection();
             for (int i = 0; i < views.Count; i++)
             {
                 if (views[i].Owner == "dbo")
                 {
                     collection.Add(views[i].Urn);
                 }
                 else
                 {
                     break;
                 }
             }
             //collection.Add(table.Urn);
             sqls = _Scripter.Script(collection);
             //遍历字符串集合对象sqls中的string对象,选择要输出的脚本语句:
             if (sqls != null && sqls.Count > 0)
             {
                 //写入文件
                 byte[] bytes = null;
                 string temp  = "";
                 foreach (string s in sqls)
                 {
                     temp  = s + "\r\n";
                     bytes = Encoding.Default.GetBytes(temp);
                     stream.Write(bytes, 0, bytes.Length);
                 }
             }
             stream.Close();
         }
         return(true);
     }
     catch (Exception ex)
     {
         return(false);
         //  WriteExceptionLog(ex);
     }
 }
Пример #30
0
        public void FileWithTheSameLengthAndDifferentTime_DoesNot_OverridesPrecompilation(
            Type resultViewType,
            long fileTimeUTC,
            bool swapsPreCompile)
        {
            // Arrange
            var instance = (View)Activator.CreateInstance(resultViewType);
            var length   = Encoding.UTF8.GetByteCount(instance.Content);

            var collection = new ViewCollection();
            var cache      = new CompilerCache(new[] { new ViewCollection() });

            var fileInfo = new Mock <IFileInfo>();

            fileInfo
            .SetupGet(i => i.Length)
            .Returns(length);
            fileInfo
            .SetupGet(i => i.LastModified)
            .Returns(DateTime.FromFileTimeUtc(fileTimeUTC));
            fileInfo.Setup(i => i.CreateReadStream())
            .Returns(GetMemoryStream(instance.Content));

            var preCompileType = typeof(PreCompile);

            var runtimeFileInfo = new RelativeFileInfo()
            {
                FileInfo     = fileInfo.Object,
                RelativePath = "ab",
            };

            // Act
            var actual = cache.GetOrAdd(runtimeFileInfo,
                                        enableInstrumentation: false,
                                        compile: () => CompilationResult.Successful(resultViewType));

            // Assert
            if (swapsPreCompile)
            {
                Assert.Equal(actual.CompiledType, resultViewType);
            }
            else
            {
                Assert.Equal(actual.CompiledType, typeof(PreCompile));
            }
        }
Пример #31
0
        public void GetOrAdd_UsesValueFromCache_IfViewStartHasNotChanged()
        {
            // Arrange
            var instance   = (View)Activator.CreateInstance(typeof(PreCompile));
            var length     = Encoding.UTF8.GetByteCount(instance.Content);
            var fileSystem = new TestFileSystem();

            var lastModified = DateTime.UtcNow;

            var fileInfo = new TestFileInfo
            {
                Length       = length,
                LastModified = lastModified,
                Content      = instance.Content
            };
            var runtimeFileInfo = new RelativeFileInfo(fileInfo, "ab");

            var viewStartContent  = "viewstart-content";
            var viewStartFileInfo = new TestFileInfo
            {
                Content      = viewStartContent,
                LastModified = DateTime.UtcNow
            };

            fileSystem.AddFile("_ViewStart.cshtml", viewStartFileInfo);
            var viewStartRazorFileInfo = new RazorFileInfo
            {
                Hash         = RazorFileHash.GetHash(GetMemoryStream(viewStartContent)),
                LastModified = viewStartFileInfo.LastModified,
                Length       = viewStartFileInfo.Length,
                RelativePath = "_ViewStart.cshtml",
                FullTypeName = typeof(RuntimeCompileIdentical).FullName
            };

            var precompiledViews = new ViewCollection();

            precompiledViews.Add(viewStartRazorFileInfo);
            var cache = new CompilerCache(new[] { precompiledViews }, fileSystem);

            // Act
            var actual = cache.GetOrAdd(runtimeFileInfo,
                                        compile: _ => { throw new Exception("shouldn't be invoked"); });

            // Assert
            Assert.Equal(typeof(PreCompile), actual.CompiledType);
        }
Пример #32
0
        /// <summary>
        /// Creates Pages in the given web and Library using the passed client context
        /// </summary>
        /// <param name="context"></param>
        /// <param name="web"></param>

        /// <summary>
        /// creates a pages using a single definition file
        /// </summary>
        /// <param name="context"></param>
        /// <param name="def"></param>
        public override void Process(ClientContext context, bool add, string def)
        {
            XmlDocument doc = new XmlDocument();

            doc.LoadXml(System.IO.File.ReadAllText(def));
            XmlNodeList views = doc.SelectNodes("Views/View");

            if (add)
            {
                foreach (XmlNode view in views)
                {
                    //get the destination list name from ListName attribute
                    List dest = context.Web.Lists.GetByTitle(view.Attributes[Constants.ViewAttributeNames.ListName].Value);
                    ViewCreationInformation info = new ViewCreationInformation();
                    info.SetAsDefaultView = Boolean.Parse(view.Attributes[Constants.ViewAttributeNames.DefaultView].Value);
                    info.Title            = view.Attributes[Constants.ViewAttributeNames.Title].Value;
                    info.ViewTypeKind     = (ViewType)int.Parse(view.Attributes[Constants.ViewAttributeNames.ViewType].Value);
                    info.ViewFields       = view.Attributes[Constants.ViewAttributeNames.ViewFields].Value.Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries);
                    View newView = dest.Views.Add(info);
                    context.ExecuteQuery();
                    newView.Toolbar = view.Attributes[Constants.ViewAttributeNames.Toolbar].Value;
                    newView.JSLink  = view.Attributes[Constants.ViewAttributeNames.JSLink].Value;
                    newView.Update();
                    context.ExecuteQuery();
                }
            }
            else
            {
                foreach (XmlNode view in views)
                {
                    //get the destination list name from ListName attribute
                    List           dest      = context.Web.Lists.GetByTitle(view.Attributes[Constants.ViewAttributeNames.ListName].Value);
                    ViewCollection listViews = dest.Views;
                    context.Load(listViews);
                    context.ExecuteQuery();
                    foreach (View viewItem in listViews)
                    {
                        if (viewItem.Title == view.Attributes[Constants.ViewAttributeNames.Toolbar].Value)
                        {
                            viewItem.DeleteObject();
                        }
                    }
                }
                context.ExecuteQuery();
            }
        }
Пример #33
0
 /// <summary>
 /// Disposes the object.
 /// </summary>
 public virtual void Dispose()
 {
     if (metadata != null)
     {
         //metadata.Dispose();
         metadata = null;
     }
     if (collectedData != null)
     {
         //collectedData.Dispose();
         collectedData = null;
     }
     if (views != null)
     {
         //views.Dispose();
         views = null;
     }
 }
        private void CreateView(Web web, View view, ViewCollection existingViews, List createdList, PnPMonitoredScope monitoredScope)
        {
            try
            {

                var viewElement = XElement.Parse(view.SchemaXml);
                var displayNameElement = viewElement.Attribute("DisplayName");
                if (displayNameElement == null)
                {
                    throw new ApplicationException("Invalid View element, missing a valid value for the attribute DisplayName.");
                }

                monitoredScope.LogDebug(CoreResources.Provisioning_ObjectHandlers_ListInstances_Creating_view__0_, displayNameElement.Value);
                var existingView = existingViews.FirstOrDefault(v => v.Title == displayNameElement.Value);

                if (existingView != null)
                {
                    existingView.DeleteObject();
                    web.Context.ExecuteQueryRetry();
                }

                var viewTitle = displayNameElement.Value;

                // Type
                var viewTypeString = viewElement.Attribute("Type") != null ? viewElement.Attribute("Type").Value : "None";
                viewTypeString = viewTypeString[0].ToString().ToUpper() + viewTypeString.Substring(1).ToLower();
                var viewType = (ViewType)Enum.Parse(typeof(ViewType), viewTypeString);

                // Fields
                string[] viewFields = null;
                var viewFieldsElement = viewElement.Descendants("ViewFields").FirstOrDefault();
                if (viewFieldsElement != null)
                {
                    viewFields = (from field in viewElement.Descendants("ViewFields").Descendants("FieldRef") select field.Attribute("Name").Value).ToArray();
                }

                // Default view
                var viewDefault = viewElement.Attribute("DefaultView") != null && Boolean.Parse(viewElement.Attribute("DefaultView").Value);

                // Row limit
                var viewPaged = true;
                uint viewRowLimit = 30;
                var rowLimitElement = viewElement.Descendants("RowLimit").FirstOrDefault();
                if (rowLimitElement != null)
                {
                    if (rowLimitElement.Attribute("Paged") != null)
                    {
                        viewPaged = bool.Parse(rowLimitElement.Attribute("Paged").Value);
                    }
                    viewRowLimit = uint.Parse(rowLimitElement.Value);
                }

                // Query
                var viewQuery = new StringBuilder();
                foreach (var queryElement in viewElement.Descendants("Query").Elements())
                {
                    viewQuery.Append(queryElement.ToString());
                }

                var viewCI = new ViewCreationInformation
                {
                    ViewFields = viewFields,
                    RowLimit = viewRowLimit,
                    Paged = viewPaged,
                    Title = viewTitle,
                    Query = viewQuery.ToString(),
                    ViewTypeKind = viewType,
                    PersonalView = false,
                    SetAsDefaultView = viewDefault,
                };

                // Allow to specify a custom view url. View url is taken from title, so we first set title to the view url value we need,
                // create the view and then set title back to the original value
                var urlAttribute = viewElement.Attribute("Url");
                var urlHasValue = urlAttribute != null && !string.IsNullOrEmpty(urlAttribute.Value);
                if (urlHasValue)
                {
                    //set Title to be equal to url (in order to generate desired url)
                    viewCI.Title = Path.GetFileNameWithoutExtension(urlAttribute.Value);
                }

                var createdView = createdList.Views.Add(viewCI);
                web.Context.Load(createdView, v => v.Scope, v => v.JSLink, v => v.Title);
                web.Context.ExecuteQueryRetry();

                if (urlHasValue)
                {
                    //restore original title
                    createdView.Title = viewTitle;
                    createdView.Update();
                }

                // Scope
                var scope = viewElement.Attribute("Scope") != null ? viewElement.Attribute("Scope").Value : null;
                ViewScope parsedScope = ViewScope.DefaultValue;
                if (!string.IsNullOrEmpty(scope) && Enum.TryParse<ViewScope>(scope, out parsedScope))
                {
                    createdView.Scope = parsedScope;
                    createdView.Update();
                }

                // JSLink
                var jslinkElement = viewElement.Descendants("JSLink").FirstOrDefault();
                if (jslinkElement != null)
                {
                    var jslink = jslinkElement.Value;
                    if (createdView.JSLink != jslink)
                    {
                        createdView.JSLink = jslink;
                        createdView.Update();
                    }
                }

                createdList.Update();
                web.Context.ExecuteQueryRetry();
            }
            catch (Exception ex)
            {
                monitoredScope.LogError(CoreResources.Provisioning_ObjectHandlers_ListInstances_Creating_view_failed___0_____1_, ex.Message, ex.StackTrace);
                throw;
            }
        }
Пример #35
0
        private void CreateView(Web web, View view, ViewCollection existingViews, List createdList)
        {
            var viewElement = XElement.Parse(view.SchemaXml);
            var displayNameElement = viewElement.Attribute("DisplayName");
            if (displayNameElement == null)
            {
                throw new ApplicationException("Invalid View element, missing a valid value for the attribute DisplayName.");
            }

            var existingView = existingViews.FirstOrDefault(v => v.Title == displayNameElement.Value);

            if (existingView != null)
            {
                existingView.DeleteObject();
                web.Context.ExecuteQueryRetry();
            }

            var viewTitle = displayNameElement.Value;

            // Type
            var viewTypeString = viewElement.Attribute("Type") != null ? viewElement.Attribute("Type").Value : "None";
            viewTypeString = viewTypeString[0].ToString().ToUpper() + viewTypeString.Substring(1).ToLower();
            var viewType = (ViewType)Enum.Parse(typeof(ViewType), viewTypeString);

            // Fields
            string[] viewFields = null;
            var viewFieldsElement = viewElement.Descendants("ViewFields").FirstOrDefault();
            if (viewFieldsElement != null)
            {
                viewFields = (from field in viewElement.Descendants("ViewFields").Descendants("FieldRef") select field.Attribute("Name").Value).ToArray();
            }

            // Default view
            var viewDefault = viewElement.Attribute("DefaultView") != null && Boolean.Parse(viewElement.Attribute("DefaultView").Value);

            // Row limit
            var viewPaged = true;
            uint viewRowLimit = 30;
            var rowLimitElement = viewElement.Descendants("RowLimit").FirstOrDefault();
            if (rowLimitElement != null)
            {
                if (rowLimitElement.Attribute("Paged") != null)
                {
                    viewPaged = bool.Parse(rowLimitElement.Attribute("Paged").Value);
                }
                viewRowLimit = uint.Parse(rowLimitElement.Value);
            }

            // Query
            var viewQuery = new StringBuilder();
            foreach (var queryElement in viewElement.Descendants("Query").Elements())
            {
                viewQuery.Append(queryElement.ToString());
            }

            var viewCI = new ViewCreationInformation
            {
                ViewFields = viewFields,
                RowLimit = viewRowLimit,
                Paged = viewPaged,
                Title = viewTitle,
                Query = viewQuery.ToString(),
                ViewTypeKind = viewType,
                PersonalView = false,
                SetAsDefaultView = viewDefault,
            };

            var createdView = createdList.Views.Add(viewCI);
            web.Context.Load(createdView, v => v.Scope, v => v.JSLink);
            web.Context.ExecuteQueryRetry();

            // Scope
            var scope = viewElement.Attribute("Scope") != null ? viewElement.Attribute("Scope").Value : null;
            ViewScope parsedScope = ViewScope.DefaultValue;
            if (!string.IsNullOrEmpty(scope) && Enum.TryParse<ViewScope>(scope, out parsedScope))
            {
                createdView.Scope = parsedScope;
                createdView.Update();
            }

            // JSLink
            var jslinkElement = viewElement.Descendants("JSLink").FirstOrDefault();
            if (jslinkElement != null)
            {
                var jslink = jslinkElement.Value;
                if (createdView.JSLink != jslink)
                {
                    createdView.JSLink = jslink;
                    createdView.Update();
                }
            }

            createdList.Update();
            web.Context.ExecuteQueryRetry();
        }
Пример #36
0
 /// <summary>
 /// Load Views
 /// </summary>
 public virtual void LoadViews()
 {
     if (MetadataSource == MetadataSource.Unknown)
     {
         throw new GeneralException(SharedStrings.ERROR_LOADING_METADATA_UNKNOWN_SOURCE);
     }
     if (MetadataSource != MetadataSource.Xml)
     {
         views = Metadata.GetViews();
     }
     else
     {
         XmlNode viewsNode = GetViewsNode();
         views = Metadata.GetViews(currentViewElement, viewsNode);
     }
 }
Пример #37
0
 public SPOView(View view, ViewCollection parentCollection)
 {
     _view = view;
     _parentCollection = parentCollection;
 }
Пример #38
0
		public Universe (ContentManager content)
		{
			if (content == null)
				throw new ArgumentNullException ("content");
			_content = content;
			_views = new ViewCollection (null);
			_views.Universe = this;
		}