コード例 #1
0
ファイル: data.cs プロジェクト: AIBrain/gold_mine
 // current version of the application data
 private static void LoadDefaults() {
     DATA = new AppData {
         TotalWins = 0,
         BestTime = 0,
         Version = DataVersion
     };
 }
コード例 #2
0
        public static RenderDurationFiFo GetAllEntries()
        {
            var result = new AppData()[_AppDataKey];

            if(result == null)
                return new RenderDurationFiFo(_renderListSize);

            return (RenderDurationFiFo)result;
        }
コード例 #3
0
 public FrmAddCustomer(AppData.CustomerProfile cpx) : this()
 {
     cp = cpx;
     txtCustomerID.Text = cp.CustomerId.ToString();
     txtName.Text = cp.CpName;
     txtDileveryAddress.Text = cp.CpDeliveryAddress;
     txtBillAddress.Text = cp.CpBillAddress;
     txtMobile.Text = cp.CpMobileNumber;
     txtEmail.Text = cp.CpEmail;
 }
コード例 #4
0
 public MainWindow()
 {
     InitializeComponent();
     appData = new AppData();
     string fullPath = Environment.CurrentDirectory + "\\" + appDataFileName;
     if(File.Exists(fullPath))
         appData.ReadXml(fullPath);
     CountryBox.Text = LastUsedCountry;
     WorkInProgress = 0;
     Browser.LoadCompleted += LoadTorList;
 }
コード例 #5
0
 public FrmAddSchedule(AppData.MenuSchedule msx) : this()
 {
     ms = msx;
     
     dateTimePicker1.Value = Convert.ToDateTime(ms.MsDate);
     txtMenuA.Text = AppData.Menu.Find(ms.MsMenuA).MName;
     txtMenuB.Text = AppData.Menu.Find(ms.MsMenuB).MName;
     txtMenuC.Text = AppData.Menu.Find(ms.MsMenuC).MName;
     txtScheduleID.Text = ms.MenuScheduleId.ToString();
     
     
 }
コード例 #6
0
ファイル: FrmAddMenu.cs プロジェクト: adhittia/skripsi-2009
 public FrmAddMenu(AppData.Menu mnx) : this()
 {
     //InitializeComponent();
     btnSave.Text = "Update";
     mn = mnx;
     txtMenuID.Text = mn.MenuId.ToString();
     txtMenuName.Text = mn.MName;
     txtDescription.Text = mn.MDescription;
     txtPrice.Text = mn.MPrice.ToString();
     cmbType.Text = mn.MType;
     cmbType.Text = mn.MCategory;
 }
コード例 #7
0
        private void appDataChanged(AppData ad)
        {
            if (lastgrablabel.InvokeRequired || nextgrablabel.InvokeRequired)
            {
                // on a different thread.. callback to self
                log.debug("invoke...");
                AppDataChangedHandler d = new AppDataChangedHandler(appDataChanged);
                this.Invoke(d, new object[] { ad });
            }
            else
            {
                log.debug("setting grab labels...");
                if (ad.lastgrab == DateTime.MinValue)
                    lastgrablabel.Text = "Last grab: N/A";
                else
                    lastgrablabel.Text = "Last grab: " + ad.lastgrab.ToString();

                if (ad.nextgrab == DateTime.MinValue)
                    nextgrablabel.Text = "Next scheduled grab: N/A";
                else
                    nextgrablabel.Text = "Next scheduled grab: " + ad.nextgrab.ToString();
            }
        }
コード例 #8
0
ファイル: data.cs プロジェクト: AIBrain/gold_mine
        public static void Load() {
            try {
                if ( File.Exists( DataPATH ) ) {

                    using ( var file = new StreamReader( DataPATH ) ) {

                        var jsonData = file.ReadToEnd();
                        file.Close();

                        DATA = JsonConvert.DeserializeObject<AppData>( jsonData );

                        if ( DATA.Version != DataVersion ) {
                            Update();
                        }
                    }

                    return;
                }
            }
            catch ( Exception exception ) {
                Debug.WriteLine( exception.Message );
            }
            LoadDefaults();
        }
コード例 #9
0
        private async Task <ViewCrowdfundViewModel> GetInfo(AppData appData, string statusMessage = null)
        {
            var      settings      = appData.GetSettings <CrowdfundSettings>();
            var      resetEvery    = settings.StartDate.HasValue ? settings.ResetEvery : CrowdfundResetEvery.Never;
            DateTime?lastResetDate = null;
            DateTime?nextResetDate = null;

            if (resetEvery != CrowdfundResetEvery.Never)
            {
                lastResetDate = settings.StartDate.Value;

                nextResetDate = lastResetDate.Value;
                while (DateTime.Now >= nextResetDate)
                {
                    lastResetDate = nextResetDate;
                    switch (resetEvery)
                    {
                    case CrowdfundResetEvery.Hour:
                        nextResetDate = lastResetDate.Value.AddHours(settings.ResetEveryAmount);
                        break;

                    case CrowdfundResetEvery.Day:
                        nextResetDate = lastResetDate.Value.AddDays(settings.ResetEveryAmount);
                        break;

                    case CrowdfundResetEvery.Month:

                        nextResetDate = lastResetDate.Value.AddMonths(settings.ResetEveryAmount);
                        break;

                    case CrowdfundResetEvery.Year:
                        nextResetDate = lastResetDate.Value.AddYears(settings.ResetEveryAmount);
                        break;
                    }
                }
            }

            var invoices = await GetInvoicesForApp(appData, lastResetDate);

            var completeInvoices = invoices.Where(entity => entity.Status == InvoiceStatusLegacy.Complete || entity.Status == InvoiceStatusLegacy.Confirmed).ToArray();
            var pendingInvoices  = invoices.Where(entity => !(entity.Status == InvoiceStatusLegacy.Complete || entity.Status == InvoiceStatusLegacy.Confirmed)).ToArray();
            var paidInvoices     = invoices.Where(entity => entity.Status == InvoiceStatusLegacy.Complete || entity.Status == InvoiceStatusLegacy.Confirmed || entity.Status == InvoiceStatusLegacy.Paid).ToArray();

            var pendingPayments = GetContributionsByPaymentMethodId(settings.TargetCurrency, pendingInvoices, !settings.EnforceTargetAmount);
            var currentPayments = GetContributionsByPaymentMethodId(settings.TargetCurrency, completeInvoices, !settings.EnforceTargetAmount);

            var perkCount = paidInvoices
                            .Where(entity => !string.IsNullOrEmpty(entity.Metadata.ItemCode))
                            .GroupBy(entity => entity.Metadata.ItemCode)
                            .ToDictionary(entities => entities.Key, entities => entities.Count());

            var perks = Parse(settings.PerksTemplate, settings.TargetCurrency);

            if (settings.SortPerksByPopularity)
            {
                var ordered       = perkCount.OrderByDescending(pair => pair.Value);
                var newPerksOrder = ordered
                                    .Select(keyValuePair => perks.SingleOrDefault(item => item.Id == keyValuePair.Key))
                                    .Where(matchingPerk => matchingPerk != null)
                                    .ToList();
                var remainingPerks = perks.Where(item => !newPerksOrder.Contains(item));
                newPerksOrder.AddRange(remainingPerks);
                perks = newPerksOrder.ToArray();
            }
            return(new ViewCrowdfundViewModel()
            {
                Title = settings.Title,
                Tagline = settings.Tagline,
                Description = settings.Description,
                CustomCSSLink = settings.CustomCSSLink,
                MainImageUrl = settings.MainImageUrl,
                EmbeddedCSS = settings.EmbeddedCSS,
                StoreId = appData.StoreDataId,
                AppId = appData.Id,
                StartDate = settings.StartDate?.ToUniversalTime(),
                EndDate = settings.EndDate?.ToUniversalTime(),
                TargetAmount = settings.TargetAmount,
                TargetCurrency = settings.TargetCurrency,
                EnforceTargetAmount = settings.EnforceTargetAmount,
                Perks = perks,
                Enabled = settings.Enabled,
                DisqusEnabled = settings.DisqusEnabled,
                SoundsEnabled = settings.SoundsEnabled,
                DisqusShortname = settings.DisqusShortname,
                AnimationsEnabled = settings.AnimationsEnabled,
                ResetEveryAmount = settings.ResetEveryAmount,
                ResetEvery = Enum.GetName(typeof(CrowdfundResetEvery), settings.ResetEvery),
                DisplayPerksRanking = settings.DisplayPerksRanking,
                PerkCount = perkCount,
                NeverReset = settings.ResetEvery == CrowdfundResetEvery.Never,
                Sounds = settings.Sounds,
                AnimationColors = settings.AnimationColors,
                CurrencyData = _Currencies.GetCurrencyData(settings.TargetCurrency, true),
                CurrencyDataPayments = currentPayments.Select(pair => pair.Key)
                                       .Concat(pendingPayments.Select(pair => pair.Key))
                                       .Select(id => _Currencies.GetCurrencyData(id.CryptoCode, true))
                                       .DistinctBy(data => data.Code)
                                       .ToDictionary(data => data.Code, data => data),
                Info = new ViewCrowdfundViewModel.CrowdfundInfo()
                {
                    TotalContributors = paidInvoices.Length,
                    ProgressPercentage = (currentPayments.TotalCurrency / settings.TargetAmount) * 100,
                    PendingProgressPercentage = (pendingPayments.TotalCurrency / settings.TargetAmount) * 100,
                    LastUpdated = DateTime.Now,
                    PaymentStats = currentPayments.ToDictionary(c => c.Key.ToString(), c => c.Value.Value),
                    PendingPaymentStats = pendingPayments.ToDictionary(c => c.Key.ToString(), c => c.Value.Value),
                    LastResetDate = lastResetDate,
                    NextResetDate = nextResetDate,
                    CurrentPendingAmount = pendingPayments.TotalCurrency,
                    CurrentAmount = currentPayments.TotalCurrency
                }
            });
        }
コード例 #10
0
ファイル: SchemeApp.cs プロジェクト: lzbgt/scada-1
        /// <summary>
        /// Инициализировать данные уровня приложения
        /// </summary>
        public static SchemeApp InitSchemeApp(WorkModes workMode)
        {
            SchemeApp schemeApp;

            if (schemeAppObj == null)
            {
                schemeApp          = new SchemeApp();
                schemeAppObj       = schemeApp;
                schemeApp.WorkMode = workMode;

                if (workMode == WorkModes.Monitor)
                {
                    // инициализация общих данных приложения SCADA-Web
                    AppData.InitAppData();
                    schemeApp.MainData = AppData.MainData;

                    // настройка журнала приложения
                    schemeApp.Log.FileName = AppData.LogDir + "ScadaScheme.log";
                    schemeApp.Log.Encoding = Encoding.UTF8;
                    schemeApp.Log.WriteBreak();
                    schemeApp.Log.WriteAction(Localization.UseRussian ? "Запуск SCADA-Схемы" :
                                              "Start SCADA-Scheme", Log.ActTypes.Action);
                }
                else // WorkModes.Edit
                {
                    // инициализация данных редактора схем
                    schemeApp.EditorData = new EditorData();

                    // настройка журнала приложения
                    schemeApp.Log.FileName = ScadaUtils.NormalDir(Path.GetDirectoryName(Application.ExecutablePath)) +
                                             "log\\ScadaSchemeEditor.log";
                    schemeApp.Log.Encoding = Encoding.UTF8;
                    schemeApp.Log.WriteBreak();
                    schemeApp.Log.WriteAction(Localization.UseRussian ? "Запуск SCADA-Редактора схем" :
                                              "Start SCADA-Scheme Editor", Log.ActTypes.Action);
                }
            }
            else if (schemeAppObj.WorkMode != workMode)
            {
                throw new ArgumentException(Localization.UseRussian ?
                                            "Ошибка при инициализации данных приложения SCADA-Схема: некорректный режим работы." :
                                            "Error initializing SCADA-Scheme application data: incorrect work mode.", "workMode");
            }
            else
            {
                schemeApp = schemeAppObj;
            }

            if (workMode == WorkModes.Monitor)
            {
                // получение настроек Silverlight-приложения из настроек SCADA-Web
                schemeApp.SchemeSettings.RefrFreq   = AppData.WebSettings.SrezRefrFreq;
                schemeApp.SchemeSettings.CmdEnabled = AppData.WebSettings.CmdEnabled;
            }

            // инициализировать используемые фразы
            schemeApp.SchemeSettings.SchemePhrases.Init();
            SchemePhrases.InitStatic();

            return(schemeApp);
        }
コード例 #11
0
        protected override async void OnNavigatedTo(NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);

            displayRequest = new DisplayRequest();
            displayRequest.RequestActive();

            var message = Newtonsoft.Json.JsonConvert.DeserializeObject <BackupProgressMessage>(e.Parameter.ToString());

            if (message.IsRestore)
            {
                HeaderText.Visibility      = Visibility.Collapsed;
                HeaderText2.Visibility     = Visibility.Visible;
                WarningMessage.Visibility  = Visibility.Collapsed;
                WarningMessage2.Visibility = Visibility.Visible;

                List <CompactAppData> skipApps = new List <CompactAppData>();

                try
                {
                    backup = message.backup;

                    ((App)App.Current).BackRequested += BackupProgress_BackRequested;
                    backupManager.BackupProgress     += BackupManager_BackupProgress;

                    LogsView.ItemsSource = log;

                    string notAvailableNames = "";
                    foreach (var item in backup.Apps)
                    {
                        if (LoadAppData.appsData.Count(x => x.FamilyName == item.FamilyName) == 0)
                        {
                            skipApps.Add(item);
                            if (notAvailableNames.Length > 0)
                            {
                                notAvailableNames += "\r\n";
                            }
                            notAvailableNames += item.DisplayName;
                        }
                    }
                }
                catch (Exception ex)
                {
                    MessageDialog md = new MessageDialog("1" + ex.Message);
                    await md.ShowAsync();
                }

                try
                {
                    foreach (var item in backup.Apps)
                    {
                        if (!skipApps.Contains(item))
                        {
                            AppData appd = AppDataExtension.FindAppData(item.FamilyName);
                            if (appd.PackageId != item.PackageId)
                            {
                                MessageDialog md = new MessageDialog("Current installed version doesn't match the version backup was created from.\r\n\r\n" +
                                                                     "Current installed version: " + appd.PackageId + "\r\n\r\n" +
                                                                     "Backup: " + item.PackageId + "\r\n\r\n\r\n" +
                                                                     "Do you want to restore this app?",
                                                                     appd.DisplayName + ": Version mismatch");
                                md.Commands.Add(new UICommand("Restore")
                                {
                                    Id = 1
                                });
                                md.Commands.Add(new UICommand("Don't restore")
                                {
                                    Id = 0
                                });
                                md.DefaultCommandIndex = 1;
                                md.CancelCommandIndex  = 0;

                                var result = await md.ShowAsync();

                                if (((int)result.Id) == 0)
                                {
                                    skipApps.Add(item);
                                }
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    MessageDialog md = new MessageDialog("2" + ex.Message);
                    await md.ShowAsync();
                }

                try
                {
                    cleanedCount   = -1;
                    totalAppsCount = backup.Apps.Count;
                }
                catch (Exception ex)
                {
                    MessageDialog md = new MessageDialog("3" + ex.Message);
                    await md.ShowAsync();
                }

                try
                {
                    await backupManager.Restore(backup, skipApps);

                    progressBar1.Value         = 100.0;
                    messageTextBlock.Text      = "Restore completed.";
                    HeaderText2.Text           = "DONE";
                    WarningMessage2.Visibility = Visibility.Collapsed;
                    FinalMessage.Visibility    = Visibility.Visible;
                    progressRing.IsActive      = false;
                    progressRing.Visibility    = Visibility.Collapsed;
                }
                catch
                {
                    MessageDialog md = new MessageDialog(" The system cannot find the backup " + backup.Name);
                    md.Commands.Add(new UICommand("OK")
                    {
                        Id = 1
                    });
                    //md.Commands.Add(new UICommand("No") { Id = 0 });
                    md.DefaultCommandIndex = 1;
                    //md.CancelCommandIndex = 0;

                    var result = await md.ShowAsync();

                    progressBar1.Value         = 100.0;
                    messageTextBlock.Text      = "Restore cancelled!";
                    HeaderText2.Text           = "ERROR";
                    WarningMessage2.Visibility = Visibility.Collapsed;
                    FinalMessage.Visibility    = Visibility.Visible;
                    progressRing.IsActive      = false;
                    progressRing.Visibility    = Visibility.Collapsed;
                }
            }
            else
            {
                backup = message.backup;

                ((App)App.Current).BackRequested += BackupProgress_BackRequested;
                backupManager.BackupProgress     += BackupManager_BackupProgress;

                LogsView.ItemsSource = log;

                List <AppData> appDatas = (from CompactAppData c in backup.Apps
                                           select AppDataExtension.FindAppData(c.FamilyName)).ToList();

                await backupManager.CreateBackup(appDatas, backup.Name);

                progressBar1.Value        = 100.0;
                messageTextBlock.Text     = "Backup completed.";
                HeaderText.Text           = "DONE";
                WarningMessage.Visibility = Visibility.Collapsed;
                FinalMessage.Visibility   = Visibility.Visible;
                progressRing.IsActive     = false;
                progressRing.Visibility   = Visibility.Collapsed;
            }

            ((App)App.Current).BackRequested -= BackupProgress_BackRequested;
            displayRequest.RequestRelease();
        }
コード例 #12
0
            public static global::System.Xml.Schema.XmlSchemaComplexType GetTypedTableSchema(global::System.Xml.Schema.XmlSchemaSet xs)
            {
                global::System.Xml.Schema.XmlSchemaComplexType type     = new global::System.Xml.Schema.XmlSchemaComplexType();
                global::System.Xml.Schema.XmlSchemaSequence    sequence = new global::System.Xml.Schema.XmlSchemaSequence();
                AppData ds = new AppData();

                global::System.Xml.Schema.XmlSchemaAny any1 = new global::System.Xml.Schema.XmlSchemaAny();
                any1.Namespace       = "http://www.w3.org/2001/XMLSchema";
                any1.MinOccurs       = new decimal(0);
                any1.MaxOccurs       = decimal.MaxValue;
                any1.ProcessContents = global::System.Xml.Schema.XmlSchemaContentProcessing.Lax;
                sequence.Items.Add(any1);
                global::System.Xml.Schema.XmlSchemaAny any2 = new global::System.Xml.Schema.XmlSchemaAny();
                any2.Namespace       = "urn:schemas-microsoft-com:xml-diffgram-v1";
                any2.MinOccurs       = new decimal(1);
                any2.ProcessContents = global::System.Xml.Schema.XmlSchemaContentProcessing.Lax;
                sequence.Items.Add(any2);
                global::System.Xml.Schema.XmlSchemaAttribute attribute1 = new global::System.Xml.Schema.XmlSchemaAttribute();
                attribute1.Name       = "namespace";
                attribute1.FixedValue = ds.Namespace;
                type.Attributes.Add(attribute1);
                global::System.Xml.Schema.XmlSchemaAttribute attribute2 = new global::System.Xml.Schema.XmlSchemaAttribute();
                attribute2.Name       = "tableTypeName";
                attribute2.FixedValue = "PhoneBookDataTable";
                type.Attributes.Add(attribute2);
                type.Particle = sequence;
                global::System.Xml.Schema.XmlSchema dsSchema = ds.GetSchemaSerializable();
                if (xs.Contains(dsSchema.TargetNamespace))
                {
                    global::System.IO.MemoryStream s1 = new global::System.IO.MemoryStream();
                    global::System.IO.MemoryStream s2 = new global::System.IO.MemoryStream();
                    try {
                        global::System.Xml.Schema.XmlSchema schema = null;
                        dsSchema.Write(s1);
                        for (global::System.Collections.IEnumerator schemas = xs.Schemas(dsSchema.TargetNamespace).GetEnumerator(); schemas.MoveNext();)
                        {
                            schema = ((global::System.Xml.Schema.XmlSchema)(schemas.Current));
                            s2.SetLength(0);
                            schema.Write(s2);
                            if ((s1.Length == s2.Length))
                            {
                                s1.Position = 0;
                                s2.Position = 0;
                                for (; ((s1.Position != s1.Length) &&
                                        (s1.ReadByte() == s2.ReadByte()));)
                                {
                                    ;
                                }
                                if ((s1.Position == s1.Length))
                                {
                                    return(type);
                                }
                            }
                        }
                    }
                    finally {
                        if ((s1 != null))
                        {
                            s1.Close();
                        }
                        if ((s2 != null))
                        {
                            s2.Close();
                        }
                    }
                }
                xs.Add(dsSchema);
                return(type);
            }
コード例 #13
0
 /// <summary>
 /// JS function handler for running showModal JS function, with input arguments.
 /// </summary>
 /// <param name="args">Argument string, containing a command to be handled later by modal</param>
 /// <returns></returns>
 public static bool ShowModal(string args)
 {
     Globals.DebugWriteLine($@"[JSInvoke:General\GeneralInvocableFuncs.ShowModal] args={args}");
     return(AppData.InvokeVoidAsync("showModal", args));
 }
コード例 #14
0
        public async Task <IActionResult> CreateApp(CreateAppViewModel vm)
        {
            var stores = await _AppsHelper.GetOwnedStores(GetUserId());

            if (stores.Length == 0)
            {
                StatusMessage = new StatusMessageModel()
                {
                    Html =
                        $"Error: You must have created at least one store. <a href='{(Url.Action("CreateStore", "UserStores"))}'>Create store</a>",
                    Severity = StatusMessageModel.StatusSeverity.Error
                }.ToString();
                return(RedirectToAction(nameof(ListApps)));
            }
            var selectedStore = vm.SelectedStore;

            vm.SetStores(stores);
            vm.SelectedStore = selectedStore;

            if (!Enum.TryParse <AppType>(vm.SelectedAppType, out AppType appType))
            {
                ModelState.AddModelError(nameof(vm.SelectedAppType), "Invalid App Type");
            }

            if (!ModelState.IsValid)
            {
                return(View(vm));
            }

            if (!stores.Any(s => s.Id == selectedStore))
            {
                StatusMessage = "Error: You are not owner of this store";
                return(RedirectToAction(nameof(ListApps)));
            }
            var id = Encoders.Base58.EncodeData(RandomUtils.GetBytes(20));

            using (var ctx = _ContextFactory.CreateContext())
            {
                var appData = new AppData()
                {
                    Id = id
                };
                appData.StoreDataId = selectedStore;
                appData.Name        = vm.Name;
                appData.AppType     = appType.ToString();
                ctx.Apps.Add(appData);
                await ctx.SaveChangesAsync();
            }
            StatusMessage = "App successfully created";
            CreatedAppId  = id;

            switch (appType)
            {
            case AppType.PointOfSale:
                return(RedirectToAction(nameof(UpdatePointOfSale), new { appId = id }));

            case AppType.Crowdfund:
                return(RedirectToAction(nameof(UpdateCrowdfund), new { appId = id }));

            default:
                return(RedirectToAction(nameof(ListApps)));
            }
        }
コード例 #15
0
 public TravelController(AppData appData)
 {
     this.appData = appData;
 }
コード例 #16
0
ファイル: JumpController.cs プロジェクト: MaximePhilipp/Blob
    // Update is called once per frame
    private void Update()
    {
        if (AppData.GetCurrentTiltType() == AppData.GroundTiltType.None)
        {
            return;
        }

#if UNITY_EDITOR
        if (Input.GetKeyDown(KeyCode.Space) && jellySprite.IsGrounded(layerMask, 1))
        {
#else
        if (jellySprite.IsGrounded(layerMask, 2) &&
            ((AppData.GetCurrentTiltType() == AppData.GroundTiltType.Touch && LeanTouch.Fingers.Count >= 2) || (AppData.GetCurrentTiltType() == AppData.GroundTiltType.Gyro && LeanTouch.Fingers.Count >= 1)))
        {
#endif

            jumpRegistered = true;
        }
    }
コード例 #17
0
 public SaleController(AppData appData, IBusinessRepository service) : base(appData, service)
 {
 }
コード例 #18
0
 public MenuService(ILogger <RestaurantMenuService> logger, AppData app)
 {
     _logger = logger;
     _app    = app;
 }
コード例 #19
0
        //-------------------------------------------------------------------------------------------------//

        public ExperimentEngine(int unitId, AppData appData)
            : base(unitId, appData)
        {
            this.configuration = (Configuration)appData.labConfiguration;
        }
コード例 #20
0
        /// <summary>
        /// 另存为
        /// </summary>
        private void SaveAs()
        {
            if (_targetModel.ResourceModel.FileState == FileStates.WaitForReceieve)
            {
                if (AppData.CanInternetAction())
                {
                    Microsoft.Win32.SaveFileDialog sfd = new Microsoft.Win32.SaveFileDialog();
                    sfd.FileName = _targetModel.ResourceModel.FileName;
                    //sfd.Filter = System.IO.Path.GetExtension(_targetModel.ResourceModel.FileName);
                    if (sfd.ShowDialog() == true)
                    {
                        try
                        {
                            File.Delete(sfd.FileName);
                        }
                        catch
                        {
                            AppData.MainMV.TipMessage = "文件已被占用,替换失败!";
                            return;
                        }
                        this.FileState = FileStates.Receiving;
                        _operateTask   = new System.Threading.CancellationTokenSource();
                        AcioningItems.Add(this);
                        ChatViewModel chatVM = AppData.MainMV.ChatListVM.SelectedItem;
                        CSClient.Helper.MessageHelper.LoadFileContent(_targetModel, _operateTask, chatVM, (result) =>
                        {
                            AcioningItems.Remove(this);
                            if (_operateTask != null)
                            {
                                _operateTask.Cancel();
                                _operateTask = null;
                            }
                        }, sfd.FileName);
                    }
                }
            }
            else
            {
                if (FileExists())
                {
                    Microsoft.Win32.SaveFileDialog dlg = new Microsoft.Win32.SaveFileDialog();
                    dlg.FileName   = System.IO.Path.GetFileName(this.FullName);    // Default file name
                    dlg.DefaultExt = System.IO.Path.GetExtension(this.FullName);   // fileName.Split('.').LastOrDefault(); // Default file extension

                    dlg.Filter = string.Format("文件 (.{0})|*.{0}", dlg.DefaultExt); // // Filter files by extension

                    dlg.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory);
                    if (dlg.ShowDialog() == true)
                    {
                        try
                        {
                            File.Copy(this.FullName, dlg.FileName, true);
                        }
                        catch
                        {
                            AppData.MainMV.TipMessage = "文件已被占用,替换失败!";
                        }
                    }
                }
            }
        }
コード例 #21
0
        protected void Page_Load(object sender, EventArgs e)
        {
            AppData  appData  = AppData.GetAppData();
            UserData userData = UserData.GetUserData();

#if DEBUG
            debugMode = true;
            userData.LoginForDebug();
#endif

            // перевод веб-страницы
            Translator.TranslatePage(Page, "Scada.Web.Plugins.Table.WFrmTable");

            // получение ид. представления из параметров запроса
            viewID = Request.QueryString.GetParamAsInt("viewID");

            // проверка прав на просмотр представления
            EntityRights rights = userData.LoggedOn ?
                                  userData.UserRights.GetUiObjRights(viewID) : EntityRights.NoRights;
            if (!rights.ViewRight)
            {
                Response.Redirect(UrlTemplates.NoView);
            }

            // загрузка представления в кеш для последующего получения данных через API
            TableView tableView = appData.ViewCache.GetView <TableView>(viewID);
            if (tableView == null)
            {
                Response.Redirect(UrlTemplates.NoView);
            }
            else
            {
                appData.AssignStamp(tableView);
            }

            // получение периода времени из cookies
            HttpCookie cookie = Request.Cookies["Table.TimeFrom"];
            int        timeFrom;
            if (cookie == null || !int.TryParse(cookie.Value, out timeFrom))
            {
                timeFrom = 0;
            }

            cookie = Request.Cookies["Table.TimeTo"];
            int timeTo;
            if (cookie == null || !int.TryParse(cookie.Value, out timeTo))
            {
                timeTo = 23;
            }

            // подготовка данных для вывода на веб-страницу
            viewTitle    = HttpUtility.JavaScriptStringEncode(tableView.Title);
            dataRefrRate = userData.WebSettings.DataRefrRate;
            arcRefrRate  = userData.WebSettings.ArcRefrRate;
            phrases      = WebUtils.DictionaryToJs("Scada.Web.Plugins.Table.WFrmTable.Js");

            DateTime nowDT = DateTime.Now;
            today = string.Format("new Date({0}, {1}, {2})", nowDT.Year, nowDT.Month - 1, nowDT.Day);

            selTimeFromHtml = GenerateTimeSelectHtml("selTimeFrom", true, timeFrom);
            selTimeToHtml   = GenerateTimeSelectHtml("selTimeTo", false, timeTo);
            bool cmdEnabled = userData.WebSettings.CmdEnabled && rights.ControlRight;
            tableViewHtml = GenerateTableViewHtml(tableView, cmdEnabled, timeFrom, timeTo);
        }
コード例 #22
0
    private void LoadFormContent()
    {
        /* we need to put all available form ID to a list because we need to use databind for the datalist*/
        lstFormID = new SortedList();
        for (int i = 0; i < formID.Length; i++)
        {
            lstFormID.Add(i, formID[i]);
        }

        string sError = "";

        //if (HideNames == "")
        HideNames = Session["HideNames"].ToString();

        dsChildInfo         = CChild.LoadSelectedChildInfo(RecID, Convert.ToInt16(RecType), ServiceDate, Session.SessionID, HideNames);
        dsReviewerEntryInfo = CForms.GetReviewerEntryData(ref sError, RecID);

        authorizedAmount = dsChildInfo.Tables[0].Rows[0]["Authorized Amount"].ToString();
        authorizedAmount = ((!string.IsNullOrEmpty(authorizedAmount)) ? Convert.ToDouble(authorizedAmount).ToString("N2") : "0.00");

        placement = (dsChildInfo.Tables[0].Rows[0]["Autho Type"].ToString() == "N") ? "0" : "1";

        /*begin - load the child info*/
        childDetail.recID               = RecID;
        childDetail.recType             = RecType;
        childDetail.serviceDate         = ServiceDate;
        childDetail.funding             = Funding;
        childDetail.placement           = placement;
        childDetail.dsChildInfo         = dsChildInfo;
        childDetail.dsReviewerEntryInfo = dsReviewerEntryInfo;
        //childDetail.eID = eID;
        pageDetailTitle.eID          = eID;
        pageDetailTitle.recID        = RecID;
        pageDetailTitle.recType      = RecType;
        pageDetailTitle.serviceDate  = ServiceDate;
        pageDetailTitle.dsChildInfo0 = dsChildInfo;
        /*end - load the child info*/

        lstForms.DataSource = lstFormID;

        DataBind();

        Page.ClientScript.RegisterStartupScript(typeof(Page), "setFirstForm", "<script language='javascript'>javascript:SetCurrentForm('100')</script>");

        /* begin - set data entry form */
        txtDataEntryTotalPaid.Text  = "$" + authorizedAmount;
        txtDataEntryMonth.Text      = ServiceDate;
        txtDataEntryReviewDate.Text = AppData.FormatDateStr(DateTime.Now.ToShortDateString());
        txtDataEntryChildID.Text    = RecID;
        txtDataEntryCounty.Text     = dsChildInfo.Tables[0].Rows[0]["county"].ToString();

        txtDataEntryTotalPaidField.Value  = authorizedAmount;
        txtDataEntryMonthField.Value      = txtDataEntryMonth.Text;
        txtDataEntryReviewDateField.Value = txtDataEntryReviewDate.Text;
        txtDataEntryChildIDField.Value    = RecID;
        txtDataEntryCountyField.Value     = txtDataEntryCounty.Text;
        /* end - set data entry form */

        strLastFormID       = dsChildInfo.Tables[0].Rows[0]["LastFormID"].ToString();
        hidLastFormID.Value = strLastFormID;

        if (Session["UserName"].ToString() == "IPFedUser")
        {
            Page.ClientScript.RegisterStartupScript(typeof(Page), "AllFormCompleted", "<script>displayAllCompleted()</script>");
            btnMarkCaseComplete.Disabled = true;
            btnReviewerForm.Disabled     = true;
        }
        else
        {
            if (Completed == "1")
            {
                Page.ClientScript.RegisterStartupScript(typeof(Page), "AllFormCompleted", "<script>displayAllCompleted()</script>");
                btnMarkCaseComplete.Visible = false;
                if (Session["IsAdminUser"] != null)
                {
                    if (Session["IsAdminUser"].ToString() == "1")
                    {
                        btnMarkCaseIncomplete.Visible = true;
                    }
                }
                lblCompleted.Visible = true;
            }
        }
    }
コード例 #23
0
        /**
         * Validate Login fields for valid entries and against database entries
         * and call the MDI MAIN Screen.
         */
        private void login()
        {
            //Create an instance of application validator
            AppValidator appValidatorObj = AppValidator.getValidatorInstance();

            //Check if Username field is empty
            if (txtUsername.Text == string.Empty)
            {
                txtFieldFocus(txtUsername);
                return;
            }

            //Get value of username and password
            String username = txtUsername.Text.Trim();

            //Validate Username for alphanumeric characters

            /*if (appValidatorObj.isValidField(username, 7))
             * {
             *  txtFieldFocus(txtUsername);
             * }
             * else
             * {
             *  lblStatus.Text = "1. Can contain digit or alphanumeric characters" + "\n" +
             *                   "2. Length at least 3 characters and maximum of 15";
             *  return;
             * }*/

            //Check if password field is empty
            if (txtPassword.Text == string.Empty)
            {
                txtFieldFocus(txtPassword);
                return;
            }

            String password = txtPassword.Text.Trim();
            //Validate Password for alphanumeric and special characters

            /*if (appValidatorObj.isValidField(password, 8))
             * {
             *  txtFieldFocus(txtPassword);
             * }
             * else
             * {
             *  lblStatus.Text = "Password :"******"1. Must contain at least one digit" + "\n" +
             *                               "2. Must contain at least one uppercase character." + "\n" +
             *                               "3. Must contain at least one special symbol" + "\n" +
             *                               "4. Length at least 8 characters and maximum of 15";
             *  return;
             * }*/

            /**
             * Establish Database Connectivity Based on type of Database Server(MS SQL SERVER if default type)
             * If MY SQL, use IConnector dbConnector = connectionObj.connectToServer("MY SQL");
             * SQL specific methods are stored in interface ISQLConnector which is child of IConnector interface.
             * Similiarly for other types of Database Servers
             * DB Connection takes the database connection string identifier from DbConnection.config file.
             * When "default" is passed, default connection identifier from config file is choosen.
             * Another instance of DBConnection is to be created to connect to different database for
             * file handling.
             */
            DBConnection connectionObj = new DBConnection(AppConstants.DEFAULT_DBCONN_IDENTIFIER);

            DesktopAppSample3.ISQLConnector dbConnector = (DesktopAppSample3.ISQLConnector)connectionObj.connectToServer(AppConstants.MS_SQL_SERVER);

            /**
             * Initialization fields of the application
             * is stored in AppData object. Validate input Username and Password
             * with the values in Database.
             */
            AppData dataObj = getLoginData(username, password, dbConnector);

            if (dataObj != null)
            {
                dataObj.setDBConnector(dbConnector);

                FrmMDIMain mainForm = new FrmMDIMain(); //Pass Data Object to Main Form for using the stored username and other fields.
                this.Hide();
                mainForm.Show();
                txtPassword.Text.Trim();
            }
            else //Invalid entries provided
            {
                lblStatus.Text = "Invalid Username/Password.";
            }
        }
コード例 #24
0
        protected void LoadLocationModals(Location location)
        {
            #region Create Modal
            // Create a Bootstrap Modal to display full location information
            HtmlGenericControl Modal = new HtmlGenericControl("div")
            {
                ID = "modal_" + location.Name
            };
            Modal.Attributes["class"] = "modal";
            HtmlGenericControl ModalDialog = new HtmlGenericControl("div");
            ModalDialog.Attributes["class"] = "modal-dialog";
            HtmlGenericControl ModalContent = new HtmlGenericControl("div");
            ModalContent.Attributes["class"] = "modal-content";
            HtmlGenericControl ModalHeader = new HtmlGenericControl("div");
            ModalHeader.Attributes["class"] = "modal-header";
            HtmlGenericControl ModalBody = new HtmlGenericControl("div");
            ModalBody.Attributes["class"] = "modal-body";
            HtmlGenericControl ModalFooter = new HtmlGenericControl("div");
            ModalFooter.Attributes["class"] = "modal-footer";

            // Create an UpdatePanel to update Favorites without refreshing page
            UpdatePanel modal_panel = new UpdatePanel()
            {
                ID = "modal_panel" + location.Name
            };
            // Add unload event to prevent exception with dynamically created UpdatePanels
            modal_panel.Unload += (sender, EventArgs) => { UpdatePanel_Unload(sender, EventArgs); };

            // Add content to the Modal
            if (location != null)
            {
                string modal_loc_Description = location.Description;

                string     title      = "<h1>" + location.Name + "</h1>";
                HtmlButton ModalClose = new HtmlButton()
                {
                    InnerText = "x",
                };
                ModalClose.Attributes["class"]        = "close";
                ModalClose.Attributes["data-dismiss"] = "modal";

                ModalHeader.Controls.Add(ModalClose);

                HtmlGenericControl LocationContent = new HtmlGenericControl("div");
                string             image           = "<img src = \"" + location.ImageLink + "\" id = \"" + "img_" + location.Name + "\" />";
                string             description     = "<p>" + modal_loc_Description + "</p><br/>";
                var content = title + image + description;
                LocationContent.InnerHtml = content;
                ModalBody.Controls.Add(LocationContent);



                ///////////////////////////////// Start: Comment Section /////////////////////////////////////
                HtmlGenericControl Comments = new HtmlGenericControl("div");

                //             ///////////////////// Start: Previous Comments ////////////////////////////
                UpdatePanel panel_Comments = new UpdatePanel()
                {
                    ID = "comments_panel_" + location.Name,
                };

                panel_Comments.Unload += (sender, EventArgs) => { UpdatePanel_Unload(sender, EventArgs); };

                HtmlGenericControl PreviousComments = new HtmlGenericControl("div");
                PreviousComments.Attributes["class"] = "list-group";

                LocationController lc = new LocationController();
                List <Comment>     CommentsForLocation = null;
                try
                {
                    CommentsForLocation = lc.GetCommentsByLocationID(location.ID);
                }
                catch (Exception ex)
                {
                    logger.Error(ex.Message);
                    var msg = AppData.CreateAlert("Could not load the comments for this location: " + location.Name, "warning");
                    err_Placeholder.Controls.Add(msg);
                }
                finally
                {
                    lc.Dispose();
                }

                if (CommentsForLocation.Count != 0)
                {
                    HtmlGenericControl CommentsHeader = new HtmlGenericControl("h3")
                    {
                        InnerText = "Comments",
                    };
                    //CommentsHeader.Attributes["class"] = "container container-fluid";
                    PreviousComments.Controls.Add(CommentsHeader);
                    foreach (Comment c in CommentsForLocation)
                    {
                        string   dateString = c.CommentDate;
                        string   format     = "yyyyMMddHHmmss";
                        DateTime dateTime   = DateTime.ParseExact(dateString, format, CultureInfo.CurrentCulture);
                        string   date       = dateTime.ToString("MMMM dd, yyyy");
                        string   month      = dateTime.Month.ToString();
                        string   day        = dateTime.Day.ToString();
                        string   year       = dateTime.Year.ToString();

                        var name          = "<p><strong>" + c.UserName + "</strong> " + "<small class='text-muted float-right' font-weight='regular'>(" + date + ")</small>" + "</p>";
                        var comment       = "<p>" + c.UserComment + "</p>";
                        var singleComment = name + comment;
                        HtmlGenericControl EachComment = new HtmlGenericControl("div")
                        {
                            InnerHtml = singleComment,
                        };
                        EachComment.Attributes["class"] = "list-group-item";
                        PreviousComments.Controls.Add(EachComment);
                    }
                }
                else
                {
                    var none = "<p><strong>There are no comments yet.</strong></p>";
                    HtmlGenericControl NoComments = new HtmlGenericControl("div")
                    {
                        InnerHtml = none,
                    };
                    PreviousComments.Controls.Add(NoComments);
                }

                // Add "previous" comments to update panel
                panel_Comments.ContentTemplateContainer.Controls.Add(PreviousComments);
                //            ///////////////////// End: Previous Comments ////////////////////////////

                //            //////////////////// Start: New User Comments ///////////////////////////
                HtmlGenericControl NewComment = new HtmlGenericControl("div");
                NewComment.Attributes["class"] = "form-group";

                HtmlGenericControl NewCommentHeader = new HtmlGenericControl("h4")
                {
                    InnerText = "Add Comment",
                };


                HtmlTextArea UserComment = new HtmlTextArea()
                {
                    ID   = "Comment_" + location.Name,
                    Rows = 3,
                };
                UserComment.Attributes["name"]        = "Comment";
                UserComment.Attributes["maxlength"]   = "200";
                UserComment.Attributes["class"]       = "form-control";
                UserComment.Attributes["placeholder"] = "Say something nice...";

                NewComment.Controls.Add(NewCommentHeader);
                NewComment.Controls.Add(UserComment);

                HtmlGenericControl CharsRemaining = new HtmlGenericControl("h6")
                {
                    ID = "CharsLeft_" + location.Name,
                };
                CharsRemaining.Attributes["class"] = "text-muted float-right";
                NewComment.Controls.Add(CharsRemaining);

                //Update panel for comment submit button
                UpdatePanel panel_Comment_Buttons = new UpdatePanel
                {
                    ID = "comment_buttons_panel_" + location.Name,
                    ChildrenAsTriggers = true,
                };
                panel_Comment_Buttons.Unload += (sender, EventArgs) => { UpdatePanel_Unload(sender, EventArgs); };
                Button modal_addComment = new Button
                {
                    ID   = "modal_comment_btn" + location.Name,
                    Text = "Add Comment",
                };
                modal_addComment.Attributes["type"]  = "button";
                modal_addComment.Attributes["class"] = "btn btn-primary";

                string commentId = DateTime.Now.ToString("yyyyMMddHHmmss");
                modal_addComment.Click += (sender, EventArgs) => { AddCommentBtn_Click(sender, EventArgs, location, new Comment(location.ID, commentId, (string)Session[AppData.USERNAME], UserComment.InnerText)); };

                panel_Comment_Buttons.ContentTemplateContainer.Controls.Add(modal_addComment);

                //            ///////////////////// End: New User Comments ////////////////////////////
                Comments.Controls.Add(panel_Comments);
                if (Session[AppData.LOGGEDIN] != null)
                {
                    bool loggedIn = (bool)Session[AppData.LOGGEDIN];

                    if (loggedIn == true)
                    {
                        Comments.Controls.Add(NewComment);
                        Comments.Controls.Add(panel_Comment_Buttons);
                    }
                    else
                    {
                        string loginLink = "<a href='./login.aspx'>log in</a>";
                        var    msg       = AppData.CreateAlert("Please " + loginLink + " to leave a comment", "warning");
                        Comments.Controls.Add(msg);
                    }
                }
                else
                {
                    string loginLink = "<a href='./login.aspx'>log in</a>";
                    var    msg       = AppData.CreateAlert("Please " + loginLink + " to leave a comment", "warning");
                    Comments.Controls.Add(msg);
                }

                ModalBody.Controls.Add(Comments);
                ///////////////////////////////// End: Comment Section /////////////////////////////////////

                if (Session[AppData.LOGGEDIN] != null)
                {
                    bool loggedIn = (bool)Session[AppData.LOGGEDIN];

                    if (loggedIn == true)
                    {
                        // Check if location already exists in favorites
                        List <Favorite> TravellerFavorites = GetFavoriteList();
                        bool            contains           = TravellerFavorites.Any(f => f.LocationID == location.ID);
                        if (contains != true)
                        {
                            // Instantiate a new 'Add to Favorites' button
                            HtmlButton modal_addFavorite = new HtmlButton
                            {
                                ID        = "modal_btn_" + location.Name,
                                InnerText = "Add to My Destinations",
                            };
                            modal_addFavorite.Attributes.Add("class", "btn btn-outline-success");
                            // Specify click event and create/call new event handler
                            modal_addFavorite.ServerClick += (sender, EventArgs) => { AddDestinationBtn_Click(sender, EventArgs, location); };

                            // Add button to UpdatePanel
                            modal_panel.ContentTemplateContainer.Controls.Add(modal_addFavorite);
                        }
                        else
                        {
                            Label modal_fv_exists = new Label
                            {
                                ID       = "modal_fv_exists_" + location.Name,
                                Text     = "Saved in your destinations",
                                CssClass = "badge badge-success",
                            };
                            modal_fv_exists.Style.Add("font-size", "12pt");
                            modal_fv_exists.Style.Add("padding", "5pt");

                            modal_panel.ContentTemplateContainer.Controls.Add(modal_fv_exists);
                        }
                    }
                }

                // Add buttons to footer
                ModalFooter.Controls.Add(modal_panel);

                // Construct Modal
                ModalContent.Controls.Add(ModalHeader);
                ModalContent.Controls.Add(ModalBody);
                ModalContent.Controls.Add(ModalFooter);
                ModalDialog.Controls.Add(ModalContent);
                Modal.Controls.Add(ModalDialog);

                // Add modal to placeholder
                loc_Placeholder.Controls.Add(Modal);
            }
            #endregion Create Modal
        }
コード例 #25
0
 public override void Use()
 {
     AppData.Instance().refreshForms();
 }
コード例 #26
0
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
            }

            if (Session[AppData.LOGGEDIN] != null)
            {
                bool loggedIn = (bool)Session[AppData.LOGGEDIN];
                if (loggedIn == true)
                {
                    HtmlGenericControl welcome = new HtmlGenericControl("div")
                    {
                        InnerHtml = "<h4>" + (string)Session[AppData.FIRSTNAME] + ", welcome back to TravelBuddy</h4>" +
                                    "<p class='form-text'>Pick up where you left off...</p><br />"
                    };
                    msgPlaceholder.Controls.Add(welcome);
                }
                else
                {
                    HtmlGenericControl welcome = new HtmlGenericControl("div")
                    {
                        InnerHtml = "<h4>Welcome to TravelBuddy</h4>" +
                                    "<p class='form-text'><a href='./login.aspx'>Log in</a> or <a href='./register.aspx'>create an account</a> " +
                                    "to begin saving destinations and planning your trips.</p><br />"
                    };
                    msgPlaceholder.Controls.Add(welcome);
                }
            }
            else
            {
                HtmlGenericControl welcome = new HtmlGenericControl("div")
                {
                    InnerHtml = "<h4>Welcome to TravelBuddy</h4>" +
                                "<p class='form-text'><a href='./login.aspx'>Log in</a> or <a href='./register.aspx'>create an account</a> " +
                                "to begin saving destinations and planning your trips.</p><br />"
                };
                msgPlaceholder.Controls.Add(welcome);
            }

            LocationController locationController = new LocationController();

            try
            {
                Locations = locationController.GetLocations();
                loc_Placeholder.Controls.Clear();
                foreach (Location loc in Locations)
                {
                    PopulateLocations(loc);
                }
            }
            catch (Exception ex)
            {
                logger.Error(ex.Message);
                var msg = AppData.CreateAlert("One of the locations could not be loaded", "warning");
                err_Placeholder.Controls.Add(msg);
            }
            finally
            {
                locationController.Dispose();
            }
        }
コード例 #27
0
ファイル: FrmBaseTable.cs プロジェクト: zuoyangithub/scada
        /// <summary>
        /// Initializes a new instance of the class.
        /// </summary>
        public FrmBaseTable(IBaseTable baseTable, TableFilter tableFilter, ScadaProject project, AppData appData)
            : this()
        {
            this.baseTable   = baseTable ?? throw new ArgumentNullException("baseTable");
            this.tableFilter = tableFilter;
            this.project     = project ?? throw new ArgumentNullException("project");
            this.appData     = appData ?? throw new ArgumentNullException("appData");

            dataTable = null;
            maxRowID  = 0;
            frmFind   = null;
            frmFilter = null;

            Text = baseTable.Title + (tableFilter == null ? "" : " - " + tableFilter);
        }
コード例 #28
0
 private void Awake()
 {
     _controller = FindObjectOfType <UIController>();
     _dashboard  = FindObjectOfType <DashboardController>();
     _attributes = AppData.Instance().MannyAttribute;
 }
コード例 #29
0
 /// <summary>
 /// JS function handler for showing Toast message.
 /// </summary>
 /// <param name="toastType">success, info, warning, error</param>
 /// <param name="toastMessage">Message to be shown in toast</param>
 /// <param name="toastTitle">(Optional) Title to be shown in toast (Empty doesn't show any title)</param>
 /// <param name="renderTo">(Optional) Part of the document to append the toast to (Empty = Default, document.body)</param>
 /// <param name="duration">(Optional) Duration to show the toast before fading</param>
 /// <returns></returns>
 public static bool ShowToast(string toastType, string toastMessage, string toastTitle = "", string renderTo = "body", int duration = 5000)
 {
     Globals.DebugWriteLine($@"[JSInvoke:General\GeneralInvocableFuncs.ShowToast] type={toastType}, message={toastMessage}, title={toastTitle}, renderTo={renderTo}, duration={duration}");
     return(AppData.InvokeVoidAsync("window.notification.new", new { type = toastType, title = toastTitle, message = toastMessage, renderTo, duration }));
 }
コード例 #30
0
ファイル: Util.cs プロジェクト: udnboss/database-manager
 public static bool SaveData(AppData file, object data)
 {
     return(SaveFile(file.ToString(), JsonConvert.SerializeObject(data, Formatting.Indented)));
 }
コード例 #31
0
 public HostModel(AppData appData)
 {
     this.appData = appData;
 }
コード例 #32
0
ファイル: Database.cs プロジェクト: jivkopetiov/gmail2
 private static void SaveDataToDisk(AppData data)
 {
     string json = new JavaScriptSerializer().Serialize(data);
     File.WriteAllText(GetPath(), json);
 }
コード例 #33
0
 /// <summary>
 /// Initializes a new instance of the class.
 /// </summary>
 public FrmProfileEdit(AppData appData, DeploymentProfile deploymentProfile)
     : this()
 {
     this.appData           = appData ?? throw new ArgumentNullException(nameof(appData));
     this.deploymentProfile = deploymentProfile ?? throw new ArgumentNullException(nameof(deploymentProfile));
 }
コード例 #34
0
ファイル: FrmBaseTable.cs プロジェクト: ytchhh/scada
 /// <summary>
 /// Initializes a new instance of the class.
 /// </summary>
 protected FrmBaseTable(AppData appData)
     : this()
 {
     this.appData = appData ?? throw new ArgumentNullException("appData");
 }
コード例 #35
0
 public Task <StoreData> GetStore(AppData app)
 {
     return(_storeRepository.FindStore(app.StoreDataId));
 }
コード例 #36
0
 public CardLoadService(ArkhamDbService arkhamDbService, LocalCardsService localCardsService, CardImageService cardImageService, AppData appData, LoadingStatusService loadingStatusService, LoggingService loggingService)
 {
     _arkhamDbService      = arkhamDbService;
     _localCardsService    = localCardsService;
     _cardImageService     = cardImageService;
     _appData              = appData;
     _loadingStatusService = loadingStatusService;
     _logger = loggingService;
 }
コード例 #37
0
ファイル: Database.cs プロジェクト: jivkopetiov/gmail2
        public static void GenerateRandomData(string personName)
        {
            var random = new RandomGenerator();

            string rootPath = HttpContext.Current.Server.MapPath("~/Server");

            var attachmentFiles = System.IO.Directory.GetFiles(Path.Combine(rootPath, "attachments"));
            var lipsumParagraphs = System.IO.File.ReadAllLines(Path.Combine(rootPath, "LipsumParagraphs.txt")).Where(l => !string.IsNullOrEmpty(l)).ToList();
            var lipsumTitles = System.IO.File.ReadAllLines(Path.Combine(rootPath, "LipsumTitles.txt")).Where(l => !string.IsNullOrEmpty(l)).ToList();
            var people = new List<AppUser>();

            for (int i = 0; i < 100; i++)
            {
                var person = new AppUser();
                person.Name = random.GetRandom(personNames);
                person.Email = person.Name.ToLowerInvariant() + "@gmail.com";
                person.Id = random.GetRandomNumber(1000000, 9999999);
                people.Add(person);
            }

            var currentUser = people.First(p => p.Name == personName);

            var posts = new List<Post>();
            for (int i = 0; i < random.GetRandomNumber(800, 1200); i++)
            {
                var post = new Post();

                post.Id = random.GetRandomNumber(100000, 999999);
                post.IsFavorite = random.GetRandomDouble() < 0.2;
                post.IsRead = random.GetRandomDouble() < 0.6;
                post.Body = random.GetRandom(lipsumParagraphs);
                post.Subject = random.GetRandom(lipsumTitles);
                post.Sender = random.GetRandom(people);
                post.DateSent = random.GetRandomDate();

                for (int j = 0; j < random.GetRandomNumber(1, 10); j++)
                    post.Recepients.Add(random.GetRandom(people));

                if (random.GetRandomBool())
                {
                    for (int j = 0; j < random.GetRandomNumber(0, 5); j++)
                        post.CC.Add(random.GetRandom(people));
                }

                if (random.GetRandomBool())
                {
                    for (int j = 0; j < random.GetRandomNumber(0, 5); j++)
                        post.BCC.Add(random.GetRandom(people));
                }

                if (random.GetRandomBool())
                {
                    for (int j = 0; j < random.GetRandomNumber(0, 3); j++)
                    {
                        var attachmentFile = new FileInfo(random.GetRandom(attachmentFiles));

                        post.Attachments.Add(new Attachment { Id = Guid.NewGuid().ToString(), Size = random.GetRandomNumber(10000, 10000000), Title = attachmentFile.Name });
                    }
                }

                if (random.GetRandomBool())
                {
                    for (int j = 0; j < random.GetRandomNumber(1, 5); j++)
                    {
                        string randomTag = random.GetRandom(defaultTags);
                        if (!post.Tags.Contains(randomTag))
                            post.Tags.Add(randomTag);
                    }
                }

                posts.Add(post);
            }

            var data = new AppData
            {
                Posts = posts,
                Users = people,
                CurrentUser = currentUser
            };

            SaveDataToDisk(data);
        }
コード例 #38
0
ファイル: FrmCulture.cs プロジェクト: wuchang/scada-v6
 /// <summary>
 /// Initializes a new instance of the class.
 /// </summary>
 public FrmCulture(AppData appData)
     : this()
 {
     this.appData = appData ?? throw new ArgumentNullException(nameof(appData));
 }
コード例 #39
0
ファイル: Program.cs プロジェクト: sumitjoshi01/BackupManager
        static void Main(string[] args)
        {
            List <ConfigModel> configList      = null;
            string             backupDirectory = string.Empty;

            try
            {
                if (applicationData == null)
                {
                    applicationData = AppData.Load();
                }

                applicationData.NoOfTimesAppRan = ++applicationData.NoOfTimesAppRan;
                applicationData.LastRanTime     = DateTime.Now.ToString("dd-MMM-yyyy hh:mm:ss tt");

                PrintDescriptionAndAuthorInfo();

                backupDirectory = ConfigHelper.GetSetting <string>("BackupFolder");

                CreateRootBackupDirIfNotExist(backupDirectory);

                BackupExistResult bkpExistRslt = IsBackupExist(backupDirectory);

                string newBackupDirName = bkpExistRslt.GetNewBackupDirName(ConfigHelper.GetSetting <string>("BkpFolderDatePattern"));
                if (bkpExistRslt.IsTodaysBackupExist)
                {
                    Console.WriteLine($"Backup Already Exist At {bkpExistRslt.TodaysBackupDirName}. Creating New Backup At {newBackupDirName}\n");
                }

                configList = LoadBackupConfigFile();

                string todaysBackupDir = Path.Combine(backupDirectory, newBackupDirName);

                TakeBackup(configList, todaysBackupDir);

                applicationData.NoOfFilesBackedUp       += fileCount;
                applicationData.NoOfDirectoriesBackedUp += dirCount;
                applicationData.Save();

                // Delete backup after taking backup
                if (ConfigHelper.GetSetting <bool>("IsDelOldBackups"))
                {
                    DeleteExistingBackups(bkpExistRslt.ExistingBackupList);
                }

                Console.WriteLine($"\nBackup Completed. Copied {fileCount} files and {dirCount} folders");
            }
            catch (Exception ex)
            {
                File.AppendAllText("ExceptionDetail.txt", $"{DateTime.Now:dd/MM/yyyy hh:ss:ss tt}\r\n{ex}\r\n");
                SendErrorMail(ex);
            }

            if (ConfigHelper.GetSetting <bool>("SendBackupSuccessMail"))
            {
                string recepiant = ConfigHelper.GetSetting <string>("BackupSuccessMailRecepiants");

                if (string.IsNullOrEmpty(recepiant))
                {
                    return;
                }

                string backupSuccessSubject = $"{ConfigHelper.GetSetting<string>("BackupSuccessMailSubject")} - {DateTime.Now:dd-MM-yyyy}";

                IEnumerable <ConfigModel> srcDirCnt = configList.Where(C => C.ConfigPattern == ConfigPatterns.SourceFolder);

                var foldersOrFolderTxt = srcDirCnt.Count() > 1 ? "folders" : "folder";

                StringBuilder mailBody = new StringBuilder(string.Empty);

                mailBody.AppendLine($"Backup of below {foldersOrFolderTxt} successfully created at {backupDirectory} on machine {Environment.MachineName}");

                foreach (var item in srcDirCnt)
                {
                    mailBody.AppendLine(item.Value);
                }

                if (ConfigHelper.GetSetting <bool>("IsDelOldBackups"))
                {
                    mailBody.AppendLine($"\"Delete Previous Backups\" setting is enabled and only keeping last {ConfigHelper.GetSetting<int>("DelOldBackupGreaterThan")} backups.");
                }

                SendMail(recepiant, backupSuccessSubject, mailBody.ToString());
            }

            if (ConfigHelper.GetSetting <bool>("ShowConsoleAfterComplete"))
            {
                Console.ReadKey();
            }
        }
コード例 #40
0
        private void DownloadVideo(string videoPath = "")
        {
            if (_targetModel == null && this.DataContext is MessageModel item)
            {
                _targetModel = item;
            }
            if (!string.IsNullOrEmpty(videoPath))
            {
                _targetModel.Content = videoPath;
                _targetModel.ResourceModel.FullName = videoPath;
            }

            if (AppData.CanInternetAction())
            {
                if (this._targetModel.MessageState == MessageStates.Loading)
                {
                    AppData.MainMV.TipMessage = "视频正在下载,请稍候";
                    return;
                }
                if (this._targetModel.MessageState == MessageStates.Fail || this._targetModel.MessageState == MessageStates.Warn)
                {
                    AppData.MainMV.TipMessage = "视频消息发送失败,无法下载";
                    return;
                }
                this._targetModel.MessageState = MessageStates.Loading;
                this.gridProgress.Visibility   = Visibility.Visible;
                this.borderPlay.Visibility     = Visibility.Collapsed;
                this.imgReset.Visibility       = Visibility.Collapsed;
                this.imgDownload.Visibility    = Visibility.Collapsed;
                //IMClient.Helper.MessageHelper.LoadVideoPreviewImage(this._targetModel);
                IMClient.Helper.MessageHelper.LoadVideoContent(this._targetModel, (b) =>
                {
                    if (b)
                    {
                        this._targetModel.MessageState = MessageStates.Success;
                        App.Current.Dispatcher.Invoke(() =>
                        {
                            this.gridProgress.Visibility = Visibility.Collapsed;
                            this.borderPlay.Visibility   = Visibility.Visible;
                            this.imgReset.Visibility     = Visibility.Collapsed;
                            this.imgDownload.Visibility  = Visibility.Collapsed;
                        });
                    }
                    else
                    {
                        this._targetModel.MessageState            = MessageStates.Fail;
                        this._targetModel.ResourceModel.FileState = FileStates.None;
                        App.Current.Dispatcher.Invoke(() =>
                        {
                            this.gridProgress.Visibility = Visibility.Collapsed;
                            this.borderPlay.Visibility   = Visibility.Collapsed;
                            this.imgReset.Visibility     = Visibility.Collapsed;
                            this.imgDownload.Visibility  = Visibility.Visible;
                        });
                    }
                });
            }
            else
            {
                this._targetModel.ResourceModel.FileState = FileStates.None;
                //this._targetModel.MessageState = MessageStates.None;
                //this.gridProgress.Visibility = Visibility.Collapsed;
                //this.borderPlay.Visibility = Visibility.Collapsed;
                //this.imgReset.Visibility = Visibility.Collapsed;
                //this.imgDownload.Visibility = Visibility.Visible;
                //IMClient.Helper.MessageHelper.LoadVideoContent(this._targetModel);
            }
        }