Пример #1
0
        /// <summary>
        /// Initializes the specified adapter.
        /// </summary>
        /// <param name="application">The application.</param>
        public override void Initialize(IApplication application)
        {
            base.Initialize(application);

            GameStorage gameStorage;
            if (WaveServices.Storage.Exists<GameStorage>())
            {
                gameStorage = WaveServices.Storage.Read<GameStorage>();
            }
            else
            {
                gameStorage = new GameStorage();
            }

            Catalog.RegisterItem(gameStorage);

            application.Adapter.DefaultOrientation = DisplayOrientation.Portrait;
            application.Adapter.SupportedOrientations = DisplayOrientation.Portrait;

            ViewportManager vm = WaveServices.ViewportManager;
            vm.Activate(768, 1024, ViewportManager.StretchMode.Uniform);

            // Play background music
            WaveServices.MusicPlayer.Play(new MusicInfo(Directories.SoundsPath + "bg_music.mp3"));
            WaveServices.MusicPlayer.IsRepeat = true;

            WaveServices.ScreenContextManager.To(new ScreenContext(new MainMenuScene()));
        }
Пример #2
0
        public override void Initialize(IApplication application)
        {
            base.Initialize(application);

            ScreenContext screenContext = new ScreenContext(new MyScene());
            WaveServices.ScreenContextManager.To(screenContext);
        }
Пример #3
0
        public BIOS(IApplication platformApp, IEpromIO platformBIOS)
        {
            platform = platformApp;
            platformIO = platformBIOS;

            sync = new object();
        }
Пример #4
0
 public ApplicationViewModel(IApplication application)
 {
     Name = application.Name;
     SiteUrl = application.SiteUrl;
     GitUrl = GetCloneUrl(application, RepositoryType.Git);
     HgUrl = GetCloneUrl(application, RepositoryType.Mercurial);
 }
        async Task Run(IApplication application)
        {
            ApplicationArchiveInfo info = await application.PackageAsync();

            Console.WriteLine("Application name: {0}", info.ApplicationName);
            Console.WriteLine("Application path: {0}", info.Path);
        }
Пример #6
0
 public SessionFactory(IApplication app, IMessageStoreFactory storeFactory, ILogFactory logFactory, IMessageFactory messageFactory)
 {
     application_ = app;
     messageStoreFactory_ = storeFactory;
     logFactory_ = logFactory;
     messageFactory_ = messageFactory ?? new DefaultMessageFactory();
 }
Пример #7
0
        protected override void OnStart(string[] args)
        {
            try
            {
                var configProvider = new MemoryConfigurationProvider();
                configProvider.Add("server.urls", "http://localhost:5000");

                var config = new ConfigurationBuilder()
                    .Add(configProvider)
                    .Build();

                var builder = new WebHostBuilder(config);
                builder.UseServer("Microsoft.AspNet.Server.Kestrel");
                builder.UseServices(services => services.AddMvc());
                builder.UseStartup(appBuilder =>
                {
                    appBuilder.UseDefaultFiles();
                    appBuilder.UseStaticFiles();
                    appBuilder.UseMvc();
                });

                var hostingEngine = builder.Build();
                _application = hostingEngine.Start();
            }
            catch (Exception ex)
            {
                Debug.WriteLine("error in OnStart: " + ex);
                throw;
            }
        }
Пример #8
0
        public override void Initialize(IApplication application)
        {
            base.Initialize(application);

            // Load storage game data
            GameStorage gameStorage;

            if (WaveServices.Storage.Exists<GameStorage>())
            {
                gameStorage = WaveServices.Storage.Read<GameStorage>();
            }
            else
            {
                gameStorage = new GameStorage();
            }

            Catalog.RegisterItem<GameStorage>(gameStorage);

            // Register the SoundManager service
            WaveServices.RegisterService<SoundManager>(new SoundManager());

            // Play background music
            WaveServices.MusicPlayer.Play(new MusicInfo(WaveContent.Assets.Audio.bg_music_mp3));
            WaveServices.MusicPlayer.IsRepeat = true;

            // GameBackContext is visible always at the background.
            // For this reason the behavior is set to Draw and Update when the scene is in background.
            var backContext = new ScreenContext("GameBackContext", new GameScene());
            backContext.Behavior = ScreenContextBehaviors.DrawInBackground | ScreenContextBehaviors.UpdateInBackground;

            //On init show the Main menu
            WaveServices.ScreenContextManager.Push(backContext);
            WaveServices.ScreenContextManager.Push(new ScreenContext("MenuContext", new MenuScene()));
        }
 public void Startup(ref object initializationData)
 {
   m_application = initializationData as IApplication;
   m_appStatus = m_application as IApplicationStatus;
   // Wireup the events
   SetupEvents();
 }
        protected override void OnStart(string[] args)
        {
            try
            {
                var temp = new ConfigurationBuilder()
                    .AddJsonFile("config.json")
                    .AddJsonFile("hosting.json", true)
                    .Build();

                var configProvider = new MemoryConfigurationProvider();
                configProvider.Add("server.urls", temp["WebServerAddress"]);
                configProvider.Add("webroot", temp.Get<string>("webroot", "wwwroot"));

                var config = new ConfigurationBuilder()
                    .Add(configProvider)
                    .Build();

                var builder = new WebHostBuilder(config);
                builder.UseServer("Microsoft.AspNet.Server.Kestrel");
                builder.UseStartup<Startup>();
                
                var hostingEngine = builder.Build();
                _application = hostingEngine.Start();
            }
            catch (Exception ex)
            {
                Debug.WriteLine("error in OnStart: " + ex);
                throw;
            }
        }
Пример #11
0
        /// <summary>
        /// Конструктор класса
        /// </summary>
        /// <param name="app">Ссылка на платформу</param>
        /// <param name="pBios">Ссылка на подсистему ввода/вывода платформы</param>
        public MainForm(IApplication app, IEpromIO pBios, IProtocol protocol)
        {
            InitializeComponent();
            textInserter = new TextInsert(InsertToText);

            oldValue = new object();
            newValue = new object();

            oldValue = "0";
            newValue = "0";

            bios = new BIOS(app, pBios);
            proto = protocol;

            currentState = new ObjectCurrentState();

            for (int i = 0; i < 11; i++)
            {
                DataGridViewRow r = new DataGridViewRow();
                if ((i % 2) == 0) r.DefaultCellStyle.BackColor = Color.WhiteSmoke;
                dataGridViewCalibrationTable.Rows.Add(r);
            }

            syncker = new Sync();
            packetSyncMutex = new Mutex(false);

            gr = new GraphicCalibration(CreateGraphics(), new Rectangle(12, 38, 422, 267));
            gr.CalculateScale();
        }
Пример #12
0
        public PublicModule(IApplication application, IRootPathProvider rootPathProvider,
		                    IArticleRepository articleRepository, IPageRepository pageRepository)
            : base(application)
        {
            this._ArticleRepository = articleRepository;
            this._PageRepository = pageRepository;
            this._rootPathProvider = rootPathProvider;

            // Bind the HTTP POST verb with /robots.txt with a response filled by text
            this.Get["/robots.txt"] = GetRobotTxt;

            // Bind the HTTP POST verb with /sitemap.xml to the GetSitemap method
            this.Get["/sitemap.xml"] = GetSitemap;

            // Define a route for urls "/{seoTitle}" which will returns the article matching the specified slug
            this.Get["/{category}/{seoTitle}"] = parameters => {
                // [BUG]: /sitemap.xml n'est pas prioritaire sur /{seoTitle}
                if(parameters.seoTitle == "rss")
                    return GetRSSFeed(parameters);
                // fin de [BUG]
                return GetStaticPage(parameters);
            };

            // Define a route for urls "/{seoTitle}" which will returns the article matching the specified slug
            this.Get["/{seoTitle}"] = parameters => {
                // [BUG]: /sitemap.xml n'est pas prioritaire sur /{seoTitle}
                if(parameters.seoTitle == "sitemap")
                    return GetSitemap(parameters);
                // fin de [BUG]
                return GetStaticPage(parameters);
            };
        }
Пример #13
0
        public ShapeToKMLForm(IApplication application)
        {
            layers = new List<LayerProperties>();
            InitializeComponent();
            this.m_application = application;

            chkLayers.Items.Clear();
            IMxDocument activeDoc = application.Document as IMxDocument;

            IMap activeMap = activeDoc.FocusMap;
            layers.Clear();

            for (int i = 0; i < activeMap.LayerCount; i++)
            {
                //if it's a raster or a feature layer. Other supported layers will be added later
                if ((activeMap.get_Layer(i) is IFeatureLayer) || (activeMap.get_Layer(i) is IRasterLayer))
                {
                    //chkLayers.Items.Add(activeMap.get_Layer(i).Name, false);
                    LayerProperties lp = new LayerProperties();
                    lp.Layeru = activeMap.get_Layer(i);
                    lp.Tesselate = false;
                    lp.AltitudeMode = AltitudeMode.clampToGround;
                    lp.Extrude = false;
                    lp.Color = Color.Black;
                    lp.name = lp.Layeru.Name;
                    chkLayers.Items.Add(lp, false);

                }
            }
        }
		private Application ()
		{
			aplication = new GtkApplication ();			
			aplication.Init ();
			
			Resources = new DefaultTheme ();			
		}
Пример #15
0
        public string InsertApplication(IApplication app)
        {
            string appid = "";
            try
            {
                Database db = DatabaseFactory.CreateDatabase();

                DbCommand dbCommand = db.GetStoredProcCommand("usp_SNB_InsertApplication");

                db.AddInParameter(dbCommand, "@first_name", DbType.String, app.FirstName);
                db.AddInParameter(dbCommand, "@last_name", DbType.String, app.LastName);
                db.AddInParameter(dbCommand, "@ssn", DbType.String, app.Ssn);
                db.AddInParameter(dbCommand, "@email", DbType.String, app.Email);

                //DataSet ds = db.ExecuteDataSet(dbCommand);
                appid = db.ExecuteScalar(dbCommand).ToString();

                dbCommand.Connection.Close();
                dbCommand.Connection.Dispose();
                dbCommand.Dispose();

            }

            catch (Exception ex)
            {

            }

            return appid;
        }
Пример #16
0
        // modified form constructor to accept the app and editor objects passed by ref
        public SpiralCurveDialog(ref IApplication pApp, ref IEditor pEditor)
        {
            //
            // Required for Windows Form Designer support
            //
            InitializeComponent();

            try
            {
                m_pApp = pApp;

                m_pEditor = pEditor;
                m_pEditProp2 = (IEditProperties2)m_pEditor;

                // REGEX strings that will be used for DMS units
                m_RegexUnitsDMS = new ArrayList();
                m_RegexUnitsDMS.Add(@" *(\d+)\.(\d\d)(\d\d\d\d) *");
                m_RegexUnitsDMS.Add(@" *(\d+)\/(\d+)\/(\d+\.?\d*) *");
                m_RegexUnitsDMS.Add(@" * *(\d+)\^(\d+)\'(\d+\.?\d*)\" + quote + " *");
                m_RegexUnitsDMS.Add(@" *(\d+)\-(\d+)\-(\d+\.?\d*) *");

                // REGEX string that will be used for DD, radians, Gons, etc..
                m_RegexUnitsDecimals = @" *(\d+\.?\d+) *";

                // REGEX object for validating the length with units
                m_RegexUnitsMeasure = new Regex(@"(\d*\.?\d+) *(" + String.Join("|", this.AllowedUnits) + ") *$");

                // validate the spatial reference of the edit data frame;
                m_SRValid = SpatialRefValid();
            }
            catch
            {

            }
        }
Пример #17
0
        public override void Initialize(IApplication application)
        {
            base.Initialize(application);

            GameStorage gameStorage;
            if (WaveServices.Storage.Exists<GameStorage>())
            {
                gameStorage = WaveServices.Storage.Read<GameStorage>();
            }
            else
            {
                gameStorage = new GameStorage();
            }

            Catalog.RegisterItem(gameStorage);

            application.Adapter.DefaultOrientation = DisplayOrientation.Portrait;
            application.Adapter.SupportedOrientations = DisplayOrientation.Portrait;

            //ViewportManager vm = WaveServices.ViewportManager;
            //vm.Activate(768, 1024, ViewportManager.StretchMode.Fill);

            ScreenContext screenContext = new ScreenContext(new MyScene());
            WaveServices.ScreenContextManager.To(screenContext);
        }
Пример #18
0
        public void Setup()
        {
            _repository = new MockRepository();
            _app = Concepts.SetupApplication(_repository, null, new TestCommandFactory());

            NavigateToFormEditor(_app);
        }
Пример #19
0
        private void LoadController(IApplication application)
        {
            Utils.LoadAssembly(a =>
            {
                foreach (Type type in a.GetTypes())
                {
                    if (IKende.IKendeCore.GetTypeAttributes<ControllerAttribute>(type, false).Length > 0 && !type.IsAbstract)
                    {
                        "load {0} controller".Log4Info(type);
                        object controller = Activator.CreateInstance(type);
                        Controllers.Add(controller);
                        foreach (System.Reflection.MethodInfo method in type.GetMethods(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance))
                        {
                            try
                            {
                                ParameterInfo[] pis = method.GetParameters();
                                if (pis.Length == 2 && (pis[0].ParameterType == typeof(ISession)))
                                {
                                    IMethodHandler handler = new MethodHandler(controller, method, application);
                                    mControllerHandlers[pis[1].ParameterType] = handler;
                                    "load {0}->{1} action success".Log4Info(type, method.Name);
                                }

                            }
                            catch (Exception e_)
                            {
                                "load {0}->{1} action error".Log4Error(e_, type, method.Name);
                            }
                        }


                    }
                }
            });
        }
Пример #20
0
        // Generates code for custom authentication and shows the file on IDE editor
        public static void ApplyCustomAuthentication(IAbstractEndpoint endpoint, IApplication application, IServiceProvider sp)
        {
            var solution = sp.TryGetService<ISolution>();

            // If the custom file doesn't exist... we will generate it
            if (!solution.Find(endpoint.Project.Name + @"\Infrastructure\Authentication.cs").Any())
            {
                application.Design.Infrastructure.Security.Authentication.LocalNamespace = endpoint.Project.Data.RootNamespace
                    + ".Infrastructure";
                application.Design.Infrastructure.Security.Authentication.As<IProductElement>()
                    // We are using Temp as we don't want the generation run on each build
                    .CreateTempGenerateCodeCommand(sp, "Authentication.cs"
                    , endpoint.Project.Name + @"\Infrastructure"
                    , @"t4://extension/a5e9f15b-ad7f-4201-851e-186dd8db3bc9/T/T4/Security/EndpointCustomAuthentication.tt")
                .Execute();
            }
            var item = solution.Find(endpoint.Project.Name + @"\Infrastructure\Authentication.cs").FirstOrDefault();
            if (item != null)
            {
                // Open the file on the IDE Editor
                item.As<EnvDTE.ProjectItem>()
                    .Open(EnvDTE.Constants.vsViewKindCode)
                    .Visible = true;
            }
        }
Пример #21
0
        public static void GenerateAuthenticationCodeOnEndpoints(IApplication app, IServiceProvider sp)
        {
            if (app.HasAuthentication)
            {
                foreach (var endpoint in app.Design.Endpoints.GetAll())
                {
                    var prefixAuthentication = "AuthenticationEndpointCode" + endpoint.As<IProductElement>().InstanceName;
                    if (!app.Design.Infrastructure.Security.Authentication.AsElement().AutomationExtensions.Any(a => a.Name.StartsWith(prefixAuthentication)))
                    {
                        app.Design.Infrastructure.Security.Authentication.LocalNamespace = endpoint.Project.Data.RootNamespace
                            + ".Infrastructure";
                        app.Design.Infrastructure.Security.Authentication.As<IProductElement>()
                            .CreateTempGenerateCodeCommand(sp, "Authentication.cs"
                            , endpoint.Project.Name + @"\Infrastructure\GeneratedCode"
                            , @"t4://extension/a5e9f15b-ad7f-4201-851e-186dd8db3bc9/T/T4/Security/EndpointAuthentication.tt"
                            , prefixAuthentication)
                        .Execute();
                    }

                    var prefixAuthorize = "AuthorizeOutgoingMessagesEndpointCode" + endpoint.As<IProductElement>().InstanceName;
                    if (!app.Design.Infrastructure.Security.Authentication.AsElement().AutomationExtensions.Any(a => a.Name.StartsWith(prefixAuthorize)))
                    {
                        app.Design.Infrastructure.Security.Authentication.LocalNamespace = endpoint.Project.Data.RootNamespace
                            + ".Infrastructure";
                        app.Design.Infrastructure.Security.Authentication.As<IProductElement>()
                            .CreateTempGenerateCodeCommand(sp, "AuthorizeOutgoingMessages.cs"
                            , endpoint.Project.Name + @"\Infrastructure\GeneratedCode"
                            , @"t4://extension/a5e9f15b-ad7f-4201-851e-186dd8db3bc9/T/T4/Security/EndpointAuthorizeOutgoingMessages.tt"
                            , prefixAuthorize)
                        .Execute();
                    }
                }
            }
        }
Пример #22
0
 public ChallengeComponent(IApplication application, INetworkedSession curSession, INetworkedSession otherSession, ChallengeDirection direction)
 {
     _application = application;
     CurSession = curSession;
     OtherSession = otherSession;
     Direction = direction;
 }
Пример #23
0
        /// <summary>
        /// Get ID of current page 
        /// </summary>
        /// <param name="obj">_Object Type</param>
        /// <returns>current page Id</returns>
        public static string GetActiveObjectID(IApplication oneNoteApp, _ObjectType obj)
        {
            string currentPageId = "";
            uint count = oneNoteApp.Windows.Count;
            foreach (Window window in oneNoteApp.Windows)
            {
                if (window.Active)
                {
                    switch (obj)
                    {
                        case _ObjectType.Notebook:
                            currentPageId = window.CurrentNotebookId;
                            break;
                        case _ObjectType.Section:
                            currentPageId = window.CurrentSectionId;
                            break;
                        case _ObjectType.SectionGroup:
                            currentPageId = window.CurrentSectionGroupId;
                            break;
                    }

                    currentPageId = window.CurrentPageId;
                }
            }

            return currentPageId;
        }
Пример #24
0
 public IDockableWindow GetDockableWindow(IApplication app, string winName)
 {
     IDockableWindowManager dWinManager = app as IDockableWindowManager;
     UID winID = new UIDClass();
     winID.Value = winName;
     return dWinManager.GetDockableWindow(winID);
 }
Пример #25
0
        public override void Initialize(IApplication application)
        {
            base.Initialize(application);
            application.Adapter.SupportedOrientations = WaveEngine.Common.Input.DisplayOrientation.LandscapeRight;

            WaveServices.ScreenContextManager.To(new ScreenContext(new MainScene()));
        }
Пример #26
0
 // Add a reference to the infrastructure project on each endpoint project
 public static void AddInfrastructureReferences(IApplication app, ISolution solution)
 {
     foreach (var endpoint in app.Design.Endpoints.GetAll())
     {
         endpoint.Project.AddReference(app.Design.Infrastructure.As<IProductElement>().GetProject());
     }
 }
Пример #27
0
 public void Init(IApplication application)
 {
     mApplication = (Implement.Application)application;
     TypeMapper = Utils.GetMessageMapping();
     Controllers = new List<object>();
     LoadController(application);
 }
Пример #28
0
        /// <summary>
        /// Конструктор
        /// </summary>
        /// <param name="application">Интерфейс связи с платформой</param>
        public Form1(IApplication application)
        {
            app = application;
            protocol = app.GetProtocol(ProtocolVersion.x100);
            try
            {
                par = LoadConfiguration(Application.StartupPath + ParametrConstants.ConfigName);
            }
            catch
            {
                par = new SetTimeParameters();
            }

            InitializeComponent();

            this.boxArray[0] = this.button1;
            this.boxArray[1] = this.button2;
            this.boxArray[2] = this.button5;
            this.boxArray[3] = this.button6;
            this.boxArray[4] = this.button7;
            this.boxArray[5] = this.button8;
            this.boxArray[6] = this.button9;

            SetImageForm();
        }
Пример #29
0
		protected Application(Generator g, Type type, bool initialize = true)
				: base(g, type, initialize)
		{
			Application.Instance = this;
			handler = (IApplication)base.Handler;
			Generator.Initialize(g); // make everything use this by default
		}
        /// <summary>
        /// Executes task.
        /// </summary>
        /// <param name="application">The application.</param>
        /// <param name="kernel">IoC container.</param>
        public void Execute(IApplication application, IKernel kernel)
        {
            var facilityConfig = GetFacilityConfig(application);

            kernel.ConfigurationStore.AddFacilityConfiguration("nhibernate.facility", facilityConfig);
            kernel.AddFacility("nhibernate.facility", new NHibernateFacility(new NHibernateConfigurator(application, kernel)));
        }
Пример #31
0
 public Input(IDisposableResource parent, IApplication application)
     : base(parent)
 {
     this.application         = application;
     application.HandleEvent += updateEvent;
 }
Пример #32
0
 internal NOPGlue(IApplication app) : base(app)
 {
 }
        private void btnExport_Click(object sender, System.EventArgs e)
        {
            //Exports the DataTable to a spreadsheet.

            #region Workbook Initialize
            //New instance of XlsIO is created.[Equivalent to launching MS Excel with no workbooks open].
            //The instantiation process consists of two steps.

            //Step 1 : Instantiate the spreadsheet creation engine.
            ExcelEngine excelEngine = new ExcelEngine();

            //Step 2 : Instantiate the excel application object.
            IApplication application = excelEngine.Excel;
            //Set the Workbook version as Excel 97to2003
            if (this.rdbExcel97.Checked)
            {
                application.DefaultVersion = ExcelVersion.Excel97to2003;
                fileName = "ExportToExcel.xls";
            }
            //Set the Workbook version as Excel 2007
            else if (this.rdbExcel2007.Checked)
            {
                application.DefaultVersion = ExcelVersion.Excel2007;
                fileName = "ExportToExcel.xlsx";
            }
            //Set the Workbook version as Excel 2010
            else if (this.rdbExcel2010.Checked)
            {
                application.DefaultVersion = ExcelVersion.Excel2010;
                fileName = "ExportToExcel.xlsx";
            }
            //Set the Workbook version as Excel 2010
            else if (this.rdbExcel2013.Checked)
            {
                application.DefaultVersion = ExcelVersion.Excel2013;
                fileName = "ExportToExcel.xlsx";
            }
            //A new workbook is created.[Equivalent to creating a new workbook in MS Excel]
            //The new workbook will have 3 worksheets
            IWorkbook workbook = application.Workbooks.Create(1);

            //The first worksheet object in the worksheets collection is accessed.
            IWorksheet worksheet = workbook.Worksheets[0];
            #endregion

            #region Export DataTable to Excel
            //Export DataTable.
            if (this.dataGrid1.DataSource != null)
            {
                worksheet.ImportDataTable((DataTable)this.dataGrid1.DataSource, true, 3, 1, -1, -1);
            }
            else
            {
                MessageBox.Show("There is no datatable to export, Please import a datatable first", "Error");

                //Close the workbook.
                workbook.Close();
                return;
            }
            #endregion

            #region Formatting the Report
            //Formatting the Report

            #region Applying Body Stlye
            //Body Style
            IStyle bodyStyle = workbook.Styles.Add("BodyStyle");
            bodyStyle.BeginUpdate();

            //Add custom colors to the palette.
            workbook.SetPaletteColor(9, Color.FromArgb(239, 242, 247));
            bodyStyle.Color = Color.FromArgb(239, 243, 247);
            bodyStyle.Borders[ExcelBordersIndex.EdgeLeft].LineStyle  = ExcelLineStyle.Thin;
            bodyStyle.Borders[ExcelBordersIndex.EdgeRight].LineStyle = ExcelLineStyle.Thin;

            //Apply Style
            worksheet.UsedRange.CellStyleName = "BodyStyle";
            bodyStyle.EndUpdate();
            #endregion

            #region Applying Header Style
            //Header Style
            IStyle headerStyle = workbook.Styles.Add("HeaderStyle");
            headerStyle.BeginUpdate();

            //Add custom colors to the palette.
            workbook.SetPaletteColor(8, Color.FromArgb(182, 189, 218));
            headerStyle.Color     = Color.FromArgb(182, 189, 218);
            headerStyle.Font.Bold = true;
            headerStyle.Borders[ExcelBordersIndex.EdgeLeft].LineStyle   = ExcelLineStyle.Thin;
            headerStyle.Borders[ExcelBordersIndex.EdgeRight].LineStyle  = ExcelLineStyle.Thin;
            headerStyle.Borders[ExcelBordersIndex.EdgeTop].LineStyle    = ExcelLineStyle.Thin;
            headerStyle.Borders[ExcelBordersIndex.EdgeBottom].LineStyle = ExcelLineStyle.Thin;

            //Apply Style
            worksheet.Range["A1:K3"].CellStyleName = "HeaderStyle";
            headerStyle.EndUpdate();
            #endregion

            //Remove grid lines in the worksheet.
            worksheet.IsGridLinesVisible = false;

            //Autofit Rows and Columns
            worksheet.UsedRange.AutofitRows();
            worksheet.UsedRange.AutofitColumns();

            //Adjust Row Height.
            worksheet.Rows[1].RowHeight = 25;

            //Freeze header row.
            worksheet.Range["A4"].FreezePanes();

            worksheet.Range["C2"].Text = "Customer Details";
            worksheet.Range["C2:D2"].Merge();
            worksheet.Range["C2"].CellStyle.Font.Size           = 14;
            worksheet.Range["C2"].CellStyle.HorizontalAlignment = ExcelHAlign.HAlignCenter;
            #endregion

            #region Workbook Save and Close
            //Saving the workbook to disk.
            workbook.SaveAs(fileName);

            //No exception will be thrown if there are unsaved workbooks.
            excelEngine.ThrowNotSavedOnDestroy = false;
            excelEngine.Dispose();
            #endregion

            #region View the Workbook
            //Message box confirmation to view the created spreadsheet.
            if (MessageBox.Show("Do you want to view the workbook?", "Workbook has been created",
                                MessageBoxButtons.YesNo, MessageBoxIcon.Information)
                == DialogResult.Yes)
            {
                //Launching the Excel file using the default Application.[MS Excel Or Free ExcelViewer]
                System.Diagnostics.Process.Start(fileName);
                //Exit
                this.Close();
            }
            else
            {
                // Exit
                this.Close();
            }
            #endregion
        }
Пример #34
0
 public override void RegisterStuff(IApplication application, IMetaDataManager metaDataManager)
 {
     RegisterDecorator <IUnityRegistrationsDecorator>(NLogUnityDecorator.Identifier, new NLogUnityDecorator(application));
 }
Пример #35
0
        /// <summary>
        /// Group or Ungroup the shapes in Excel document
        /// </summary>
        /// <returns>Return the created excel document as stream</returns>
        public MemoryStream GroupShapesXlsIO(string button, string option)
        {
            if (button == "Input Document")
            {
                //New instance of XlsIO is created.[Equivalent to launching Microsoft Excel with no workbooks open].
                //The instantiation process consists of two steps.

                //Step 1 : Instantiate the spreadsheet creation engine
                using (ExcelEngine excelEngine = new ExcelEngine())
                {
                    //Step 2 : Instantiate the excel application object
                    IApplication application = excelEngine.Excel;
                    application.DefaultVersion = ExcelVersion.Excel2016;

                    //Opening the encrypted Workbook
                    FileStream inputStream = new FileStream(ResolveApplicationPath("group-shapes.xlsx"), FileMode.Open, FileAccess.Read);
                    IWorkbook  workbook    = application.Workbooks.Open(inputStream, ExcelParseOptions.Default, true, "PASSWORD");

                    //Save the document as a stream and retrun the stream
                    using (MemoryStream stream = new MemoryStream())
                    {
                        //Save the created Excel document to MemoryStream
                        workbook.SaveAs(stream);
                        return(stream);
                    }
                }
            }
            else
            {
                //New instance of XlsIO is created.[Equivalent to launching Microsoft Excel with no workbooks open].
                //The instantiation process consists of two steps.

                //Step 1 : Instantiate the spreadsheet creation engine
                using (ExcelEngine excelEngine = new ExcelEngine())
                {
                    //Step 2 : Instantiate the excel application object
                    IApplication application = excelEngine.Excel;
                    application.DefaultVersion = ExcelVersion.Excel2016;

                    //Opening the encrypted Workbook
                    FileStream inputStream = new FileStream(ResolveApplicationPath("group-shapes.xlsx"), FileMode.Open, FileAccess.Read);
                    IWorkbook  workbook    = application.Workbooks.Open(inputStream, ExcelParseOptions.Default, true, "PASSWORD");

                    IWorksheet worksheet;

                    if (option == "Group")
                    {
                        //The first worksheet object in the worksheets collection is accessed
                        worksheet = workbook.Worksheets[0];
                        IShapes shapes = worksheet.Shapes;

                        IShape[] groupItems;
                        for (int i = 0; i < shapes.Count; i++)
                        {
                            if (shapes[i].Name == "Development" || shapes[i].Name == "Production" || shapes[i].Name == "Sales")
                            {
                                groupItems = new IShape[] { shapes[i], shapes[i + 1], shapes[i + 2], shapes[i + 3], shapes[i + 4], shapes[i + 5] };
                                shapes.Group(groupItems);
                                i = -1;
                            }
                        }

                        groupItems = new IShape[] { shapes[0], shapes[1], shapes[2], shapes[3], shapes[4], shapes[5], shapes[6] };

                        //Group the selected shapes
                        shapes.Group(groupItems);
                    }
                    else if (option == "Ungroup All")
                    {
                        //The second worksheet object in the worksheets collection is accessed
                        worksheet = workbook.Worksheets[1];
                        IShapes shapes = worksheet.Shapes;

                        //Ungroup group shape and its all the inner shapes
                        shapes.Ungroup(shapes[0] as IGroupShape, true);
                        worksheet.Activate();
                    }
                    else if (option == "Ungroup")
                    {
                        //The second worksheet object in the worksheets collection is accessed
                        worksheet = workbook.Worksheets[1];
                        IShapes shapes = worksheet.Shapes;

                        //Ungroup group shape
                        shapes.Ungroup(shapes[0] as IGroupShape);
                        worksheet.Activate();
                    }
                    //Save the document as a stream and retrun the stream
                    using (MemoryStream stream = new MemoryStream())
                    {
                        //Save the created Excel document to MemoryStream
                        workbook.SaveAs(stream);
                        return(stream);
                    }
                }
            }
        }
Пример #36
0
 public AddEventForm(IApplication app) : base(app)
 {
 }
Пример #37
0
 public override void RegisterStuff(IApplication application, IMetaDataManager metaDataManager)
 {
     RegisterDecorator <IDistributionDecorator>(EntityFrameworkDistributionDecorator.Identifier, new EntityFrameworkDistributionDecorator());
     RegisterDecorator <DistributionDecoratorBase>(Decorators.EntityFrameworkDistributionDecorator.Identifier, new Decorators.EntityFrameworkDistributionDecorator());
 }
 public WindowsApplicationEvent(IApplication application)
 {
     Application = application;
 }
 public IdentityUserDecorator(IdentityServerConfigurationTemplate template, IApplication application)
 {
     _template    = template;
     _application = application;
     Priority     = -50;
 }
Пример #40
0
        internal static Inbox Create(IDataStore dataStore, IApplicationSettings applicationSettings, IApplication application, Random random)
        {
            InboxManager manager = new InboxManager(dataStore);

            Inbox inbox = new Inbox(
                application.ApplicationId
                , "TestInbox " + random.Next(1000000, 10000000)
                , true);

            BusinessObjectActionReport <DataRepositoryActionStatus> report = manager.Create(inbox);

            Assert.AreEqual(DataRepositoryActionStatus.Success, report.Status);
            Assert.Greater(inbox.InboxId, 0);

            Inbox dsInbox = manager.GetInbox(inbox.InboxId);

            Assert.IsNotNull(dsInbox);

            return(dsInbox);
        }
Пример #41
0
 // IPlugin
 public void Unprepare()
 {
     mAppRef    = null;
     mFileData  = null;
     mAddrTrans = null;
 }
Пример #42
0
        public override void Initialize(IApplication application)
        {
            base.Initialize(application);

            WaveServices.ScreenContextManager.To(new ScreenContext(new MainScene()));
        }
        private async Task <bool> HandleCallbackAsync(
            IOwinEnvironment context,
            IClient client,
            IApplication application,
            IJwt jwt,
            string nextPath,
            CancellationToken cancellationToken)
        {
            var isNewSubscriber = false;

            if (jwt.Body.ContainsClaim("isNewSub"))
            {
                isNewSubscriber = (bool)jwt.Body.GetClaim("isNewSub");
            }

            var status = jwt.Body.GetClaim("status").ToString();

            var isLogin        = status.Equals("authenticated", StringComparison.OrdinalIgnoreCase);
            var isLogout       = status.Equals("logout", StringComparison.OrdinalIgnoreCase);
            var isRegistration = isNewSubscriber || status.Equals("registered", StringComparison.OrdinalIgnoreCase);

            if (isRegistration)
            {
                var grantResult = await ExchangeTokenAsync(application, jwt, cancellationToken);

                var registrationExecutor = new RegisterExecutor(client, _configuration, _handlers, _logger);
                var account = await(await grantResult.GetAccessTokenAsync(cancellationToken)).GetAccountAsync(cancellationToken);
                await registrationExecutor.HandlePostRegistrationAsync(context, account, cancellationToken);

                return(await LoginAndRedirectAsync(
                           context,
                           client,
                           grantResult,
                           true,
                           nextPath,
                           cancellationToken));
            }

            if (isLogin)
            {
                var grantResult = await ExchangeTokenAsync(application, jwt, cancellationToken);

                return(await LoginAndRedirectAsync(
                           context,
                           client,
                           grantResult,
                           false,
                           nextPath,
                           cancellationToken));
            }

            if (isLogout)
            {
                var executor = new LogoutExecutor(client, _configuration, _handlers, _logger);

                await executor.HandleLogoutAsync(context, cancellationToken);

                await executor.HandleRedirectAsync(context);

                return(true);
            }

            // json response
            throw new ArgumentException($"Unknown assertion status '{status}'");
        }
 public override object CreateDecoratorInstance(IApplication application)
 {
     return(new ExceptionHandlerFilterWebApiConfigDecorator());
 }
Пример #45
0
        void OnButtonClicked(object sender, EventArgs e)
        {
            ExcelEngine  excelEngine = new ExcelEngine();
            IApplication application = excelEngine.Excel;

            application.DefaultVersion = ExcelVersion.Excel2013;

            #region Initializing Workbook
            Assembly assembly = typeof(App).GetTypeInfo().Assembly;

            Stream fileStream = null;
                        #if COMMONSB
            fileStream = assembly.GetManifestResourceStream("SampleBrowser.Samples.XlsIO.Samples.Template.ReplaceOptions.xlsx");
                        #else
            fileStream = assembly.GetManifestResourceStream("SampleBrowser.XlsIO.Samples.Template.ReplaceOptions.xlsx");
                        #endif

            IWorkbook workbook = application.Workbooks.Open(fileStream);
            //The first worksheet object in the worksheets collection is accessed.
            IWorksheet sheet = workbook.Worksheets[0];
            #endregion

            int    replaceIndex = this.picker.SelectedIndex;
            string replaceText;

            switch (replaceIndex)
            {
            default:
            case 0:
                replaceText = "Berlin";
                break;

            case 1:
                replaceText = "8000";
                break;

            case 2:
                replaceText = "Representative";
                break;
            }
            ExcelFindOptions option = ExcelFindOptions.None;

            if (switch1.IsToggled)
            {
                option |= ExcelFindOptions.MatchCase;
            }

            if (switch2.IsToggled)
            {
                option |= ExcelFindOptions.MatchEntireCellContent;
            }
            MemoryStream stream = null;
            try
            {
                if (entry.Text != null && entry.Text != "")
                {
                    sheet.Replace(replaceText, entry.Text, option);
                }
                stream = new MemoryStream();
                workbook.SaveAs(stream);
            }
            catch (Exception exception)
            {
                Error.Text = "Given string is invalid.";
            }
            workbook.Version = ExcelVersion.Excel2013;
            workbook.Close();
            excelEngine.Dispose();

            if (stream != null)
            {
                if (Device.OS == TargetPlatform.WinPhone || Device.OS == TargetPlatform.Windows)
                {
                    Xamarin.Forms.DependencyService.Get <ISaveWindowsPhone>().Save("FindAndReplace.xlsx", "application/msexcel", stream);
                }
                else
                {
                    Xamarin.Forms.DependencyService.Get <ISave>().Save("FindAndReplace.xlsx", "application/msexcel", stream);
                }
            }
        }
Пример #46
0
 // IPlugin
 public void Prepare(IApplication appRef, byte[] fileData, AddressTranslate addrTrans)
 {
     mAppRef    = appRef;
     mFileData  = fileData;
     mAddrTrans = addrTrans;
 }
Пример #47
0
 public void DisplayApplicationWithoutSession(IApplication application)
 {
     base.Channel.DisplayApplicationWithoutSession(application);
 }
Пример #48
0
 public frmPlateAndShell(IApplication app)
 {
     InitializeComponent();
     this.app = app;
 }
Пример #49
0
        public async Task <HttpResponseMessage> HandleRouteAsync(Type controllerType,
                                                                 IApplication httpApp, HttpRequestMessage request, string routeName,
                                                                 RouteHandlingDelegate continueExecution)
        {
            var stopwatch = Stopwatch.StartNew();
            var requestId = Guid.NewGuid().ToString("N");
            var telemetry = new RequestTelemetry()
            {
                Id        = requestId,
                Source    = "EastFive.Api",
                Timestamp = DateTimeOffset.UtcNow,
                Url       = request.RequestUri,
            };

            #region User / Session

            var claims = request.GetClaims(
                claimsEnumerable => claimsEnumerable.ToArray(),
                () => new Claim[] { },
                (why) => new Claim[] { });
            var sessionIdClaimType = BlackBarLabs.Security.ClaimIds.Session;
            var sessionIdMaybe     = SessionToken.GetClaimIdMaybe(claims, sessionIdClaimType);
            if (sessionIdMaybe.HasValue)
            {
                telemetry.Context.Session.Id = sessionIdMaybe.Value.ToString().ToUpper();
            }

            var accountIdClaimType = EastFive.Api.AppSettings.ActorIdClaimType.ConfigurationString(
                (accIdCT) => accIdCT,
                (why) => default);
            if (accountIdClaimType.HasBlackSpace())
            {
                var accountIdMaybe = SessionToken.GetClaimIdMaybe(claims, accountIdClaimType);
                if (accountIdMaybe.HasValue)
                {
                    var accountIdStr = accountIdMaybe.Value.ToString().ToUpper();
                    telemetry.Context.User.AccountId           = accountIdStr;
                    telemetry.Context.User.AuthenticatedUserId = accountIdStr;
                }
            }

            foreach (var claim in claims)
            {
                telemetry.Properties.Add($"claim[{claim.Type}]", claim.Value);
            }

            #endregion

            request.Properties.Add(HttpRequestMessagePropertyRequestTelemetryKey, telemetry);
            var response = await continueExecution(controllerType, httpApp, request, routeName);

            telemetry.ResponseCode = response.StatusCode.ToString();
            if (response.ReasonPhrase.HasBlackSpace())
            {
                telemetry.Properties.AddOrReplace("reason_phrase", response.ReasonPhrase);
            }
            telemetry.Success = response.IsSuccessStatusCode;

            #region Method result identfiers

            if (response.Headers.TryGetValues(HeaderStatusName, out IEnumerable <string> statusNames))
            {
                if (statusNames.Any())
                {
                    telemetry.Properties.Add(TelemetryStatusName, statusNames.First());
                }
            }
            if (response.Headers.TryGetValues(HeaderStatusInstance, out IEnumerable <string> statusInstances))
            {
                if (statusInstances.Any())
                {
                    telemetry.Properties.Add(TelemetryStatusInstance, statusInstances.First());
                }
            }

            #endregion

            var telemetryClient = AppSettings.ApplicationInsights.InstrumentationKey.LoadTelemetryClient();
            telemetry.Duration = stopwatch.Elapsed;
            telemetryClient.TrackRequest(telemetry);

            return(response);
        }
Пример #50
0
        private void btnExport_Click(object sender, EventArgs e)
        {
            #region Initialize Workbook
            //New instance of XlsIO is created.[Equivalent to launching MS Excel with no workbooks open].
            //The instantiation process consists of two steps.
            //Instantiate the spreadsheet creation engine.
            ExcelEngine excelEngine = new ExcelEngine();
            //Step 2 : Instantiate the excel application object.
            IApplication application = excelEngine.Excel;
            //Set the Default version as Excel 97to2003
            if (this.rdbExcel97.Checked)
            {
                application.DefaultVersion = ExcelVersion.Excel97to2003;
                fileName = "CollectionObject.xls";
            }
            //Set the Default version as Excel 2007
            else if (this.rdbExcel2007.Checked)
            {
                application.DefaultVersion = ExcelVersion.Excel2007;
                fileName = "CollectionObject.xlsx";
            }
            else if (this.rdbExcel2010.Checked)
            {
                application.DefaultVersion = ExcelVersion.Excel2010;
                fileName = "CollectionObject.xlsx";
            }
            else if (this.rdbExcel2013.Checked)
            {
                application.DefaultVersion = ExcelVersion.Excel2013;
                fileName = "CollectionObject.xlsx";
            }
            //Create a new spreadsheet.
            IWorkbook workbook = excelEngine.Excel.Workbooks.Create(1);
            //The first worksheet object in the worksheets collection is accessed.
            IWorksheet sheet = workbook.Worksheets[0];

            sheet.ImportData((List <Brand>) this.dataGridView1.DataSource, 4, 1, true);

            #region Define Styles
            IStyle pageHeader  = workbook.Styles.Add("PageHeaderStyle");
            IStyle tableHeader = workbook.Styles.Add("TableHeaderStyle");

            pageHeader.Font.FontName       = "Calibri";
            pageHeader.Font.Size           = 16;
            pageHeader.Font.Bold           = true;
            pageHeader.Color               = Color.FromArgb(0, 146, 208, 80);
            pageHeader.HorizontalAlignment = ExcelHAlign.HAlignCenter;
            pageHeader.VerticalAlignment   = ExcelVAlign.VAlignCenter;

            tableHeader.Font.Bold     = true;
            tableHeader.Font.FontName = "Calibri";
            tableHeader.Color         = Color.FromArgb(0, 146, 208, 80);

            #endregion

            #region Apply Styles
            // Apply style for header
            sheet["A1:C2"].Merge();
            sheet["A1"].Text      = "Automobile Brands in the US";
            sheet["A1"].CellStyle = pageHeader;

            sheet["A4:C4"].CellStyle = tableHeader;

            sheet["A1:C1"].CellStyle.Font.Bold = true;
            sheet.UsedRange.AutofitColumns();

            #endregion

            #endregion

            #region Save the Workbook
            //Saving the workbook to disk. This spreadsheet is the result of opening and modifying
            //an existing spreadsheet and then saving the result to a new workbook.
            workbook.SaveAs(fileName);
            #endregion

            #region Workbook Close and Dispose
            //Close the workbook.
            workbook.Close();

            excelEngine.Dispose();
            #endregion

            #region View the Workbook
            //Message box confirmation to view the created spreadsheet.
            if (MessageBox.Show("Do you want to view the workbook?", "Workbook has been created",
                                MessageBoxButtons.YesNo, MessageBoxIcon.Information)
                == DialogResult.Yes)
            {
                //Launching the Excel file using the default Application.[MS Excel Or Free ExcelViewer]
#if NETCORE
                System.Diagnostics.Process process = new System.Diagnostics.Process();
                process.StartInfo = new System.Diagnostics.ProcessStartInfo(fileName)
                {
                    UseShellExecute = true
                };
                process.Start();
#else
                Process.Start(fileName);
#endif
            }
            // Exit
            //this.Close();
            #endregion
        }
Пример #51
0
 public OptionsDialogHandler(IApplication app)
 {
     _app = app;
 }
Пример #52
0
        private void modernButton3_Click(object sender, EventArgs e)
        {
            Log("%TEST%");
            var ew = new ExcelWindow("Test#3");

            ew.spreadsheet1.Open("Data\\Test\\c5.xlsx");
            ew.ShowDialog();
            //ExcelOperator2 ex=new ExcelOperator2(ew.spreadsheet1);
            var s = ew.spreadsheet1.ActiveSheet;
            var l = s.ExportDataTable(s.UsedRange, ExcelExportDataTableOptions.ColumnNames | ExcelExportDataTableOptions.ComputedFormulaValues);
            //MessageBox.Show($"{l.Rows[0][0].ToString()}");
            //ScoreTable st=new ScoreTable(new Dictionary<string, ScoreModel>(),new InputDataIndicator() );
            List <ScoreModel> li = new List <ScoreModel>();

            for (int j = 0; j < l.Rows.Count; j++)
            {
                ScoreModel sm = new ScoreModel();
                for (int i = 0; i < l.Columns.Count; i++)
                {
                    switch (i)
                    {
                    case 0:
                        sm.Name = l.Rows[j][i].ToString();
                        break;

                    case 1:
                        sm.Id = Int32.Parse(l.Rows[j][i].ToString());
                        break;

                    case 2:
                        sm.SumRank = Int32.Parse(l.Rows[j][i].ToString());
                        break;

                    case 3:
                        sm.SumGradeRank = Int32.Parse(l.Rows[j][i].ToString());
                        break;

                    case 4:
                        sm.Zh = Single.Parse(l.Rows[j][i].ToString());
                        break;

                    case 5:
                        sm.ZhRank = Int32.Parse(l.Rows[j][i].ToString());
                        break;

                    case 6:
                        sm.ZhGradeRank = int.Parse(l.Rows[j][i].ToString());
                        break;

                    case 7:
                        sm.M = float.Parse(l.Rows[j][i].ToString());
                        break;

                    case 8:
                        sm.MRank = int.Parse(l.Rows[j][i].ToString());
                        break;

                    case 9:
                        sm.MGradeRank = int.Parse(l.Rows[j][i].ToString());
                        break;

                    case 10:
                        sm.En = float.Parse(l.Rows[j][i].ToString());
                        break;

                    case 11:
                        sm.EnRank = int.Parse(l.Rows[j][i].ToString());
                        break;

                    case 12:
                        sm.EnGradeRank = int.Parse(l.Rows[j][i].ToString());
                        break;

                    case 13:
                        sm.P = float.Parse(l.Rows[j][i].ToString());
                        break;

                    case 14:
                        sm.PRank = int.Parse(l.Rows[j][i].ToString());
                        break;

                    case 15:
                        sm.PGradeRank = int.Parse(l.Rows[j][i].ToString());
                        break;

                    case 16:
                        sm.C = float.Parse(l.Rows[j][i].ToString());
                        break;

                    case 17:
                        sm.CRank = int.Parse(l.Rows[j][i].ToString());
                        break;

                    case 18:
                        sm.CGradeRank = int.Parse(l.Rows[j][i].ToString());
                        break;

                    case 19:
                        sm.Po = float.Parse(l.Rows[j][i].ToString());
                        break;

                    case 20:
                        sm.PoRank = Int32.Parse(l.Rows[j][i].ToString());
                        break;

                    case 21:
                        sm.PoGradeRank = Int32.Parse(l.Rows[j][i].ToString());
                        break;

                    case 22:
                        sm.H = float.Parse(l.Rows[j][i].ToString());
                        break;

                    case 23:
                        sm.HRank = int.Parse(l.Rows[j][i].ToString());
                        break;

                    case 24:
                        sm.HGradeRank = int.Parse(l.Rows[j][i].ToString());
                        break;

                    case 25:
                        sm.G = float.Parse(l.Rows[j][i].ToString());
                        break;

                    case 26:
                        sm.GRank = int.Parse(l.Rows[j][i].ToString());
                        break;

                    case 27:
                        sm.GGradeRank = int.Parse(l.Rows[j][i].ToString());
                        break;

                    case 28:
                        sm.B = float.Parse(l.Rows[j][i].ToString());
                        break;

                    case 29:
                        sm.BRank = int.Parse(l.Rows[j][i].ToString());
                        break;

                    case 30:
                        sm.BGradeRank = int.Parse(l.Rows[j][i].ToString());
                        break;

                    default: throw new NotImplementedException();
                        break;
                    }
                }
                li.Add(sm);
                //MessageBox.Show($"%C# {name}%=>%JSON%:\r\n{sm.ToString()}");
            }
            IList <(NfSubjects, float)> aveList = Analyzer.Average(li);
            //BindingList<(NfSubjects, float)> aveBindingList = Analyzer.Average(li);//todo;
            IList <(NfSubjects, float)>   sumList  = Analyzer.Sum(li);
            IList <(NfSubjects, float[])> modeList = Analyzer.Mode(li);
            IList <(NfSubjects, double)>  midList  = Analyzer.Mid(li);

            Log("Average:\r\n" + string.Join(",", aveList));
            Log("Sum:\r\n" + string.Join(",", sumList));
            Log("Mode:");
            foreach (var mode in modeList)
            {
                Log($"{mode.Item1.ToString()}:{string.Join(",",mode.Item2)}");
            }
            //Log("Mode:\r\n" + string.Join(",",modeList));
            Log("Mid:\r\n" + string.Join(",", midList));
            //MessageBox.Show(aveList[0].Item2.ToString());
            DataVisualization dv = new DataVisualization();

            dv.lDChartDataSourceBindingSource.DataSource = new LDChartDataSource(aveList);

            #region Data Convert:
            ChartSeries                 cs     = new ChartSeries("%Title%");
            ChartDataBindModel          cdbm   = new ChartDataBindModel(aveList);
            ChartDataBindAxisLabelModel cdbalm = new ChartDataBindAxisLabelModel(aveList);
            cdbm.XName       = "Item1";
            cdbalm.LabelName = "Item1";
            cdbm.YNames      = new String[] { "Item2" };
            cs.SeriesModel   = cdbm;
            dv.chartControl1.Series.Add(cs);
            dv.chartControl1.PrimaryXAxis.LabelsImpl = cdbalm;
            dv.chartControl2.Series.Add(cs);
            dv.chartControl2.PrimaryXAxis.LabelsImpl = cdbalm;
            dv.chartControl2.PrimaryYAxis.Range      = new MinMaxInfo(0, 150, 100);
            #endregion

            dv.Show();

            //#region PPT Output

            //IPresentation ip = Presentation.Create();
            //IList<double> avelist_ppt=new List<double>();
            //foreach (var ii in aveList)
            //{
            //	avelist_ppt.Add(ii.Item2);
            //}
            //ISlide sl = ip.Slides.Add(SlideLayoutType.Blank);
            //IPresentationChart ct = sl.Shapes.AddChart(avelist_ppt, 5, 5, 100, 100);
            //Spire.Presentation.Presentation ppt =new Spire.Presentation.Presentation(File.Open($"{new Random().Next()}.pptx",FileMode.Create,FileAccess.ReadWrite),FileFormat.Pptx2010);
            //var cts = ppt.Slides[0].Shapes.AppendChart(ChartType.Column3D,new RectangleF(5,5,200,200));

            //foreach (var ave in avelist_ppt)
            //{
            //	//cts.Series.Append(ave);
            //	cts.Series[0].Values.Add(ave);
            //}

            //ip.Save($"{new Random().Next()}.pptx");
            //#endregion

            #region ExcelChart

            ExcelEngine  ee  = new ExcelEngine();
            IApplication xls = ee.Excel;
            xls.DefaultVersion = Syncfusion.XlsIO.ExcelVersion.Excel2016;
            IWorkbook   wb    = xls.Workbooks.Open("Data\\Test\\c5.xlsx", ExcelOpenType.Automatic);
            IWorksheet  ws    = wb.Worksheets.Create("Chart");
            IChartShape chart = ws.Charts.Add();
            /////////////////////////////////////////////////////
            //IChartSerie serie = chart.Series.Add(Syncfusion.XlsIO.ExcelChartType.Column_Clustered);
            //chart.ChartType = Syncfusion.XlsIO.ExcelChartType.Column_Clustered;
            IList <string> xave = new List <string>();
            IList <object> yave = new List <object>();
            int            allavei = Int32.MaxValue, allmidi = Int32.MaxValue;
            for (var index = 0; index < aveList.Count; index++)
            {
                if (aveList[index].Item1 == NfSubjects.All)
                {
                    allavei = index;
                }
                var ave = aveList[index];
                xave.Add(ave.Item1.Name());
                yave.Add(ave.Item2);
            }

            //serie.EnteredDirectlyValues = yave.ToArray();
            //serie.Name = "平均分";
            //serie.EnteredDirectlyCategoryLabels = xave.ToArray();
            ChartGen.GenChart(chart, xave.ToArray(), yave.ToArray(), "平均分", ExcelChartType.Column_Clustered);
            ////////////////////////////////////////////////
            //IChartSerie seriemid = chart.Series.Add(Syncfusion.XlsIO.ExcelChartType.Column_Clustered);
            //chart.ChartType = Syncfusion.XlsIO.ExcelChartType.Column_Clustered;
            IList <string> xmid = new List <string>();
            IList <object> ymid = new List <object>();
            for (var index = 0; index < midList.Count; index++)
            {
                if (midList[index].Item1 == NfSubjects.All)
                {
                    allmidi = index;
                }
                var mid = midList[index];
                xmid.Add(mid.Item1.Name());
                ymid.Add(mid.Item2);
            }
            ChartGen.GenChart(chart, xmid.ToArray(), ymid.ToArray(), "中位分", ExcelChartType.Column_Clustered);
            //{{{{{{{{{{{{{{
            xave.RemoveAt(allavei);
            yave.RemoveAt(allavei);
            xmid.RemoveAt(allmidi);
            ymid.RemoveAt(allmidi);
            IChartShape leida = ws.Shapes.AddChart();

            ChartGen.GenChart(leida, xave.ToArray(), yave.ToArray(), "平均分", ExcelChartType.Radar);
            ChartGen.GenChart(leida, xmid.ToArray(), ymid.ToArray(), "中位分", ExcelChartType.Radar);
            leida.Name       = "学科成绩分布1";
            leida.ChartTitle = "学科成绩分布1";
            //}}}}}}}}}}}}}}
            //{{{{{{{{{{{{{{
            var         xyave  = Analyzer.ReArrangeData(aveList);
            var         xymid  = Analyzer.ReArrangeData(midList);
            IChartShape leida2 = ws.Shapes.AddChart();

            ChartGen.GenChart(leida2, xyave.Item1, xyave.Item2, "平均分", ExcelChartType.Radar);
            ChartGen.GenChart(leida2, xymid.Item1, xymid.Item2, "中位分", ExcelChartType.Radar);
            leida2.Name       = "学科成绩分布2";
            leida2.ChartTitle = "学科成绩分布2";
            //}}}}}}}}}}}}}}
            var ordered = li.OrderBy(pp => pp.Sum);
            ChartGen.GenChart(ws.Shapes.AddChart(), ordered.Select(sm => (object)(sm.Name)).ToArray(), ordered.Select(sm => (object)(sm.Sum ?? 0)).ToArray(), "总分", ExcelChartType.Column_3D);
            //seriemid.EnteredDirectlyValues = ymid.ToArray();
            //seriemid.Name = "中位分";
            //seriemid.EnteredDirectlyCategoryLabels = xmid.ToArray();
            /////////////////////////////////////////////////
            xls.Save("output.xlsx");
            wb.Close();
            ee.Dispose();
            #endregion
        }
 private void OnApplicationCreatedEventHandler(IApplication app)
 {
 }
        void OnButtonClicked(object sender, EventArgs e)
        {
            //Instantiate excel engine
            ExcelEngine excelEngine = new ExcelEngine();
            //Excel application
            IApplication application = excelEngine.Excel;

            application.DefaultVersion = ExcelVersion.Excel2013;

            #region Initializing Workbook
            //A new workbook is created.[Equivalent to creating a new workbook in MS Excel]
            //The new workbook will have 1 worksheet
            IWorkbook workbook = application.Workbooks.Create(1);

            //The first worksheet object in the worksheets collection is accessed.
            IWorksheet sheet = workbook.Worksheets[0];
            #endregion

            #region Generate Excel

            sheet.EnableSheetCalculations();

            sheet.Range["A2"].ColumnWidth = 20;
            sheet.Range["B2"].ColumnWidth = 13;
            sheet.Range["C2"].ColumnWidth = 13;
            sheet.Range["D2"].ColumnWidth = 13;

            sheet.Range["A2:D2"].Merge(true);

            //Inserting sample text into the first cell of the first worksheet.
            sheet.Range["A2"].Text = "EXPENSE REPORT";
            sheet.Range["A2"].CellStyle.Font.FontName = "Verdana";
            sheet.Range["A2"].CellStyle.Font.Bold     = true;
            sheet.Range["A2"].CellStyle.Font.Size     = 28;
            sheet.Range["A2"].CellStyle.Font.RGBColor = COLOR.Color.FromArgb(255, 0, 112, 192);
            sheet.Range["A2"].HorizontalAlignment     = ExcelHAlign.HAlignCenter;
            sheet.Range["A2"].RowHeight = 34;

            sheet.Range["A4"].Text = "Employee";
            sheet.Range["B4"].Text = "Roger Federer";
            sheet.Range["A4:B7"].CellStyle.Font.FontName = "Verdana";
            sheet.Range["A4:B7"].CellStyle.Font.Bold     = true;
            sheet.Range["A4:B7"].CellStyle.Font.Size     = 11;
            sheet.Range["A4:A7"].CellStyle.Font.RGBColor = COLOR.Color.FromArgb(255, 128, 128, 128);
            sheet.Range["A4:A7"].HorizontalAlignment     = ExcelHAlign.HAlignLeft;
            sheet.Range["B4:B7"].CellStyle.Font.RGBColor = COLOR.Color.FromArgb(255, 174, 170, 170);
            sheet.Range["B4:B7"].HorizontalAlignment     = ExcelHAlign.HAlignRight;
            sheet.Range["B4:D4"].Merge(true);

            sheet.Range["A9:D20"].CellStyle.Font.FontName = "Verdana";
            sheet.Range["A9:D20"].CellStyle.Font.Size     = 11;

            sheet.Range["A5"].Text = "Department";
            sheet.Range["B5"].Text = "Administration";
            sheet.Range["B5:D5"].Merge(true);

            sheet.Range["A6"].Text         = "Week Ending";
            sheet.Range["B6"].NumberFormat = "m/d/yyyy";
            sheet.Range["B6"].DateTime     = DateTime.Parse("10/10/2012");
            sheet.Range["B6:D6"].Merge(true);

            sheet.Range["A7"].Text         = "Mileage Rate";
            sheet.Range["B7"].NumberFormat = "$#,##0.00";
            sheet.Range["B7"].Number       = 0.70;
            sheet.Range["B7:D7"].Merge(true);

            sheet.Range["A10"].Text = "Miles Driven";
            sheet.Range["A11"].Text = "Reimbursement";
            sheet.Range["A12"].Text = "Parking/Tolls";
            sheet.Range["A13"].Text = "Auto Rental";
            sheet.Range["A14"].Text = "Lodging";
            sheet.Range["A15"].Text = "Breakfast";
            sheet.Range["A16"].Text = "Lunch";
            sheet.Range["A17"].Text = "Dinner";
            sheet.Range["A18"].Text = "Snacks";
            sheet.Range["A19"].Text = "Others";
            sheet.Range["A20"].Text = "Total";
            sheet.Range["A20:D20"].CellStyle.Color      = COLOR.Color.FromArgb(255, 0, 112, 192);
            sheet.Range["A20:D20"].CellStyle.Font.Color = ExcelKnownColors.Black;
            sheet.Range["A20:D20"].CellStyle.Font.Bold  = true;

            IStyle style = sheet["B9:D9"].CellStyle;
            style.VerticalAlignment   = ExcelVAlign.VAlignCenter;
            style.HorizontalAlignment = ExcelHAlign.HAlignRight;
            style.Color      = COLOR.Color.FromArgb(255, 0, 112, 192);
            style.Font.Bold  = true;
            style.Font.Color = ExcelKnownColors.Black;

            sheet.Range["A9"].Text                 = "Expenses";
            sheet.Range["A9"].CellStyle.Color      = COLOR.Color.FromArgb(255, 0, 112, 192);
            sheet.Range["A9"].CellStyle.Font.Color = ExcelKnownColors.White;
            sheet.Range["A9"].CellStyle.Font.Bold  = true;
            sheet.Range["B9"].Text                 = "Day 1";
            sheet.Range["B10"].Number              = 100;
            sheet.Range["B11"].NumberFormat        = "$#,##0.00";
            sheet.Range["B11"].Formula             = "=(B7*B10)";
            sheet.Range["B12"].NumberFormat        = "$#,##0.00";
            sheet.Range["B12"].Number              = 0;
            sheet.Range["B13"].NumberFormat        = "$#,##0.00";
            sheet.Range["B13"].Number              = 0;
            sheet.Range["B14"].NumberFormat        = "$#,##0.00";
            sheet.Range["B14"].Number              = 0;
            sheet.Range["B15"].NumberFormat        = "$#,##0.00";
            sheet.Range["B15"].Number              = 9;
            sheet.Range["B16"].NumberFormat        = "$#,##0.00";
            sheet.Range["B16"].Number              = 12;
            sheet.Range["B17"].NumberFormat        = "$#,##0.00";
            sheet.Range["B17"].Number              = 13;
            sheet.Range["B18"].NumberFormat        = "$#,##0.00";
            sheet.Range["B18"].Number              = 9.5;
            sheet.Range["B19"].NumberFormat        = "$#,##0.00";
            sheet.Range["B19"].Number              = 0;
            sheet.Range["B20"].NumberFormat        = "$#,##0.00";
            sheet.Range["B20"].Formula             = "=SUM(B11:B19)";

            sheet.Range["C9"].Text          = "Day 2";
            sheet.Range["C10"].Number       = 145;
            sheet.Range["C11"].NumberFormat = "$#,##0.00";
            sheet.Range["C11"].Formula      = "=(B7*C10)";
            sheet.Range["C12"].NumberFormat = "$#,##0.00";
            sheet.Range["C12"].Number       = 15;
            sheet.Range["C13"].NumberFormat = "$#,##0.00";
            sheet.Range["C13"].Number       = 0;
            sheet.Range["C14"].NumberFormat = "$#,##0.00";
            sheet.Range["C14"].Number       = 45;
            sheet.Range["C15"].NumberFormat = "$#,##0.00";
            sheet.Range["C15"].Number       = 9;
            sheet.Range["C16"].NumberFormat = "$#,##0.00";
            sheet.Range["C16"].Number       = 12;
            sheet.Range["C17"].NumberFormat = "$#,##0.00";
            sheet.Range["C17"].Number       = 15;
            sheet.Range["C18"].NumberFormat = "$#,##0.00";
            sheet.Range["C18"].Number       = 7;
            sheet.Range["C19"].NumberFormat = "$#,##0.00";
            sheet.Range["C19"].Number       = 0;
            sheet.Range["C20"].NumberFormat = "$#,##0.00";
            sheet.Range["C20"].Formula      = "=SUM(C11:C19)";

            sheet.Range["D9"].Text          = "Day 3";
            sheet.Range["D10"].Number       = 113;
            sheet.Range["D11"].NumberFormat = "$#,##0.00";
            sheet.Range["D11"].Formula      = "=(B7*D10)";
            sheet.Range["D12"].NumberFormat = "$#,##0.00";
            sheet.Range["D12"].Number       = 17;
            sheet.Range["D13"].NumberFormat = "$#,##0.00";
            sheet.Range["D13"].Number       = 8;
            sheet.Range["D14"].NumberFormat = "$#,##0.00";
            sheet.Range["D14"].Number       = 45;
            sheet.Range["D15"].NumberFormat = "$#,##0.00";
            sheet.Range["D15"].Number       = 7;
            sheet.Range["D16"].NumberFormat = "$#,##0.00";
            sheet.Range["D16"].Number       = 11;
            sheet.Range["D17"].NumberFormat = "$#,##0.00";
            sheet.Range["D17"].Number       = 16;
            sheet.Range["D18"].NumberFormat = "$#,##0.00";
            sheet.Range["D18"].Number       = 7;
            sheet.Range["D19"].NumberFormat = "$#,##0.00";
            sheet.Range["D19"].Number       = 5;
            sheet.Range["D20"].NumberFormat = "$#,##0.00";
            sheet.Range["D20"].Formula      = "=SUM(D11:D19)";

            sheet.Range["A10:D10"].CellStyle.Font.RGBColor = COLOR.Color.FromArgb(255, 174, 170, 170);
            #endregion

            workbook.Version = ExcelVersion.Excel2013;

            MemoryStream stream = new MemoryStream();
            workbook.SaveAs(stream);
            workbook.Close();
            excelEngine.Dispose();


            if (stream != null)
            {
                SaveiOS iOSSave = new SaveiOS();
                iOSSave.Save("CreateSheet.xlsx", "application/msexcel", stream);
            }
        }
Пример #55
0
 public static void SetApplicationHandler(this PlatformApplication platformApplication, IApplication application, IMauiContext context) =>
 SetHandler(platformApplication, application, context);
Пример #56
0
        static async Task Main(string[] args)
        {
            try
            {
                Console.OutputEncoding = Encoding.GetEncoding(936);
            }
            catch
            {
                try
                {
                    Console.OutputEncoding = Encoding.UTF8;
                }
                catch
                {
                    // ignored
                }
            }

            ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls;

            var contentRootPath = Directory.GetCurrentDirectory();

            var profilePath = CliUtils.GetOsUserConfigFilePath();
            var sscmsPath   = PathUtils.Combine(contentRootPath, Constants.ConfigFileName);

            var builder = new ConfigurationBuilder()
                          .SetBasePath(contentRootPath)
                          .AddJsonFile(profilePath, optional: true, reloadOnChange: true)
                          .AddJsonFile(sscmsPath, optional: true, reloadOnChange: true)
                          .AddEnvironmentVariables();

            var configuration = builder.Build();

            Log.Logger = new LoggerConfiguration()
                         .WriteTo.File("logs/cli/log.log", rollingInterval: RollingInterval.Day)
                         .Enrich.FromLogContext()
                         .CreateLogger();

            var services = new ServiceCollection();

            var entryAssembly = Assembly.GetExecutingAssembly();
            var assemblies = new List <Assembly> {
                entryAssembly
            }.Concat(entryAssembly.GetReferencedAssemblies().Select(Assembly.Load));

            var settingsManager = services.AddSettingsManager(configuration, contentRootPath, PathUtils.Combine(contentRootPath, Constants.WwwrootDirectory), entryAssembly);

            services.AddPlugins(configuration, settingsManager);
            //services.AddPluginServices(pluginManager);

            Application = new Application(settingsManager);
            services.AddSingleton <IConfiguration>(configuration);
            services.AddCache(settingsManager.Redis.ConnectionString);

            services.AddRepositories(assemblies);
            services.AddServices();
            services.AddCliServices();
            services.AddCliJobs();

            await Application.RunAsync(args);
        }
Пример #57
0
        protected void bExport_Click(object sender, EventArgs e)
        {
            try
            {
                excelEngine = new ExcelEngine();
                IApplication application = excelEngine.Excel;
                workbook       = application.Workbooks.Open(Request.MapPath("~/App_Data/ExportMetricTemplate.xls"));
                AnyPeriodExist = false;

                if (rbIntervalCommon.Checked)
                {
                    if (dpCommonFrom.IsEmpty)
                    {
                        return;
                    }
                    if (dpCommonTo.IsEmpty)
                    {
                        return;
                    }
                    CommonBegin = dpCommonFrom.SelectedDate;
                    CommonEnd   = dpCommonTo.SelectedDate;
                }
                else if (rbIntervalFull.Checked)
                {
                    MetricTrac.Bll.MetricValue.GetFullDateRange(out CommonBegin, out CommonEnd);
                }

                if (phDaily.Visible)
                {
                    AddExportPeriod(dpSelectDayFrom.SelectedDate, dpSelectDayTo.SelectedDate, 1, "Daily", "Day");
                }
                if (phWeekly.Visible)
                {
                    AddExportPeriod(cSelectWeekFrom.SelectedDate, cSelectWeekTo.SelectedDate, 2, "Weekly", "Week");
                }
                if (phMonthly.Visible)
                {
                    AddExportPeriod(cSelectMonthFrom.SelectedDate, cSelectMonthTo.SelectedDate, 3, "Monthly", "Month");
                }

                if (phQtrly.Visible)
                {
                    AddExportPeriod(cSelectQuarterFrom.SelectedDate, cSelectQuarterTo.SelectedDate, 4, "Quarterly", "Quarter");
                }
                if (phSemiAnnual.Visible)
                {
                    AddExportPeriod(cSelectSemiYearFrom.SelectedDate, cSelectSemiYearTo.SelectedDate, 5, "Semiannual", "Semi-year");
                }
                if (phAnnual.Visible)
                {
                    AddExportPeriod(cSelectYearFrom.SelectedDate, cSelectYearTo.SelectedDate, 6, "Annual", "Year");
                }
                if (phBiAnnual.Visible)
                {
                    AddExportPeriod(cSelectBiYearFrom.SelectedDate, cSelectBiYearTo.SelectedDate, 7, "Biannual", "Bi-year");
                }

                if (phFiscalQtrly.Visible)
                {
                    AddExportPeriod(cSelectFiscalQuarterFrom.SelectedDate, cSelectFiscalQuarterTo.SelectedDate, 4, "Quarterly", "Quarter");
                }
                if (phFiscalSemiAnnual.Visible)
                {
                    AddExportPeriod(cSelectFiscalSemiYearFrom.SelectedDate, cSelectFiscalSemiYearTo.SelectedDate, 5, "Semiannual", "Semi-year");
                }
                if (phFiscalAnnual.Visible)
                {
                    AddExportPeriod(cSelectFiscalYearFrom.SelectedDate, cSelectFiscalYearTo.SelectedDate, 6, "Annual", "Year");
                }
                if (phFiscalBiAnnual.Visible)
                {
                    AddExportPeriod(cSelectFiscalBiYearFrom.SelectedDate, cSelectFiscalBiYearTo.SelectedDate, 7, "Biannual", "Bi-year");
                }
                if (!AnyPeriodExist)
                {
                    return;
                }
                workbook.Worksheets.Remove(0);
                workbook.SaveAs("MetricExport.xls", ExcelSaveType.SaveAsXLS, Response, ExcelDownloadType.PromptDialog);
            }
            finally
            {
                try
                {
                    workbook.Close();
                    excelEngine.Dispose();
                }
                catch { }
            }
        }
        public ActionResult ExcelToPDF(string button, string checkboxStream, string checkboxName, string Group1)
        {
            if (button == null)
                return View();
            ExcelEngine excelEngine = new ExcelEngine();
            IApplication application = excelEngine.Excel;
            IWorkbook workbook;
            if (button == "Input Template")
            {
                if (checkboxStream != null || checkboxName != null)
                {
                    workbook = application.Workbooks.Open(ResolveApplicationDataPath(@"invoiceTemplate.xlsx"), ExcelOpenType.Automatic);
                    return excelEngine.SaveAsActionResult(workbook, "invoiceTemplate.xlsx", HttpContext.ApplicationInstance.Response, ExcelDownloadType.PromptDialog, ExcelHttpContentType.Excel2016);
                }
                else
                {
                    workbook = application.Workbooks.Open(ResolveApplicationDataPath(@"ExcelTopdfwithChart.xlsx"), ExcelOpenType.Automatic);
                    return excelEngine.SaveAsActionResult(workbook, "ExcelTopdfwithChart.xlsx", HttpContext.ApplicationInstance.Response, ExcelDownloadType.PromptDialog, ExcelHttpContentType.Excel2016);
                }
            }
            checkfontName = checkboxName;
            checkfontStream = checkboxStream;            
            if (checkboxStream != null || checkboxName!=null)
            {
                application.SubstituteFont += new Syncfusion.XlsIO.Implementation.SubstituteFontEventHandler(SubstituteFont);
                 workbook = application.Workbooks.Open(ResolveApplicationDataPath("invoiceTemplate.xlsx"));
            }
            else
            workbook = application.Workbooks.Open(ResolveApplicationDataPath("ExcelTopdfwithChart.xlsx"));

            ExcelToPdfConverter converter = new ExcelToPdfConverter(workbook);
            converter.ChartToImageConverter = new ChartToImageConverter();
            //Set the image quality
            converter.ChartToImageConverter.ScalingMode = ScalingMode.Best;
            //Intialize the PdfDocument Class
            PdfDocument pdfDoc = new PdfDocument();

            //Intialize the ExcelToPdfConverterSettings class
            ExcelToPdfConverterSettings settings = new ExcelToPdfConverterSettings();

            //Set the Layout Options for the output Pdf page.
            if (Group1 == "NoScaling")
                settings.LayoutOptions = LayoutOptions.NoScaling;
            else if (Group1 == "FitAllRowsOnOnePage")
                settings.LayoutOptions = LayoutOptions.FitAllRowsOnOnePage;
            else if (Group1 == "FitAllColumnsOnOnePage")
                settings.LayoutOptions = LayoutOptions.FitAllColumnsOnOnePage;
            else
                settings.LayoutOptions = LayoutOptions.FitSheetOnOnePage;

            //Assign the output PdfDocument to the TemplateDocument property of ExcelToPdfConverterSettings 
            settings.TemplateDocument = pdfDoc;
            settings.DisplayGridLines = GridLinesDisplayStyle.Invisible;
            //Convert the Excel document to PDf
            pdfDoc = converter.Convert(settings);
            try
            {
              //return pdfDoc.ExportAsActionResult("ExcelToPDF.pdf", HttpContext.ApplicationInstance.Response, HttpReadType.Save);
              return new Syncfusion.Mvc.Pdf.PdfResult(pdfDoc, "ExcelToPDF.pdf", HttpContext.ApplicationInstance.Response, HttpReadType.Save);
            }
            catch (Exception)
            {
            }
            finally
            {

            }
            return View();
        }
Пример #59
0
        private void Button_Click(object sender, RoutedEventArgs e)
        {
            // New instance of XlsIO is created.[Equivalent to launching MS Excel with no workbooks open].
            // The instantiation process consists of two steps.

            // Step 1 : Instantiate the spreadsheet creation engine.
            ExcelEngine excelEngine = new ExcelEngine();

            // Step 2 : Instantiate the excel application object.
            IApplication application = excelEngine.Excel;

            // An existing workbook is opened.
#if NETCORE
            IWorkbook workbook = application.Workbooks.Open(@"..\..\..\..\..\..\..\Common\Data\XlsIO\NorthwindTemplate.xls");
#else
            IWorkbook workbook = application.Workbooks.Open(@"..\..\..\..\..\..\Common\Data\XlsIO\NorthwindTemplate.xls");
#endif

            // The first worksheet object in the worksheets collection is accessed.
            IWorksheet sheet = workbook.Worksheets[0];

            string fileName = string.Empty;

            if (sheetRBtn.IsChecked.Value)
            {
                fileName = "WorksheetToHTML.html";
                sheet.SaveAsHtml(fileName);

                //// We may also explicitly set Image path and Text mode
                //HtmlSaveOptions options = new HtmlSaveOptions();
                //options.TextMode = HtmlSaveOptions.GetText.DisplayText;
                //options.ImagePath = @"..\..\Output\";

                //// Specify the HtmlSaveOptions when saving the sheet as Html
                //sheet.SaveAsHtml("Sample.html", options);
            }
            else
            {
                fileName = "WorkbookToHTML.html";
                workbook.SaveAsHtml(fileName, HtmlSaveOptions.Default);
            }

            //Close the workbook.
            workbook.Close();
            excelEngine.Dispose();

            //Message box confirmation to view the created spreadsheet.
            if (MessageBox.Show("Do you want to view the HTML?", "Conversion successful",
                                MessageBoxButton.YesNo, MessageBoxImage.Information) == MessageBoxResult.Yes)
            {
                try
                {
                    //Launching the Excel file using the default Application.[MS Excel Or Free ExcelViewer]
#if NETCORE
                    System.Diagnostics.Process process = new System.Diagnostics.Process();
                    process.StartInfo = new System.Diagnostics.ProcessStartInfo(fileName)
                    {
                        UseShellExecute = true
                    };
                    process.Start();
#else
                    Process.Start(fileName);
#endif

                    //Exit
                    this.Close();
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.ToString());
                }
            }
            else
            {
                // Exit
                this.Close();
            }
        }
Пример #60
0
        private void btnWriteFormual_Click(object sender, System.EventArgs e)
        {
            #region Workbook Initialize
            ////New instance of XlsIO is created.[Equivalent to launching MS Excel with no workbooks open].
            ////The instantiation process consists of two steps.

            //Step 1 : Instantiate the spreadsheet creation engine.
            ExcelEngine excelEngine = new ExcelEngine();
            //Step 2 : Instantiate the excel application object.
            IApplication application = excelEngine.Excel;

            //Open the workbook
            IWorkbook workbook = application.Workbooks.Create(1);

            //The first worksheet object in the worksheets collection is accessed.
            IWorksheet worksheet = workbook.Worksheets[0];
            #endregion

            string fullPath = Path.GetFullPath(DEFAULTPATH);

            //External formula from another workboook
            worksheet.Range["A1"].Formula = @"='" + fullPath + "[External_Input.xlsx]Sheet1'!$A$1";
            worksheet.Range["A2"].Formula = @"='" + fullPath + "[External_Input.xlsx]Sheet1'!$A$2";
            worksheet.Range["A3"].Formula = @"='" + fullPath + "[External_Input.xlsx]Sheet1'!$A$3";
            worksheet.Range["A4"].Formula = @"='" + fullPath + "[External_Input.xlsx]Sheet1'!$A$4";
            worksheet.Range["A5"].Formula = @"='" + fullPath + "[External_Input.xlsx]Sheet1'!$A$5";
            worksheet.Range["A6"].Formula = @"='" + fullPath + "[External_Input.xlsx]Sheet1'!$A$6";
            worksheet.Range["A7"].Formula = @"='" + fullPath + "[External_Input.xlsx]Sheet1'!$A$7";
            worksheet.Range["B1"].Formula = @"='" + fullPath + "[External_Input.xlsx]Sheet1'!$B$1";
            worksheet.Range["B2"].Formula = @"='" + fullPath + "[External_Input.xlsx]Sheet1'!$B$2";
            worksheet.Range["B3"].Formula = @"='" + fullPath + "[External_Input.xlsx]Sheet1'!$B$3";
            worksheet.Range["B4"].Formula = @"='" + fullPath + "[External_Input.xlsx]Sheet1'!$B$4";
            worksheet.Range["B5"].Formula = @"='" + fullPath + "[External_Input.xlsx]Sheet1'!$B$5";
            worksheet.Range["B6"].Formula = @"='" + fullPath + "[External_Input.xlsx]Sheet1'!$B$6";
            worksheet.Range["C1"].Formula = @"='" + fullPath + "[External_Input.xlsx]Sheet1'!$C$1";
            worksheet.Range["C2"].Formula = @"='" + fullPath + "[External_Input.xlsx]Sheet1'!$C$2";
            worksheet.Range["C3"].Formula = @"='" + fullPath + "[External_Input.xlsx]Sheet1'!$C$3";
            worksheet.Range["C4"].Formula = @"='" + fullPath + "[External_Input.xlsx]Sheet1'!$C$4";
            worksheet.Range["C5"].Formula = @"='" + fullPath + "[External_Input.xlsx]Sheet1'!$C$5";
            worksheet.Range["C6"].Formula = @"='" + fullPath + "[External_Input.xlsx]Sheet1'!$C$6";
            worksheet.Range["D1"].Formula = @"='" + fullPath + "[External_Input.xlsx]Sheet1'!$D$1";
            worksheet.Range["D2"].Formula = @"='" + fullPath + "[External_Input.xlsx]Sheet1'!$D$2";
            worksheet.Range["D3"].Formula = @"='" + fullPath + "[External_Input.xlsx]Sheet1'!$D$3";
            worksheet.Range["D4"].Formula = @"='" + fullPath + "[External_Input.xlsx]Sheet1'!$D$4";
            worksheet.Range["D5"].Formula = @"='" + fullPath + "[External_Input.xlsx]Sheet1'!$D$5";
            worksheet.Range["D6"].Formula = @"='" + fullPath + "[External_Input.xlsx]Sheet1'!$D$6";
            worksheet.Range["E1"].Formula = @"='" + fullPath + "[External_Input.xlsx]Sheet1'!$E$1";
            worksheet.Range["E2"].Formula = @"='" + fullPath + "[External_Input.xlsx]Sheet1'!$E$2";
            worksheet.Range["E3"].Formula = @"='" + fullPath + "[External_Input.xlsx]Sheet1'!$E$3";
            worksheet.Range["E4"].Formula = @"='" + fullPath + "[External_Input.xlsx]Sheet1'!$E$4";
            worksheet.Range["E5"].Formula = @"='" + fullPath + "[External_Input.xlsx]Sheet1'!$E$5";
            worksheet.Range["E6"].Formula = @"='" + fullPath + "[External_Input.xlsx]Sheet1'!$E$6";
            worksheet.Range["F1"].Formula = @"='" + fullPath + "[External_Input.xlsx]Sheet1'!$F$1";
            worksheet.Range["B7"].Formula = "=SUM(B2:B6)";
            worksheet.Range["C7"].Formula = "=SUM(C2:C6)";
            worksheet.Range["D7"].Formula = "=SUM(D2:D6)";
            worksheet.Range["E7"].Formula = "=SUM(E2:E6)";
            worksheet.Range["F7"].Formula = "=SUM(F2:F6)";
            worksheet.Range["F2"].Formula = "=B2*C2+D2-E2";
            worksheet.Range["F3"].Formula = "=B3*C3+D3-E3";
            worksheet.Range["F4"].Formula = "=B4*C4+D4-E4";
            worksheet.Range["F5"].Formula = "=B5*C5+D5-E5";
            worksheet.Range["F6"].Formula = "=B6*C6+D6-E6";
            worksheet.Range["A1:F7"].CellStyle.Font.FontName = "Verdana";
            worksheet.Range["C2:F7"].NumberFormat            = "_($* #,##0.00_)";
            worksheet.Range["A1:F1"].CellStyle.Color         = System.Drawing.Color.FromArgb(0, 0, 112, 192);
            worksheet.Range["A7:F7"].CellStyle.Color         = System.Drawing.Color.FromArgb(0, 0, 112, 192);
            worksheet.Range["A1:F1"].CellStyle.Font.Bold     = true;
            worksheet.Range["A1:F1"].CellStyle.Font.Size     = 11;
            worksheet.Columns[0].ColumnWidth = 17;
            worksheet.Columns[1].ColumnWidth = 13;
            worksheet.Columns[2].ColumnWidth = 11;
            worksheet.Columns[3].ColumnWidth = 11;
            worksheet.Columns[4].ColumnWidth = 13;
            worksheet.Columns[5].ColumnWidth = 13;

            worksheet.Calculate();
            #region Workbook Save
            //Saving the workbook to disk.
            workbook.SaveAs("ExternalFormula.xlsx");
            #endregion

            #region Workbook Close and Dispose
            //Close the workbook.
            workbook.Close();

            //No exception will be thrown if there are unsaved workbooks.
            excelEngine.ThrowNotSavedOnDestroy = false;
            excelEngine.Dispose();
            #endregion

            #region View the Workbook
            //Message box confirmation to view the created spreadsheet.
            if (MessageBox.Show("Do you want to view the workbook?", "Workbook has been created",
                                MessageBoxButtons.YesNo, MessageBoxIcon.Information)
                == DialogResult.Yes)
            {
                //Launching the Excel file using the default Application.[MS Excel Or Free ExcelViewer]
#if NETCORE
                System.Diagnostics.Process process = new System.Diagnostics.Process();
                process.StartInfo = new System.Diagnostics.ProcessStartInfo("ExternalFormula.xlsx")
                {
                    UseShellExecute = true
                };
                process.Start();
#else
                Process.Start("ExternalFormula.xlsx");
#endif
            }
            #endregion
        }