Ejemplo n.º 1
0
		public void Construct()
		{
			using (Prompt prompt = new Prompt())
			{
				Assert.IsNotNull(prompt);
			}
		}
Ejemplo n.º 2
0
        public SynthesisState(SpeechSynthesizer synthesizer, Prompt promptBeingSynthesized)
        {
            Synthesizer = synthesizer;
            PromptBeingSynthesized = promptBeingSynthesized;

            synthesizer.SpeakCompleted += SynthesizerOnSpeakCompleted;
        }
Ejemplo n.º 3
0
    void Start()
    {
        // Stop reorientation weirdness
        // http://answers.unity3d.com/questions/14655/unity-iphone-black-rect-when-i-turn-the-iphone
        Screen.autorotateToPortrait = false;
        Screen.autorotateToPortraitUpsideDown = false;
        Screen.autorotateToLandscapeRight = false;
        Screen.autorotateToLandscapeLeft = false;

        sounds = new Sounds(gameObject);
        sounds.Start();

        var loopTracker = new LoopTracker(sounds);

        var textLabel = new GameObject("prompt text");
        textLabel.SetActive(false);
        var text = textLabel.AddComponent<GUIText>();
        textLabel.transform.position = new Vector3(0f, 0.06f, -9.5f);
        var font = (Font) Resources.Load("sierra_agi_font/sierra_agi_font", typeof(Font));
        text.font = font;

        messageBox = new MessageBox(font);
        var prompt = new Prompt(textLabel, text).build();

        sceneManager = new SceneManager(loopTracker, new MessagePromptCoordinator(prompt, messageBox));
    }
Ejemplo n.º 4
0
 protected IActionResult Prompt(Action<Prompt> setupPrompt)
 {
     var prompt = new Prompt();
     setupPrompt(prompt);
     Response.StatusCode = prompt.StatusCode;
     return View("Prompt", prompt);
 }
Ejemplo n.º 5
0
 public override void Output(string output)
 {
     if (!Brain.Awake)
         return;
     output = output.StripHtml().RemoveExtraSpaces();
     //if (_current != null)
        // _synthesizer.SpeakAsyncCancel(_current);
     _current = _synthesizer.SpeakAsync(output);
 }
Ejemplo n.º 6
0
        public void Say(string text)
        {
            EnsureSynthesizer();

            if (prompt != null)
                synth.SpeakAsyncCancel(prompt);

            prompt = synth.SpeakAsync(text);
        }
Ejemplo n.º 7
0
        public void SpeakAsync(Prompt prompt, String text)
        {
            _spokenWords.Push(text);

            if (!Settings.Muted)
                _voice.SpeakAsync(prompt);

            if (Spoke != null)
                Spoke(text);
        }
Ejemplo n.º 8
0
		public void CanExtend_CalledAfterDisposed_Throws()
		{
			var prompt = new Prompt();
			prompt.Dispose();
			using (var textBox = new TextBox())
			{
				Assert.Throws<ObjectDisposedException>(
					() => prompt.CanExtend(textBox)
				);
			}
		}
Ejemplo n.º 9
0
	public static void DisplayPrompt(Prompt p, Bound f)
	{
		prompt = p;
		if (p.button != null) {
			promptText.text = p.button.ToUpper () + " - " + p.text.ToUpper ();
		} else {
			promptText.text = p.text.ToUpper ();
		}
		promptText.enabled = true;
		callback = f;
	}
Ejemplo n.º 10
0
    protected override void LoadContent()
    {
        var spriteRenderer = new SpriteRenderer(graphics, Content);
        prompt = new Prompt(spriteRenderer, Content);
        messageBox = new MessageBox(Content, spriteRenderer);
        var sounds = new Sounds();
        sceneManager = new SceneManager(new LoopTracker(sounds),
                                        new MessagePromptCoordinator(prompt, messageBox));
        var sceneFactory = new SceneFactory(sceneManager, spriteRenderer);

        // create the scene objects and preload their content
        sceneManager.LoadAndStart(sceneFactory);
    }
Ejemplo n.º 11
0
        void _jukebox_SongStarting(object sender, SongEventArgs e)
        {
            if (_lastTempFile != null)
            {
                if (File.Exists(_lastTempFile))
                    File.Delete(_lastTempFile);

                _lastTempFile = null;
            }

            var script = GetScript(e.Song);

            var prompt = new Prompt(script, SynthesisTextFormat.Text);

            var tempFile = Path.GetTempFileName();

            using (var speaker = new SpeechSynthesizer())
            {
                speaker.SetOutputToWaveFile(
                    tempFile,
                    this._audioFormat);

                speaker.Speak(prompt);
            }

            this._mediaPlayer.PlaySong(null, tempFile);

            using (var mre = new ManualResetEvent(false))
            {
                var handler = new EventHandler((s, args) => mre.Set());

                this._mediaPlayer.SongFinished += handler;
                try
                {
                    this._mediaPlayer.PlaySong(null, tempFile);
                    mre.WaitOne();
                }
                catch (Exception ex)
                {
                    Trace.WriteLine(string.Format("Error playing prompt: {0}", ex), "SongAnnouncer");
                }
                finally
                {
                    this._mediaPlayer.SongFinished -= handler;
                }
            }

            _lastTempFile = tempFile;
        }
Ejemplo n.º 12
0
 public virtual void HandleUnauthorizedRequest(ActionExecutingContext context)
 {
     var prompt = new Prompt
     {
         Title = "Sign Out First",
         StatusCode = 403,
         Details = "You must be a guest to visit this page."
     };
     var services = context.HttpContext.ApplicationServices;
     context.Result = new ViewResult
     {
         StatusCode = prompt.StatusCode,
         TempData = new TempDataDictionary(services.GetRequiredService<IHttpContextAccessor>(), services.GetRequiredService<ITempDataProvider>()),
         ViewName = "Prompt",
         ViewData = new ViewDataDictionary(new EmptyModelMetadataProvider(), context.ModelState) { Model = prompt }
     };
 }
Ejemplo n.º 13
0
 public virtual void HandleUnauthorizedRequest(ActionExecutingContext context)
 {
     var prompt = new Prompt
     {
         Title = "Permission Denied",
         StatusCode = 403,
         Details = "You must sign in with a higher power account.",
         Requires = "Claims",
         Hint = claimTypes
     };
     var services = context.HttpContext.RequestServices;
     context.Result = new ViewResult
     {
         StatusCode = prompt.StatusCode,
         TempData = new TempDataDictionary(services.GetRequiredService<IHttpContextAccessor>().HttpContext, services.GetRequiredService<ITempDataProvider>()),
         ViewName = "Prompt",
         ViewData = new ViewDataDictionary(new EmptyModelMetadataProvider(), context.ModelState) { Model = prompt }
     };
 }
Ejemplo n.º 14
0
        private void btnTest_Click(object sender, EventArgs e)
        {
            var p = new Prompt(LocRm.GetString("UploadTo"), _testloc);
            p.ShowDialog(this);
            if (p.Val != "")
            {
                _testloc = p.Val;
                using (var imageStream = new MemoryStream())
                {
                    try
                    {
                        Resources.cam_offline.Save(imageStream, ImageFormat.Jpeg);

                        string error;
                        txtFTPServer.Text = txtFTPServer.Text.Trim('/');
                        if (txtFTPServer.Text.IndexOf("/", StringComparison.Ordinal) == -1)
                        {
                            txtFTPServer.Text = "ftp://" + txtFTPServer.Text;
                        }
                        string fn = String.Format(CultureInfo.InvariantCulture, _testloc, Helper.Now);
                        if ((new AsynchronousFtpUpLoader()).FTP(txtFTPServer.Text + ":" + txtFTPPort.Text,
                                                                chkUsePassive.Checked,
                                                                txtFTPUsername.Text, txtFTPPassword.Text, fn, 0,
                                                                imageStream.ToArray(), out error, chkFTPRename.Checked))
                        {
                            MessageBox.Show(LocRm.GetString("ImageUploaded"), LocRm.GetString("Success"));
                        }
                        else
                            MessageBox.Show(string.Format("{0}: {1}", LocRm.GetString("UploadFailed"), error), LocRm.GetString("Failed"));
                    }
                    catch (Exception ex)
                    {
                        MainForm.LogExceptionToFile(ex);
                        MessageBox.Show(ex.Message);
                    }
                    imageStream.Close();
                }
            }
        }
Ejemplo n.º 15
0
        public bool Save()
        {
            if (EncDec.DecryptData(_group.password,MainForm.Conf.EncryptCode)!=txtPassword.Text)
            {
                var p = new Prompt(LocRm.GetString("ConfirmPassword")+": "+_group.name, "", true);
                if (p.ShowDialog(this) == DialogResult.OK)
                {
                    var v = p.Val;
                    if (v != txtPassword.Text)
                    {
                        MessageBox.Show(this, LocRm.GetString("PasswordMismatch"));
                        p.Dispose();
                        return false;
                    }
                }
                p.Dispose();
                _group.password =  EncDec.EncryptData(txtPassword.Text,MainForm.Conf.EncryptCode);
            }

            var tot = (from CheckBox c in fpFeatures.Controls where c.Checked select (int)c.Tag).Sum();
            _group.featureset = tot;
            return true;
        }
Ejemplo n.º 16
0
 /// <summary>
 /// Cancels the asynchronous speech of the given prompt.
 /// </summary>
 /// <param name="prompt">The prompt to cancel.</param>
 public virtual void SpeakAsyncCancel(Prompt prompt)
 {
     throw new NotImplementedException();
 }
Ejemplo n.º 17
0
        private void ovalPictureBox1_Click(object sender, EventArgs e)
        {
            count++;
            textBox1.Text = Convert.ToString(count);

            //Cursor.Position = new Point(x+x1,y+y1);
            if (count == 1)
            {
                ovalPictureBox1.BackColor = Color.RosyBrown;
                timer1.Interval           = 500;
            }
            else if (count == 2)
            {
                ovalPictureBox1.BackColor = Color.Khaki;
                timer1.Interval           = 475;
            }
            else if (count == 3)
            {
                ovalPictureBox1.BackColor = Color.SteelBlue;
                timer1.Interval           = 450;
            }
            else if (count == 4)
            {
                ovalPictureBox1.BackColor = Color.Plum;
                timer1.Interval           = 400;
            }
            else if (count == 5)
            {
                ovalPictureBox1.BackColor = Color.Pink;
                timer1.Stop();
                timer2.Stop();
                gametime = time;
                this.sort_winners();
                highsc = this.getLowerScoreForHighScores();
                if (gametime < highsc)
                {
                    string name = Prompt.ShowDialog("Enter please your name", "New Record!");
                    this.SetWinnerName(name, gametime);
                }
                DialogResult dialog = MessageBox.Show("Do you want to play again?",
                                                      "You win!", MessageBoxButtons.YesNo);
                if (dialog == DialogResult.Yes)
                {
                    textBox1.Text = "0";
                    count         = 0;
                    time          = 0;
                    label1.Text   = "00:00";
                    timer1.Start();
                    timer2.Start();
                }
                else if (dialog == DialogResult.No)
                {
                    count                   = 0;
                    time                    = 0;
                    textBox1.Text           = "0";
                    label1.Text             = "00:00";
                    ovalPictureBox1.Enabled = false;
                    Start.Enabled           = true;
                    HighScores.Enabled      = true;
                    Pause_Resume.Enabled    = false;
                    HighScores.BackColor    = Color.MintCream;
                    HighScores.ForeColor    = Color.LightSlateGray;
                    splitter1.BackColor     = Color.LightSlateGray;
                    Start.BackColor         = Color.MintCream;
                    Start.ForeColor         = Color.LightSlateGray;
                    Pause_Resume.BackColor  = Color.LightSlateGray;
                    Pause_Resume.ForeColor  = Color.SlateGray;

                    //this.Hide();
                    //form.ShowDialog();
                }
            }
        }
Ejemplo n.º 18
0
 internal VoiceChangeEventArgs(Prompt prompt, VoiceInfo voice)
     : base(prompt)
 {
     _voice = voice;
 }
Ejemplo n.º 19
0
        /// <summary>
        /// Private helper method to initialize the CSTA voice device
        /// </summary>
        private void initializeVoiceDevice()
        {
            p = new Provider(inputParam.sipServerIP, new CredentialManager(inputParam.sipServerIP));

            Phone cdsPhone = Utilities.GetPhone(inputParam.sipServerIP, Utilities.LocalMacAddresses[0], inputParam.myExtension);
            if (cdsPhone == null)
            {
                throw new ApplicationException("Cannot find phone owned by " + inputParam.myExtension + " on server");
            }

            /**
             * To create an instance of VoiceDevice, use GenericInteractiveVoice as the flag.
             */
            phone = p.GetDevice(inputParam.myExtension, Provider.DeviceCategory.GenericInteractiveVoice, cdsPhone.FunctionId) as VoiceDevice;

            /**
             * Setup event handler methods
             */
            phone.Established += new EstablishedEventHandler(phone_Established);
            phone.ConnectionCleared += new ConnectionClearedEventHandler(phone_ConnectionCleared);
            phone.InfoEventReceived += new InfoEventHandler(phone_InfoEventReceived);
            phone.Originated += new OriginatedEventHandler(phone_Originated);
            phone.Delivered += new DeliveredEventHandler(phone_Delivered);
            phone.RegistrationStateChanged += new RegistrationStateChangedEventHandler(phone_RegistrationStateChanged);
            /**
             * Allocate a prompt
             */
            pm = phone.AllocatePrompt("CalleePrompt");
            pm.Started += new VoiceEventHandler(pm_Started);
            pm.Completed += new VoiceEventHandler(pm_Completed);
            pm.InterruptionDetected += new VoiceEventHandler(pm_InterruptionDetected);
            pm.VoiceErrorOccurred += new VoiceEventHandler(pm_VoiceErrorOccurred);
            prepareListener();

            // Now prepare the recorder
            if (allowRecording == true)
                prepareRecorder();
        }
Ejemplo n.º 20
0
            private void OnExecute(CommandLineApplication app, IConsole console)
            {
                #region 验证

                var deleteFile = false;
                if (File.Exists(SavePath))
                {
                    deleteFile = Prompt.GetYesNo($"{SavePath}{Environment.NewLine}文件已经存在,您确认覆盖当前文件吗?", false, ConsoleColor.Yellow);
                    if (!deleteFile)
                    {
                        return;
                    }
                }

                if (!File.Exists(ConfigPath))
                {
                    console.ForegroundColor = ConsoleColor.Yellow;
                    console.WriteLine("生成 Ocelot Swagger 文档的配置文件不存在。");
                    console.WriteLine(ConfigPath);
                    console.ResetColor();
                    return;
                }

                if (!File.Exists(OcelotPath))
                {
                    console.ForegroundColor = ConsoleColor.Yellow;
                    console.WriteLine("Ocelot 配置文件不存在。");
                    console.WriteLine(OcelotPath);
                    console.ResetColor();
                    return;
                }

                #endregion

                var generator = new OcelotSwaggerGenerator()
                {
                    ThrowException = false
                };

                var settings      = OcelotSwaggerSettings.FromFile(ConfigPath);
                var configuration = Configuration.FromFile(OcelotPath);

                var doc = generator.Generate(settings, configuration).GetAwaiter().GetResult();

                try
                {
                    var json = doc.ToJson();

                    if (deleteFile)
                    {
                        File.Delete(SavePath);
                    }

                    using (var sw = new StreamWriter(SavePath))
                    {
                        sw.Write(json);
                    }

                    console.ForegroundColor = ConsoleColor.Green;
                    console.WriteLine("已完成 Swagger 文档生成,请查看:");
                    console.WriteLine(SavePath);
                    console.ResetColor();
                }
                catch (Exception ex)
                {
                    console.ForegroundColor = ConsoleColor.Red;
                    console.WriteLine(ex.Message);
                    console.WriteLine("生成失败,请查看日志。");
                    console.ResetColor();
                }
            }
Ejemplo n.º 21
0
        private void toolStripButton_Save_Click(object sender, EventArgs e)
        {
            if (textBox_CusName.Text.Equals(""))
            {
                Prompt.Information("未选择新客户信息!");
                return;
            }

            if (textBox_AgreementNum.Text.Trim().Equals(""))
            {
                Prompt.Information("编号不能为空!");
                return;
            }

            using (SqlConnection connection = SqlHelper.OpenConnection())  //创建连接对象
            {
                SqlTransaction sqlTran = connection.BeginTransaction();    //开始事务
                SqlCommand     cmd     = connection.CreateCommand();       //创建SqlCommand对象
                cmd.Transaction = sqlTran;                                 //将SqlCommand与SqlTransaction关联起

                try
                {
                    if (OperType == OperationType.contract)
                    {
                        //签约主表
                        cmd.CommandText = string.Format("update ContractMain Set CustomerID = {0}, CustomerName = '{1}', CustomerPhone = '{2}',ContractNum = '{3}' where ContractID = {4}",
                                                        textBox_CusName.Tag.ToString(), textBox_CusName.Text, textBox_CusPhone.Text, textBox_AgreementNum.Text.Trim(), AgreementID);
                    }
                    else
                    {
                        //认购主表
                        cmd.CommandText = string.Format("update SubscribeMain Set CustomerID = {0}, CustomerName = '{1}', CustomerPhone = '{2}',SubscribeNum = '{3}' where SubscribeID = {4}",
                                                        textBox_CusName.Tag.ToString(), textBox_CusName.Text, textBox_CusPhone.Text, textBox_AgreementNum.Text.Trim(), AgreementID);
                    }
                    cmd.ExecuteNonQuery();

                    //更名记录
                    string strValue = AgreementID + ",'" + OperType.ToString() + "'," + CustomerID + ",'" + textBox_OrigCusName.Text + "','" + textBox_OrigCusPhone.Text + "'," + textBox_CusName.Tag.ToString() + ",'" + textBox_CusName.Text + "',"
                                      + "'" + dateTimePicker_ChangeNameDate.Value.ToString("yyyy-MM-dd") + "','" + textBox_Memo.Text + "','" + textBox_Relation.Text.Trim() + "','" + Login.User.UserName + "',GETDATE()";
                    cmd.CommandText = string.Format("insert into NameExchange "
                                                    + "(AgreementID,ExchangeType,OrigID,OrigName,OrigPhone,NewID,NewName,ExchangeDate,Memo,Relation, MakeUserName,MakeDate) values ({0})", strValue);
                    cmd.ExecuteNonQuery();



                    sqlTran.Commit();  //事务提交
                    connection.Close();

                    NewCustomer.CustomerID   = textBox_CusName.Tag.ToString();
                    NewCustomer.CustomerName = textBox_CusName.Text;
                    NewCustomer.Phone        = textBox_CusPhone.Text;

                    this.DialogResult = System.Windows.Forms.DialogResult.OK;
                }
                catch (Exception ex)
                {
                    sqlTran.Rollback();  //异常事务回滚
                    Prompt.Error("操作失败, 错误:" + ex.Message);
                }
            }
        }
Ejemplo n.º 22
0
		public void GetSite_CalledAfterDisposed_Throws()
		{
#pragma warning disable 219
			var prompt = new Prompt();
			prompt.Dispose();
			ISite site;
			Assert.Throws<ObjectDisposedException>(
				() => site = prompt.Site
			);
#pragma warning restore 219
		}
Ejemplo n.º 23
0
 public MessagePromptCoordinator(Prompt prompt, MessageBox messageBox)
 {
     this.prompt = prompt;
     this.messageBox = messageBox;
 }
Ejemplo n.º 24
0
        static async Task Main(string[] args)
        {
            var companyId   = 0;
            var accessToken = "";

            // Configuration を作成
            var config = new Configuration
            {
                AccessToken = accessToken
            };

            // 各種マスタの取得
            var accountItems = await new AccountItemsApi(config).GetAccountItemsAsync(companyId);
            var taxesCodes   = await new TaxesApi(config).GetTaxCodesAsync();
            var partners     = await new PartnersApi(config).GetPartnersAsync(companyId);
            var sections     = await new SectionsApi(config).GetSectionsAsync(companyId);
            var items        = await new ItemsApi(config).GetItemsAsync(companyId);
            var tags         = await new TagsApi(config).GetTagsAsync(companyId);

            // ユーザー入力
            var selectedAccountItem = Prompt.Select("勘定科目", accountItems.AccountItems, valueSelector: x => x.Name);
            var selectedTaxesCode   = Prompt.Select("税区分コード", taxesCodes.Taxes, valueSelector: x => x.NameJa);
            var selectedPartner     = Prompt.Select("取引先", partners.Partners, valueSelector: x => x.Name);
            var selectedSection     = Prompt.Select("部門", sections.Sections, valueSelector: x => x.Name);
            var selectedItem        = Prompt.Select("品目", items.Items, valueSelector: x => x.Name);
            var selectedTag         = Prompt.Select("タグ", tags.Tags, valueSelector: x => x.Name);

            var amount = Prompt.Input <int>("取引金額");

            // 未決済取引の作成
            var details = new List <CreateDealParamsDetails>
            {
                new CreateDealParamsDetails
                {
                    AccountItemId = selectedAccountItem.Id,
                    Amount        = amount,
                    ItemId        = selectedItem.Id,
                    SectionId     = selectedSection.Id,
                    TagIds        = new List <int> {
                        selectedTag.Id
                    },
                    TaxCode = selectedTaxesCode.Code
                }
            };

            var dealResponse = await new DealsApi(config).CreateDealAsync(new CreateDealParams(
                                                                              "2019-07-01", CreateDealParams.TypeEnum.Income, companyId, "2019-08-31",
                                                                              selectedPartner.Id, details: details, refNumber: "100"));

            var newDeal = dealResponse.Deal;

            Console.WriteLine("取引(未決済)を作成しました。");

            // ユーザー入力
            var walletables = await new WalletablesApi(config).GetWalletablesAsync(companyId);

            var selectedWalletable = Prompt.Select("決済口座", walletables.Walletables, valueSelector: x => x.Name);

            // 決済の登録
            var paymentResponse = await new PaymentsApi(config).CreateDealPaymentAsync(newDeal.Id, new DealPaymentParams(
                                                                                           companyId, "2019-07-30", ToWalletableTypeEnum(selectedWalletable.Type), selectedWalletable.Id, amount));

            Console.WriteLine("決済を登録しました。");

            var updateDeal = paymentResponse.Deal;

            // 更新の登録
            await new RenewsApi(config).CreateDealRenewAsync(updateDeal.Id, new RenewsCreateParams(
                                                                 companyId, "2019-07-30", updateDeal.Details[0].Id, new List <RenewsCreateDetailParams>
            {
                new RenewsCreateDetailParams
                {
                    AccountItemId = selectedAccountItem.Id,
                    Amount        = amount,
                    ItemId        = selectedItem.Id,
                    SectionId     = selectedSection.Id,
                    TagIds        = new List <int> {
                        selectedTag.Id
                    },
                    TaxCode = selectedTaxesCode.Code
                }
            }));
        }
Ejemplo n.º 25
0
		public void SetPrompt_CalledAfterDisposed_Throws()
		{
			var prompt = new Prompt();
			prompt.Dispose();
			using (var textBox = new TextBox())
			{
				Assert.Throws<ObjectDisposedException>(
					() => prompt.SetPrompt(textBox, "prompt")
				);
			}
		}
Ejemplo n.º 26
0
 public bool GetYesNo(string message, bool defaultAnswer)
 {
     return(Prompt.GetYesNo(message, defaultAnswer, ConsoleColor.DarkGreen));
 }
Ejemplo n.º 27
0
        protected override async Task <int> Run(CommandLineApplication command)
        {
            var environmentName  = GetStringFromUser(RenameReleaseOptionNames.Environment, languageProvider.GetString(LanguageSection.UiStrings, "WhichEnvironmentPrompt"));
            var releaseName      = GetStringFromUser(RenameReleaseOptionNames.ReleaseName, languageProvider.GetString(LanguageSection.UiStrings, "ReleaseNamePrompt"));
            var groupRestriction = GetStringFromUser(RenameReleaseOptionNames.GroupFilter, languageProvider.GetString(LanguageSection.UiStrings, "RestrictToGroupsPrompt"), allowEmpty: true);

            var environment = await FetchEnvironmentFromUserInput(environmentName);

            if (environment == null)
            {
                return(-2);
            }

            if (!SemanticVersion.TryParse(releaseName, out _))
            {
                System.Console.WriteLine(languageProvider.GetString(LanguageSection.UiStrings, "InvalidReleaseVersion"));
                return(-2);
            }

            var groupIds = new List <string>();

            if (!string.IsNullOrEmpty(groupRestriction))
            {
                progressBar.WriteStatusLine(languageProvider.GetString(LanguageSection.UiStrings, "GettingGroupInfo"));
                groupIds =
                    (await octoHelper.GetFilteredProjectGroups(groupRestriction))
                    .Select(g => g.Id).ToList();
            }

            var projectStubs = await octoHelper.GetProjectStubs();

            var toRename = new List <ProjectRelease>();

            progressBar.CleanCurrentLine();

            foreach (var projectStub in projectStubs)
            {
                progressBar.WriteProgress(projectStubs.IndexOf(projectStub) + 1, projectStubs.Count(),
                                          String.Format(languageProvider.GetString(LanguageSection.UiStrings, "LoadingInfoFor"), projectStub.ProjectName));
                if (!string.IsNullOrEmpty(groupRestriction))
                {
                    if (!groupIds.Contains(projectStub.ProjectGroupId))
                    {
                        continue;
                    }
                }

                var release = (await this.octoHelper.GetReleasedVersion(projectStub.ProjectId, environment.Id)).Release;
                if (release != null && !release.Version.Equals("none", StringComparison.InvariantCultureIgnoreCase))
                {
                    toRename.Add(new ProjectRelease {
                        Release = release, ProjectStub = projectStub
                    });
                }
            }

            progressBar.CleanCurrentLine();

            System.Console.WriteLine();

            var table = new ConsoleTable(languageProvider.GetString(LanguageSection.UiStrings, "ProjectName"), languageProvider.GetString(LanguageSection.UiStrings, "CurrentRelease"));

            foreach (var release in toRename)
            {
                table.AddRow(release.ProjectStub.ProjectName, release.Release.Version);
            }

            table.Write(Format.Minimal);

            if (Prompt.GetYesNo(String.Format(languageProvider.GetString(LanguageSection.UiStrings, "GoingToRename"), releaseName), true))
            {
                foreach (var release in toRename)
                {
                    System.Console.WriteLine(languageProvider.GetString(LanguageSection.UiStrings, "Processing"), release.ProjectStub.ProjectName);
                    var result = await this.octoHelper.RenameRelease(release.Release.Id, releaseName);

                    if (result.success)
                    {
                        System.Console.WriteLine(languageProvider.GetString(LanguageSection.UiStrings, "Done"), release.ProjectStub.ProjectName);
                    }
                    else
                    {
                        System.Console.WriteLine(languageProvider.GetString(LanguageSection.UiStrings, "Failed"), release.ProjectStub.ProjectName, result.error);
                    }
                }
            }

            return(0);
        }
Ejemplo n.º 28
0
        private void Run()
        {
            if (ShowVersion)
            {
                if (SemVersion.TryParse(
                        FileVersionInfo.GetVersionInfo(typeof(Program).Assembly.Location).ProductVersion,
                        out var toolVersion))
                {
                    WriteLine(toolVersion);
                }
                else
                {
                    WriteLine(typeof(Program).Assembly.GetName().Version.ToString(3));
                }
                return;
            }

            var currentDirectory = new DirectoryInfo(Directory.GetCurrentDirectory());

            var projectFile = !string.IsNullOrWhiteSpace(ProjectFilePath)
                ? new FileInfo(ProjectFilePath)
                : currentDirectory.EnumerateFiles("*.csproj").FirstOrDefault();

            if (projectFile is null ||
                projectFile.Exists == false)
            {
                throw new CliException(1, $"Unable to find a project file in directory '{currentDirectory}'.");
            }

            var projectFileFullName = projectFile.FullName;

            var xDocument      = XDocument.Load(projectFileFullName);
            var versionElement = xDocument.Root?.Descendants("Version").FirstOrDefault();
            var currentVersion = ParseVersion(versionElement?.Value ?? "0.0.0");

            WriteLine($"Current version: {currentVersion}");

            if (Show)
            {
                return;
            }

            SemVersion version = null;

            if (!string.IsNullOrWhiteSpace(NewVersion))
            {
                version = ParseVersion(NewVersion);
            }
            else
            {
                if (Major)
                {
                    version = currentVersion.Change(
                        currentVersion.Major + 1,
                        0,
                        0,
                        "",
                        "");
                }
                else if (Minor)
                {
                    version = currentVersion.Change(
                        minor: currentVersion.Minor + 1,
                        patch: 0,
                        prerelease: "",
                        build: "");
                }
                else if (Patch)
                {
                    version = currentVersion.Change(
                        patch: currentVersion.Patch + 1,
                        prerelease: "",
                        build: "");
                }

                if (Final)
                {
                    version = (version ?? currentVersion).Change(
                        prerelease: string.Empty);
                }

                if (ReleaseCandidate)
                {
                    if (Final)
                    {
                        throw new CliException(1, "Can't increment release candidate number of the final version.");
                    }

                    version = (version ?? currentVersion).Change(
                        prerelease: CreatePreReleaseString(
                            ReleaseCandidateString,
                            version is null ? currentVersion.Prerelease : ""),
                        build: "");
                }
                else if (Beta)
                {
                    if (Final)
                    {
                        throw new CliException(1, "Can't increment beta number of the final version.");
                    }

                    if (version is null &&
                        currentVersion.Prerelease.StartsWith(ReleaseCandidateString,
                                                             StringComparison.OrdinalIgnoreCase))
                    {
                        throw new CliException(1,
                                               "Can't increment beta version number of a release candidate version number.");
                    }

                    version = (version ?? currentVersion).Change(
                        prerelease: CreatePreReleaseString(BetaString,
                                                           version is null ? currentVersion.Prerelease : ""),
                        build: "");
                }
                else if (Alpha)
                {
                    if (Final)
                    {
                        throw new CliException(1, "Can't increment alpha number of the final version.");
                    }

                    if (version is null &&
                        currentVersion.Prerelease.StartsWith(ReleaseCandidateString,
                                                             StringComparison.OrdinalIgnoreCase))
                    {
                        throw new CliException(1,
                                               "Can't increment alpha version number of a release candidate version number.");
                    }

                    if (version is null &&
                        currentVersion.Prerelease.StartsWith(BetaString, StringComparison.OrdinalIgnoreCase))
                    {
                        throw new CliException(1, "Can't increment alpha version number of a beta version number.");
                    }

                    version = (version ?? currentVersion).Change(
                        prerelease: CreatePreReleaseString(AlphaString,
                                                           version is null ? currentVersion.Prerelease : ""),
                        build: "");
                }
            }

            if (version is null)
            {
                var inputVersion = Prompt.GetString("New version:");
                version = ParseVersion(inputVersion);
            }
            else
            {
                WriteLine($"New version: {version}");
            }

            if (versionElement is null)
            {
                var propertyGroupElement = xDocument.Root?.Descendants("PropertyGroup").FirstOrDefault();
                if (propertyGroupElement is null)
                {
                    propertyGroupElement = new XElement("PropertyGroup");
                    xDocument.Root?.Add(propertyGroupElement);
                }

                propertyGroupElement.Add(new XElement("Version", version));
            }
            else
            {
                versionElement.Value = version.ToString();
            }

            File.WriteAllText(projectFileFullName, xDocument.ToString());

            if (!NoGit)
            {
                if (string.IsNullOrWhiteSpace(ProjectFilePath))
                {
                    try
                    {
                        var tag     = $"{GitVersionPrefix}{version}";
                        var message = !string.IsNullOrWhiteSpace(CommitMessage)
                            ? CommitMessage
                            : tag;

                        Process.Start(new ProcessStartInfo("git", $"commit -am \"{message}\"")
                        {
                            RedirectStandardError  = true,
                            RedirectStandardOutput = true,
                        })?.WaitForExit();

                        if (!NoGitTag)
                        {
                            // Hack to make sure the wrong commit is tagged
                            Thread.Sleep(200);
                            Process.Start(new ProcessStartInfo("git", $"tag {tag}")
                            {
                                RedirectStandardError  = true,
                                RedirectStandardOutput = true,
                            })?.WaitForExit();
                        }
                    }
                    catch
                    {
                        /* Ignored */
                    }
                }
                else
                {
                    WriteLine(
                        "Not running git integration when project file has been specified, to prevent running git in wrong directory.");
                }
            }

            WriteLine($"Successfully set version to {version}");
        }
Ejemplo n.º 29
0
        public ExecuteResultEnum Create(IProjectCommandOptions options)
        {
            var path        = options.Path;
            var displayName = options.DisplayName;

            if (string.IsNullOrEmpty(path))
            {
                if (options.Silent)
                {
                    _reportService.Error($"Path to spocr.json is required");
                    _reportService.Output($"\tPlease use '--path'");
                    return(ExecuteResultEnum.Error);
                }
                else
                {
                    path = Prompt.GetString("Enter path to spocr.json, e.g. base directory of your project:", new DirectoryInfo(Directory.GetCurrentDirectory()).Name);
                }
            }

            if (string.IsNullOrEmpty(path))
            {
                return(ExecuteResultEnum.Aborted);
            }

            path = CreateConfigFilePath(path);

            if (string.IsNullOrEmpty(displayName))
            {
                displayName = CreateDisplayNameFromPath(path);
            }

            if (string.IsNullOrEmpty(displayName))
            {
                _reportService.Error($"DisplayName for project is required");
                _reportService.Output($"\tPlease use '--name'");
                return(ExecuteResultEnum.Error);
            }

            if (IsDisplayNameAlreadyUsed(displayName, options))
            {
                return(ExecuteResultEnum.Error);
            }

            _globalConfigFile.Config?.Projects.Add(new GlobalProjectConfigurationModel
            {
                DisplayName = displayName,
                ConfigFile  = path
            });

            _globalConfigFile.Save(_globalConfigFile.Config);

            if (options.Silent)
            {
                _reportService.Output($"{{ \"displayName\": \"{displayName}\" }}");
            }
            else
            {
                _reportService.Output($"Project '{displayName}' created.");
            }
            return(ExecuteResultEnum.Succeeded);
        }
Ejemplo n.º 30
0
    // Update is called once per frame
    void Update()
    {
        if (dialogue != null)
        {
            if (dcont)
            {
                if (!dialogue.Advance())
                {
                    dialogue = null;
                }
                else
                {
                    dcont = false;
                    Line l = dialogue.GetCurrentLine();

                    prompt = l.prompt;
                    print(l.text);

                    if (prompt != null)
                    {
                        prompt.Reset();
                        for (int i = 0; i < l.prompt.options.Length; i++)
                        {
                            if (l.prompt.options[i].available)
                            {
                                print("\t" + (i + 1) + ": " + l.prompt.options[i].text);
                            }
                        }
                    }
                }
            }

            if (Input.GetKeyDown(KeyCode.E) || (prompt != null && prompt.response != Prompt.Unanswered))
            {
                prompt = null;
                dcont  = true;
            }

            if (prompt != null)
            {
                if (Input.GetKeyDown(KeyCode.Keypad1))
                {
                    prompt.response = 0;
                }
                if (Input.GetKeyDown(KeyCode.Keypad2))
                {
                    prompt.response = 1;
                }
                if (Input.GetKeyDown(KeyCode.Keypad3))
                {
                    prompt.response = 2;
                }
                if (Input.GetKeyDown(KeyCode.Keypad4))
                {
                    prompt.response = 3;
                }
                if (Input.GetKeyDown(KeyCode.Keypad5))
                {
                    prompt.response = 4;
                }
                if (Input.GetKeyDown(KeyCode.Keypad6))
                {
                    prompt.response = 5;
                }
                if (Input.GetKeyDown(KeyCode.Keypad7))
                {
                    prompt.response = 6;
                }
                if (Input.GetKeyDown(KeyCode.Keypad8))
                {
                    prompt.response = 7;
                }
                if (Input.GetKeyDown(KeyCode.Keypad9))
                {
                    prompt.response = 8;
                }
            }
        }
        else
        {
            transform.localRotation     = Quaternion.Euler(Vector3.up * (mouseX += Input.GetAxis("Mouse X") * lookSpeed));
            cam.transform.localRotation = Quaternion.Euler(Vector3.left * (mouseY += Input.GetAxis("Mouse Y") * lookSpeed));
            if (characterController.isGrounded)
            {
                moveDirection = transform.right * Input.GetAxis("Horizontal") * moveSpeed + transform.forward * Input.GetAxis("Vertical") * moveSpeed + transform.up * (Input.GetKey(KeyCode.Space)?jumpPower:0);
            }
            else
            {
                moveDirection.y += gravity * Time.deltaTime;
            }

            characterController.Move(moveDirection);

            if (Input.GetKeyDown(KeyCode.E))
            {
                RaycastHit hit;
                if (Physics.Raycast(transform.position, transform.forward, out hit, 4))
                {
                    hit.collider.transform.GetComponent <MeshRenderer>().material.color = Color.green;
                    StartCoroutine("uncolor", hit);
                    dialogue = hit.collider.GetComponent <Dialogue>();
                    dialogue.Reset();
                    dcont = true;
                }
            }
        }
    }
Ejemplo n.º 31
0
		public void Dispose_CalledTwice_CallsHandlerOnce()
		{
			Prompt prompt = new Prompt();
			int disposedCalledCount = 0;
			prompt.Disposed += delegate { ++disposedCalledCount; };
			Assert.AreEqual(0, disposedCalledCount);
			prompt.Dispose();
			Assert.AreEqual(1, disposedCalledCount);
			prompt.Dispose();
			Assert.AreEqual(1, disposedCalledCount);
		}
Ejemplo n.º 32
0
        public void Init()
        {
            Prompt one = new Prompt("The Missus enters... You hear the door slam behind her. What do you do?");

            CurrentPrompt = (Prompt)one;

            Prompt two    = new Prompt("You ask her what is wrong.\nThe Missus: You'll NEVER guess what Becky said to me today..");
            Prompt three  = new Prompt("You tell her \"Hey, calm down.\" You have angered The Missus..\nThe Missus: Don't you tell me to CALM DOWN! What do you do?");
            Prompt four   = new Prompt("Not a good choice. You created an issue. The Missus now resents you. YOU LOSE.");
            Prompt five   = new Prompt("You apologize and tell her you are here to listen. The Missus: Thanks. I felt like a chicken sandwich today so I ordered one in,\nand Becky had the NERVE to tell me I should've stuck with a salad. Can you believe that?!");
            Prompt six    = new Prompt("You ask her why she is so upset. The Missus: Well, I felt like a chicken sandwich today so I ordered one in, \nand Becky had the NERVE to tell me I should've stuck with a salad. Can you believe that?!");
            Prompt seven  = new Prompt("You tell her she's overreacting. Not a good choice. You created an issue. The Missus now resents you. YOU LOSE.");
            Prompt eight  = new Prompt("The Missus: Thanks for listening. I felt like a chicken sandwich today so I ordered one in,\nand Becky had the NERVE to tell me I should've stuck with a salad. Can you believe that?!");
            Prompt nine   = new Prompt("You say \"Something snarky, I assume.\" The Missus: Oh, like THAT you mean?\n The Missus has given you an out..");
            Prompt ten    = new Prompt("The Missus: I felt like a chicken sandwich today so I ordered one in,\nand Becky had the NERVE to tell me I should've stuck with a salad. Can you believe that?!");
            Prompt eleven = new Prompt("The author would like to inform you, the plot has become too complex to continue. In honor of George R.R Martin,\n the next chapter in this story will be released in 7 years, give or take. Thanks for playing!");
            Prompt twelve = new Prompt("You refuse to take the Out. Wise Choice. You have listened to The Missus successfully, showing you care and being adequately invovled. YOU WIN!");


            Item Out = new Item("Out", "\"No Strings Attached\"");

            //2good, 3bad -- start
            //4 -- lose 7-- ovverreacting lose
            //5,6 --continue
            one.Choices.Add(Response.listen, two);
            one.Choices.Add(Response.question, two);
            one.Choices.Add(Response.statement, three);
            one.Choices.Add(Response.silence, four);
            two.Choices.Add(Response.listen, eight);
            two.Choices.Add(Response.question, six);
            two.Choices.Add(Response.statement, nine);
            two.Choices.Add(Response.silence, ten);
            three.Choices.Add(Response.listen, five);
            three.Choices.Add(Response.question, six);
            three.Choices.Add(Response.statement, seven);
            three.Choices.Add(Response.silence, four);
            five.Choices.Add(Response.listen, eleven);
            five.Choices.Add(Response.question, eleven);
            five.Choices.Add(Response.statement, eleven);
            five.Choices.Add(Response.silence, eleven);

            six.Choices.Add(Response.listen, eleven);
            six.Choices.Add(Response.question, eleven);
            six.Choices.Add(Response.statement, eleven);
            six.Choices.Add(Response.silence, eleven);

            eight.Choices.Add(Response.listen, eleven);
            eight.Choices.Add(Response.question, eleven);
            eight.Choices.Add(Response.statement, eleven);
            eight.Choices.Add(Response.silence, eleven);

            nine.Choices.Add(Response.listen, twelve);
            nine.Choices.Add(Response.question, eleven);
            nine.Choices.Add(Response.statement, eleven);
            nine.Choices.Add(Response.silence, eleven);

            ten.Choices.Add(Response.listen, eleven);
            ten.Choices.Add(Response.question, eleven);
            ten.Choices.Add(Response.statement, eleven);
            ten.Choices.Add(Response.silence, eleven);



            nine.Items.Add(Out);
            CurrentUser = new User();
        }
Ejemplo n.º 33
0
        //--------------------------------------------------------------------------------------------------------------------
        public async Task StartPlay(bool isFromStart)
        {
            synthesizer.SetOutputToDefaultAudioDevice();
            ICollectionView view = CollectionViewSource.GetDefaultView(SelectedTrak.Paragraphs);

            view.MoveCurrentToFirst();

            ctsPlay = new CancellationTokenSource();
            if (isFromStart)
            {
                SelectedTrak.Position = 0;
            }

            Task task = new Task(async() =>
            {
                try
                {
                    string currentSpeech = "";
                    for (int i = SelectedTrak.Position; i < SelectedTrak.Paragraphs.Count; i++)
                    {
                        currentSpeech = SelectedTrak.Paragraphs[i];
                        if (ctsPlay.Token.IsCancellationRequested)
                        {
                            break;
                        }

                        PromptBuilder promptBuilder = new PromptBuilder();
                        ProcessPhrase(promptBuilder, currentSpeech);

                        try
                        {
                            Prompt p = await speechSynthesizerAsTask.SpeakAsync(new Prompt(promptBuilder), ctsPlay.Token);
                        }
                        catch (OperationCanceledException oce)
                        {
                            break;
                        }
                        catch (Exception ce)
                        {
                            MessageBox.Show(ce.Message);
                        }

                        Thread.Sleep(SpeechPause);

                        Application.Current.Dispatcher.Invoke(
                            (Action)(() =>
                        {
                            SelectedTrak.Position = i;
                            OnSpeechPhraseScrollIntoView();
                        }));
                    }
                }
                catch (OperationCanceledException oce)
                {
                }
                catch (Exception ce)
                {
                    MessageBox.Show(ce.Message);
                }
                ctsPlay = null;
            },
                                 ctsPlay.Token);

            task.Start();

            try
            {
                await task;
            }
            catch (OperationCanceledException)
            {
                MessageBox.Show("Operation canceled");
            }
            // Check for other exceptions.
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
Ejemplo n.º 34
0
 public void SetOpeningLine(Prompt line)
 {
     currentOpeningLine = line;
 }
Ejemplo n.º 35
0
        private void toolStripButton_Del_Click(object sender, EventArgs e)
        {
            if (dataGridView_Contract.CurrentRow == null)
            {
                return;
            }

            string contractId = dataGridView_Contract.CurrentRow.Cells["ColContractID"].Value.ToString();

            if (dataGridView_Change.CurrentRow == null)
            {
                Prompt.Warning("未选择相关记录!");
                return;
            }

            string sql = string.Empty;

            int changeId = int.Parse(dataGridView_Change.CurrentRow.Cells["ColID"].Value.ToString());

            int maxId = int.Parse(SqlHelper.ExecuteScalar(string.Format("select IsNull(MAX(ID),0) from AreaChangeMain where ContractID = {0}", contractId)).ToString());

            if (changeId != maxId)
            {
                Prompt.Information("仅允许删除最后一次变更记录!");
                return;
            }

            //检验首付、贷款、总款变化时,不允许删除(影响数据恢复)
            sql = string.Format("select count(a.ContractID) from ContractMain a inner join AreaChangeMain b on b.ContractID = a.ContractID"
                                + " where a.DownPayAmount = b.NewDownPay and a.Loan = b.NewLoan and a.TotalAmount = b.NewTotalAmount and a.ContractID = {0}", contractId);
            if (int.Parse(SqlHelper.ExecuteScalar(sql).ToString()) == 0)
            {
                Prompt.Warning("数据已发生变更,无法删除!");
                return;
            }


            if (MessageBox.Show("确认要删除选择的记录吗?", Common.MsgCaption, MessageBoxButtons.YesNo, MessageBoxIcon.Question) == System.Windows.Forms.DialogResult.Yes)
            {
                string origArea        = string.Empty;
                string origAmount      = string.Empty;
                string origDownPay     = string.Empty;
                string origLoan        = string.Empty;
                string origTotalAmount = string.Empty;
                string itemId          = string.Empty;

                using (SqlConnection connection = SqlHelper.OpenConnection())  //创建连接对象
                {
                    SqlTransaction sqlTran = connection.BeginTransaction();    //开始事务
                    SqlCommand     cmd     = connection.CreateCommand();       //创建SqlCommand对象
                    cmd.Transaction = sqlTran;

                    try
                    {
                        sql = string.Format("select OrigDownPay, OrigLoan, OrigTotalAmount from AreaChangeMain where ID = {0}", changeId);
                        SqlDataReader sdr = SqlHelper.ExecuteReader(sql);

                        if (sdr.Read())
                        {
                            origDownPay     = sdr["OrigDownPay"].ToString();
                            origLoan        = sdr["OrigLoan"].ToString();
                            origTotalAmount = sdr["OrigTotalAmount"].ToString();

                            //恢复签约主表
                            cmd.CommandText = string.Format("update ContractMain set DownPayAmount = {0}, Loan = {1}, TotalAmount = {2} where ContractID = {3}", origDownPay, origLoan, origTotalAmount, contractId);
                            cmd.ExecuteNonQuery();

                            //恢复签约明细
                            sql = string.Format("select ItemID, OrigAmount, OrigArea from AreaChangeDetail where MainID = {0}", changeId);
                            SqlDataReader sdrOrigData = SqlHelper.ExecuteReader(sql);
                            while (sdrOrigData.Read())
                            {
                                itemId          = sdrOrigData["ItemID"].ToString();
                                origArea        = sdrOrigData["OrigArea"].ToString();
                                origAmount      = sdrOrigData["OrigAmount"].ToString();
                                cmd.CommandText = string.Format("update ContractDetail set Area = {0}, Amount = {1} where ContractID = {2} and ItemID = {3}", origArea, origAmount, contractId, itemId);
                                cmd.ExecuteNonQuery();
                            }
                            sdrOrigData.Close();
                        }

                        sdr.Close();

                        //恢复原始分期、删除历史分期
                        cmd.CommandText = string.Format("Delete Installment where ContractID = {0}", contractId);
                        cmd.ExecuteNonQuery();

                        cmd.CommandText = string.Format("insert into Installment (ContractID,Sequence,PayDate,Amount,Settled) select ContractID,Sequence,PayDate,Amount,Settled from InstallmentHis where ContractID = {0} and SourceID = {1}", contractId, changeId);
                        cmd.ExecuteNonQuery();

                        cmd.CommandText = string.Format("delete InstallmentHis where ContractID = {0} and SourceID = {1}", contractId, changeId);
                        cmd.ExecuteNonQuery();

                        //删除面积变更记录
                        cmd.CommandText = string.Format("delete AreaChangeMain where ID = {0}", changeId);
                        cmd.ExecuteNonQuery();

                        cmd.CommandText = string.Format("delete AreaChangeDetail where MainID = {0}", changeId);
                        cmd.ExecuteNonQuery();

                        sqlTran.Commit();  //事务提交
                    }
                    catch (Exception ex)
                    {
                        sqlTran.Rollback();  //异常事务回滚
                        Prompt.Error("操作失败, 错误:" + ex.Message);
                    }
                }

                Search(" and ContractMain.ContractID = " + contractId);

                Prompt.Information("操作成功,数据已经更新!");
            }
        }
Ejemplo n.º 36
0
        public void Speak(string textToSpeak)
        {
            _logger.LogInformation($"Speak({textToSpeak})");

            _currentPrompt = _speechSynthesizer.SpeakAsync(textToSpeak);
        }
Ejemplo n.º 37
0
 public VoiceResponse Prompt(Prompt prompt)
 {
     this.Append(prompt);
     return(this);
 }
Ejemplo n.º 38
0
 private void OnSpeakCompleted(object sender, SpeakCompletedEventArgs e)
 {
     SpeakCompleted();
     _currentPrompt = null;
 }
Ejemplo n.º 39
0
 public void Speak(Prompt prompt, String text)
 {
     SpeakAsync(prompt, text);
 }
Ejemplo n.º 40
0
        private static void HandleConsent(IWebDriver driver, LabUser user, UserInformationFieldIds fields, Prompt prompt)
        {
            // For MSA, a special consent screen seems to come up every now and then
            if (user.Upn.Contains("outlook.com"))
            {
                try
                {
                    Trace.WriteLine("Finding accept prompt");
                    var acceptBtn = driver.WaitForElementToBeVisibleAndEnabled(
                        ByIds(CoreUiTestConstants.ConsentAcceptId, fields.AADSignInButtonId),
                        waitTime: ShortExplicitTimespan,
                        ignoreFailures: true);
                    acceptBtn?.Click();
                }
                catch
                {
                    Trace.WriteLine("No accept prompt found accept prompt");
                }
            }

            if (prompt == Prompt.Consent)
            {
                Trace.WriteLine("Consenting...");
                driver.WaitForElementToBeVisibleAndEnabled(By.Id(fields.AADSignInButtonId)).Click();
            }
        }
Ejemplo n.º 41
0
        /// <summary>
        /// Private helper method for the constructors
        /// </summary>
        private void initializeCallee()
        {
            conn = null;
            phone = null;
            pm = null;
            ll = null;
            recorder = null;
            calleeData = null;
            isRegistered = false;

            /**
             * Read the configuration params file and populate suitable parameters
             */
            readConfigParams();
            display("Configration file = " + inputParam.configFile);

             //           this.numIterations = totalIter * totalSets;

            display("Extension = " + inputParam.myExtension);

            /**
             * Create an instance of prompt wait timer
             */
            promptTimer = new System.Windows.Forms.Timer();
            promptTimer.Enabled = false;
            promptTimer.Interval = promptWaitDuration * 1000;
            promptTimer.Tick += new System.EventHandler(promptTimer_Tick);

            missingHangupDetectionTimer = new System.Windows.Forms.Timer();
            missingHangupDetectionTimer.Enabled = false;

            // Missing hangup detection timer is set to 5 times maximum call duration and wait time between calls
            missingHangupDetectionTimer.Interval = 5 * (maxCallDuration + waitTimeBetweenCalls) * 1000;
            missingHangupDetectionTimer.Enabled = false;
            missingHangupDetectionTimer.Tick += new System.EventHandler(missingHangupDetectionTimer_Tick);
            initializeVoiceDevice();
        }
        public bool ProveraIspravnosti(Form forma)
        {
            bool ProveraIspravnosti = false;

            //forma = Program.Parent.ActiveMdiChild;

            sql = "Select Id_DokumentaView from GlavnaKnjiga where ID_DokumentaView =@param0";
            DataTable t = db.ParamsQueryDT(sql, iddokument);

            if (t.Rows.Count > 0)
            {
                if (forma.Controls.OfType <Field>().FirstOrDefault(n => n.IME == "Proknjizeno").Vrednost.Contains("Zatvaranje") == true)
                {
                    if (MessageBox.Show("Vec postoji glana knjiga zelite li je brisati ?", "", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                    {
                        sql = "Delete from GlavnaKnjiga where ID_DokumentaView =@param0";
                        ret = db.ParamsInsertScalar(sql, iddokument);
                    }
                }
            }

            if (forma.Controls.OfType <Field>().FirstOrDefault(n => n.IME == "Proknjizeno").Vrednost.Contains("MalaSalda") == true)
            {
                IznosZaOtpis = Prompt.ShowDialog("", "Unesite iznos za otpis ", " Otpis malih salda ");
                clsOperacije co = new clsOperacije();
                bool         r  = co.IsNumeric(IznosZaOtpis);
                if (r == false)
                {
                    MessageBox.Show("Pogresno unesen iznos ponovite !!!"); return(ProveraIspravnosti);
                }

                KontoPrihoda = Prompt.ShowDialog("", "Unesite konto za prihod ", " Otpis malih salda ").Trim();
                if (KontoPrihoda.Substring(1, 1) != "6")
                {
                    MessageBox.Show("Pogresno unesen konto prihoda !!!"); return(ProveraIspravnosti);
                }

                KontoTroskova = Prompt.ShowDialog("", "Unesite konto za troskove ", " Otpis malih salda ").Trim();
                if (KontoPrihoda.Substring(1, 1) != "5")
                {
                    MessageBox.Show("Pogresno unesen konto troskova !!!"); return(ProveraIspravnosti);
                }

                sql = "Delete from GlavnaKnjiga where ID_DokumentaView =@param0";
                ret = db.ParamsInsertScalar(sql, iddokument);
            }


            if (forma.Controls.OfType <Field>().FirstOrDefault(n => n.IME == "Proknjizeno").Vrednost.Contains("Otvaranje") == true)
            {
                if (forma.Controls.OfType <Field>().FirstOrDefault(n => n.IME == "Predhodni").Vrednost == "1")
                {
                    MessageBox.Show("Niste odabrali  prethodnika !!!");
                    return(ProveraIspravnosti);
                }

                sql = "Select Proknjizeno from Dokumenta where ID_Dokumenta =@param0";
                t   = db.ParamsQueryDT(sql, forma.Controls.OfType <Field>().FirstOrDefault(n => n.IME == "Predhodni").ID);
                if (t.Rows.Count > 0)
                {
                    if (t.Rows[0]["Proknjizeno"].ToString().Contains("Zatvaranje") == false)
                    {
                        MessageBox.Show("Niste odabrali zatvaranje kao prethodnika otvaranju!!!");
                        return(ProveraIspravnosti);
                    }
                }
            }

            ProveraIspravnosti = true;
            return(ProveraIspravnosti);
        }
Ejemplo n.º 43
0
 void Start()
 {
     foreach (var type in Enum.GetValues(typeof(ResourceType))) {
     var obj = GameObject.Find(type.ToString() + "Text");
     if (obj != null)
         resourceTexts[(int)type] = obj.GetComponent<Text>();
     }
     // Find ALL the buttons!
     refineButtons = GameObject.Find("RefineButtons");
     refineButtons.SetActive(false);
     stopRefineButtons = GameObject.Find("StopRefineButtons");
     stopRefineButtons.SetActive(false);
     hiveButtonsRoot = GameObject.Find("HiveButtons");
     hiveButtonsRoot.SetActive(false);
     queenButtonsRoot = GameObject.Find("QueenButtons");
     queenButtonsRoot.SetActive(false);
     larvaButtonsRoot = GameObject.Find("LarvaButtons");
     larvaButtonsRoot.SetActive(false);
     bpText = GameObject.Find("BPText");
     bpText.SetActive(false);
     TooltipPanel = GameObject.Find("TooltipPanel");
     specButtonsRoot = GameObject.Find("SpecializationButtons");
     specButtonsRoot.SetActive(false);
     MsgPrompt = GameObject.Find("MessagePrompt").GetComponent<Prompt>();
     MsgPrompt.gameObject.SetActive(false);
     // Subscribe to ResourceManager's events
     if (resourceManager == null) {
     var rm = GameObject.Find("ResourceManager");
     resourceManager = rm.GetComponent<ResourceManager>();
     }
     resourceManager.OnResourceChange += updateResources;
     updateResources();
 }
Ejemplo n.º 44
0
        private static void RunInputSample()
        {
            var name = Prompt.Input <string>("What's your name?", validators: new[] { Validators.Required() });

            Console.WriteLine($"Hello, {name}!");
        }
        private bool speechkitInitialize()
        {
            try
            {
                AppInfo.SpeechKitServer = textBoxServerIp.Text;
                AppInfo.SpeechKitPort = Convert.ToInt32(textBoxServerPort.Text);
            }
            catch (FormatException e)
            {
                MessageBox.Show("Port must be a number");

                return false;
            }

            try
            {
                _speechKit = SpeechKit.initialize(AppInfo.SpeechKitAppId, AppInfo.SpeechKitServer, AppInfo.SpeechKitPort, AppInfo.SpeechKitSsl, AppInfo.SpeechKitApplicationKey);
            }
            catch (Exception e)
            {
                MessageBox.Show(e.Message);

                return false;
            }

            _beep = _speechKit.defineAudioPrompt("beep.wav");
            _speechKit.setDefaultRecognizerPrompts(_beep, null, null, null);
            _speechKit.connect();
            Thread.Sleep(10); // to guarantee the time to load prompt resource

            return true;
        }
Ejemplo n.º 46
0
        void Core_Insert(Background insert)
        {
            Core.SuspendUpdate();
            try
            {
                bool compressed = (CurrentType == BackgroundType.Battle);

                byte[] data_palette = Palette.Merge(insert.Palettes).ToBytes(compressed);
                byte[] data_tileset = insert.Graphics.ToBytes(false); // is compressed below
                byte[] data_tsa     = insert.Tiling.ToBytes(compressed, !compressed);

                var repoints = new List <Tuple <string, Pointer, int> >();
                var writepos = new List <Pointer>();

                List <byte[]> strips = new List <byte[]>();
                if (CurrentType == BackgroundType.Screen &&
                    (Core.CurrentROM is FE8 ||
                     (Core.CurrentROM is FE7 &&
                      Core.CurrentROM.Version != GameVersion.JAP &&
                      (byte)Current["Strips"] == 0x01)))
                {
                    byte[] buffer = new byte[32 * 2 * GBA.Tile.LENGTH];
                    for (int i = 0; i < 10; i++)
                    {
                        Array.Copy(data_tileset, i * buffer.Length, buffer, 0, Math.Min(data_tileset.Length - i * buffer.Length, buffer.Length));
                        strips.Add(LZ77.Compress(buffer));

                        repoints.Add(Tuple.Create("Tileset " + i, Core.ReadPointer((Pointer)Current["Tileset"] + i * 4), strips[i].Length));
                        writepos.Add(Current.GetAddress(Current.EntryIndex, "Tileset") + i * 4);
                    }
                }
                else
                {
                    data_tileset = LZ77.Compress(data_tileset);

                    repoints.Add(Tuple.Create("Tileset", (Pointer)Current["Tileset"], data_tileset.Length));
                    writepos.Add(Current.GetAddress(Current.EntryIndex, "Tileset"));
                }
                repoints.Add(Tuple.Create("Palette", (Pointer)Current["Palette"], data_palette.Length));
                writepos.Add(Current.GetAddress(Current.EntryIndex, "Palette"));

                repoints.Add(Tuple.Create("TSA", (Pointer)Current["TSA"], data_tsa.Length));
                writepos.Add(Current.GetAddress(Current.EntryIndex, "TSA"));

                bool cancel = Prompt.ShowRepointDialog(this, "Repoint Background",
                                                       "The background to insert may need some of its parts to be repointed.",
                                                       CurrentEntry, repoints.ToArray(), writepos.ToArray());
                if (cancel)
                {
                    return;
                }

                if (CurrentType == BackgroundType.Screen && (Core.CurrentROM is FE8 ||
                                                             (Core.CurrentROM is FE7 && Core.ReadByte(Current.Address) == 0x01)))
                {
                    for (int i = 0; i < 10; i++)
                    {
                        Core.WriteData(this,
                                       Core.ReadPointer((Pointer)Current["Tileset"] + i * 4),
                                       strips[i],
                                       CurrentEntry + "Tileset " + i + " changed");
                    }
                }   // write graphics in 32x2 strips
                else
                {
                    Core.WriteData(this,
                                   (Pointer)Current["Tileset"],
                                   data_tileset,
                                   CurrentEntry + "Tileset changed");
                }

                Core.WriteData(this,
                               (Pointer)Current["Palette"],
                               data_palette,
                               CurrentEntry + "Palette changed");

                Core.WriteData(this,
                               (Pointer)Current["TSA"],
                               data_tsa,
                               CurrentEntry + "TSA changed");
            }
            catch (Exception ex)
            {
                Program.ShowError("Could not insert the background.", ex);
            }
            Core.ResumeUpdate();
            Core.PerformUpdate();
        }
Ejemplo n.º 47
0
		public void Setup()
		{
			_prompt = new Prompt();
		}
Ejemplo n.º 48
0
        private static void RunPasswordSample()
        {
            var secret = Prompt.Password("Type new password", new[] { Validators.Required(), Validators.MinLength(8) });

            Console.WriteLine("Password OK");
        }
Ejemplo n.º 49
0
		public void Dispose_HasDisposedEventHandler_CallsHandler()
		{
			Prompt prompt = new Prompt();
			bool disposedCalled = false;
			prompt.Disposed += delegate { disposedCalled = true; };
			Assert.IsFalse(disposedCalled);
			prompt.Dispose();
			Assert.IsTrue(disposedCalled);
		}
Ejemplo n.º 50
0
        private static void RunConfirmSample()
        {
            var answer = Prompt.Confirm("Are you ready?");

            Console.WriteLine($"Your answer is {answer}");
        }
Ejemplo n.º 51
0
		public void GetIsPromptVisible_CalledAfterDisposed_Throws()
		{
			var prompt = new Prompt();
			prompt.Dispose();
			using (var textBox = new TextBox())
			{
				Assert.Throws<ObjectDisposedException>(
					() => prompt.GetIsPromptVisible(textBox)
				);
			}
		}
Ejemplo n.º 52
0
        private static void RunMultiSelectSample()
        {
            var options = Prompt.MultiSelect("Which cities would you like to visit?", new[] { "Seattle", "London", "Tokyo", "New York", "Singapore", "Shanghai" }, pageSize: 3);

            Console.WriteLine($"You picked {string.Join(", ", options)}");
        }
Ejemplo n.º 53
0
		public void SetSite_CalledAfterDisposed_Throws()
		{
			var prompt = new Prompt();
			prompt.Dispose();
			Assert.Throws<ObjectDisposedException>(
				() => prompt.Site = null
			);
		}
Ejemplo n.º 54
0
        private static void RunSelectEnumSample()
        {
            var value = Prompt.Select <MyEnum>("Select enum value");

            Console.WriteLine($"You selected {value}");
        }
Ejemplo n.º 55
0
        private async System.Threading.Tasks.Task OnExecuteAsync()
        {
            if (!this.MigrateSubs && !this.DeleteAllPostsAndComments && !this.MigrateSaved)
            {
                Console.WriteLine("Please specify a flag. See --help.");
                return;
            }

            if (this.MigrateSubs)
            {
                Console.WriteLine("I will migrate your subreddits.");
            }

            if (this.MigrateSaved)
            {
                Console.WriteLine("I will migrate your saved items.");
            }

            if (this.DeleteAllPostsAndComments)
            {
                Console.WriteLine("I will delete all DESTINATION USER comments and posts.");
            }

            if (!Yes)
            {
                var result = Prompt.GetYesNo("Do you want to proceed?", false);
                if (!result)
                {
                    return;
                }
            }


            Console.WriteLine($"Attempting login for {TargetUsername}");
            var targetRedditAgent = new BotWebAgent(TargetUsername, TargetPassword, clientid, clientsecret, redirecturi);
            var targetReddit      = new Reddit(targetRedditAgent, initUser: true);

            Console.WriteLine($"Success.");

            Console.WriteLine($"Attempting login for {DestUsername}");
            var destinationRedditAgent = new BotWebAgent(DestUsername, DestPassword, clientid, clientsecret, redirecturi);
            var destinationReddit      = new Reddit(destinationRedditAgent, initUser: true);

            Console.WriteLine($"Success.");

            if (MigrateSubs)
            {
                Console.WriteLine($"Starting subreddit migration.");

                await targetReddit.User.GetSubscribedSubreddits().ForEachAsync(async(subreddit, index) => {
                    try
                    {
                        Console.WriteLine($"({index}) - Fetching {subreddit.Name}.");
                        var subredditToResubscribe = await destinationReddit.GetSubredditAsync(subreddit.Name, validateName: false);
                        await subredditToResubscribe.SubscribeAsync();
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine($"Failed to fetch {subreddit}. Skipping subscription.");
                        Log(Verbose, ex.Message);
                    }
                });
            }
            else
            {
                Console.WriteLine("Skipping subreddit migration. Use --migratesubs");
            }

            if (DeleteAllPostsAndComments)
            {
                await destinationReddit.User.GetComments(limit : 100).ForEachAsync(async(comment, index) =>
                {
                    try
                    {
                        Console.WriteLine($"({index}) - Deleting comment {comment.Id}.");
                        await comment.DelAsync();
                    } catch (Exception ex)
                    {
                        Console.WriteLine($"Failed to fetch {comment.Id}. Skipping comment.");
                        Log(Verbose, ex.Message);
                    }
                });

                await destinationReddit.User.GetPosts(limit : 100).ForEachAsync(async(post, index) =>
                {
                    try
                    {
                        Console.WriteLine($"({index}) - Deleting post {post.Id}.");
                        await post.DelAsync();
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine($"Failed to fetch {post.Id}. Skipping post.");
                        Log(Verbose, ex.Message);
                    }
                });
            }
            else
            {
                Console.WriteLine("Skipping delete all posts and comments. Use --deleteallpostsandcomments");
            }

            if (MigrateSaved)
            {
                Console.WriteLine("Migrating saved.");

                await targetReddit.User.GetSaved().ForEachAsync(async(thing, index) =>
                {
                    try
                    {
                        Console.WriteLine($"({index}) - Getting saved thing {thing.Id}.");
                        var savedThingDest = await destinationReddit.GetThingByFullnameAsync(thing.FullName);
                        if (savedThingDest is not null)
                        {
                            switch (savedThingDest)
                            {
                            case Comment:
                                await((Comment)savedThingDest).SaveAsync();
                                break;

                            case Post:
                                await((Post)savedThingDest).SaveAsync();
                                break;

                            default:
                                throw new NotImplementedException("Unsupported saved thing.");
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine($"Failed to fetch {thing.Id}. Skipping comment.");
                        Log(Verbose, ex.Message);
                    }
                });
            }
            else
            {
                Console.WriteLine("Skipping migrating saved posts. Use --migratesaved");
            }

            Console.WriteLine("Done!");
        }
Ejemplo n.º 56
0
 public void CalibrateCompiler(Prompt p, IReport ReportGenerator, HttpObject HttpHandler)
 {
     this.ReportGenerator = ReportGenerator;
     this.HttpHandler     = HttpHandler;
     System.Console.WriteLine(p.Destination);
 }
 public void Say(string input)
 {
     var synth = new SpeechSynthesizer();
     var sayThis = new Prompt(input);
     synth.Speak(sayThis);
 }
Ejemplo n.º 58
0
        private bool GenerateSiteProvisioningFile(List <Brand> brands, string outputDirectory)
        {
            string siteFilename = Path.Combine(outputDirectory, $"{OutputFilePrefix}_Site_Provisioning.yaml");

            if (File.Exists(siteFilename))
            {
                var overwrite = Prompt.GetYesNo("A site provisioning file already exists," +
                                                " would you like to overwrite it and any brand provisioning" +
                                                $" files that already exist? ({siteFilename})", false);
                if (!overwrite)
                {
                    return(false);
                }
            }

            var p = new ProvisioningDescription();

            p.AddEndpoint(new EndpointDescription {
                type = "EventHub", eventTypes = new List <string> {
                    "DeviceMessage"
                }
            });
            var tenantSpace = new SpaceDescription
            {
                name         = "SmartHotel 360 Tenant",
                description  = "This is the root node for the SmartHotel360 IoT Demo",
                friendlyName = "SmartHotel 360 Tenant",
                type         = "Tenant",
                keystoreName = "SmartHotel360 Keystore"
            };
            SpaceDescription desiredTenantSpace = tenantSpace;

            p.AddSpace(tenantSpace);

            if (!string.IsNullOrWhiteSpace(SubTenantName))
            {
                var subtenantSpace = new SpaceDescription
                {
                    name         = SubTenantName,
                    description  = $"This is the root node for the {SubTenantName} sub Tenant",
                    friendlyName = SubTenantName,
                    type         = "Tenant"
                };
                tenantSpace.AddSpace(subtenantSpace);
                desiredTenantSpace = subtenantSpace;
            }
            else
            {
                tenantSpace.AddResource(new ResourceDescription {
                    type = "IoTHub"
                });
            }

            desiredTenantSpace.AddType(new TypeDescription {
                name = "Classic", category = "SensorType"
            });
            desiredTenantSpace.AddType(new TypeDescription {
                name = "HotelBrand", category = "SpaceType"
            });
            desiredTenantSpace.AddType(new TypeDescription {
                name = "Hotel", category = "SpaceType"
            });
            desiredTenantSpace.AddType(new TypeDescription {
                name = "VIPFloor", category = "SpaceSubType"
            });
            desiredTenantSpace.AddType(new TypeDescription {
                name = "QueenRoom", category = "SpaceSubType"
            });
            desiredTenantSpace.AddType(new TypeDescription {
                name = "KingRoom", category = "SpaceSubType"
            });
            desiredTenantSpace.AddType(new TypeDescription {
                name = "SuiteRoom", category = "SpaceSubType"
            });
            desiredTenantSpace.AddType(new TypeDescription {
                name = "VIPSuiteRoom", category = "SpaceSubType"
            });
            desiredTenantSpace.AddType(new TypeDescription {
                name = "ConferenceRoom", category = "SpaceSubType"
            });
            desiredTenantSpace.AddType(new TypeDescription {
                name = "GymRoom", category = "SpaceSubType"
            });
            desiredTenantSpace.AddType(new TypeDescription {
                name = BlobDescription.FloorplanFileBlobSubType, category = "SpaceBlobSubType"
            });

            desiredTenantSpace.AddPropertyKey(new PropertyKeyDescription
            {
                name = PropertyKeyDescription.DeviceIdPrefixName,
                primitiveDataType = PropertyKeyDescription.PrimitiveDataType.String,
                description       = "Prefix used in sending Device Method calls to the IoT Hub."
            });
            desiredTenantSpace.AddPropertyKey(new PropertyKeyDescription
            {
                name = PropertyKeyDescription.DisplayOrder,
                primitiveDataType = PropertyKeyDescription.PrimitiveDataType.UInt,
                description       = "Order to display spaces"
            });
            desiredTenantSpace.AddPropertyKey(new PropertyKeyDescription
            {
                name = PropertyKeyDescription.MinTemperatureAlertThreshold,
                primitiveDataType = PropertyKeyDescription.PrimitiveDataType.Int,
                description       = "Alert if the temperature goes below this value."
            });
            desiredTenantSpace.AddPropertyKey(new PropertyKeyDescription
            {
                name = PropertyKeyDescription.MaxTemperatureAlertThreshold,
                primitiveDataType = PropertyKeyDescription.PrimitiveDataType.Int,
                description       = "Alert if the temperature goes above this value."
            });
            desiredTenantSpace.AddPropertyKey(new PropertyKeyDescription
            {
                name = PropertyKeyDescription.ImagePath,
                primitiveDataType = PropertyKeyDescription.PrimitiveDataType.String,
                description       = "Path of the image to display for the space."
            });
            desiredTenantSpace.AddPropertyKey(new PropertyKeyDescription
            {
                name = PropertyKeyDescription.ImageBlobId,
                primitiveDataType = PropertyKeyDescription.PrimitiveDataType.String,
                description       = "Id of the image blob for the space."
            });
            desiredTenantSpace.AddPropertyKey(new PropertyKeyDescription
            {
                name = PropertyKeyDescription.DetailedImagePath,
                primitiveDataType = PropertyKeyDescription.PrimitiveDataType.String,
                description       = "Path of the detailed image to display for the space."
            });
            desiredTenantSpace.AddPropertyKey(new PropertyKeyDescription
            {
                name = PropertyKeyDescription.DetailedImageBlobId,
                primitiveDataType = PropertyKeyDescription.PrimitiveDataType.String,
                description       = "Id of the detailed image blob for the space."
            });
            desiredTenantSpace.AddPropertyKey(new PropertyKeyDescription
            {
                name = PropertyKeyDescription.Latitude,
                primitiveDataType = PropertyKeyDescription.PrimitiveDataType.String,
                description       = "Geo Position"
            });
            desiredTenantSpace.AddPropertyKey(new PropertyKeyDescription
            {
                name = PropertyKeyDescription.Longitude,
                primitiveDataType = PropertyKeyDescription.PrimitiveDataType.String,
                description       = "Geo Position"
            });

            desiredTenantSpace.AddUser("Head Of Operations");

            var matcherTemperature = new MatcherDescription {
                name = "Matcher Temperature", dataTypeValue = "Temperature"
            };

            desiredTenantSpace.AddMatcher(matcherTemperature);
            var temperatureProcessor = new UserDefinedFunctionDescription
            {
                name         = "Temperature Processor",
                matcherNames = new List <string>(),
                script       = "../UserDefinedFunctions/temperatureThresholdAlert.js"
            };

            temperatureProcessor.matcherNames.Add(matcherTemperature.name);
            desiredTenantSpace.AddUserDefinedFunction(temperatureProcessor);

            desiredTenantSpace.AddRoleAssignment(new RoleAssignmentDescription
            {
                roleId       = RoleAssignment.RoleIds.SpaceAdmin,
                objectName   = temperatureProcessor.name,
                objectIdType = RoleAssignment.ObjectIdTypes.UserDefinedFunctionId
            });

            foreach (Brand brand in brands)
            {
                string brandFilename = GetBrandProvisioningFilename(brand);
                desiredTenantSpace.AddSpaceReference(new SpaceReferenceDescription {
                    filename = brandFilename
                });
            }

            var    yamlSerializer = new Serializer();
            string serializedProvisioningDescription = yamlSerializer.Serialize(p);

            File.WriteAllText(siteFilename, serializedProvisioningDescription);

            Console.WriteLine($"Successfully created site provisioning file: {siteFilename}");

            return(true);
        }
Ejemplo n.º 59
0
        private static void RunSelectSample()
        {
            var city = Prompt.Select("Select your city", new[] { "Seattle", "London", "Tokyo", "New York", "Singapore", "Shanghai" }, pageSize: 3);

            Console.WriteLine($"Hello, {city}!");
        }
Ejemplo n.º 60
0
        /// <summary>
        /// Reset button click event or Login Id/SecurityAnswer Enter Press event implementation - validate errors, navigate to notification screen
        /// </summary>
        /// <param name="param"></param>
        private void ResetCommandMethod(object param)
        {
            try
            {
                if (_manageLogins != null)
                {
                    if (ErrorValidation())
                    {
                        #region GetUser Service Call
                        _manageLogins.GetUser(LoginIdText, false, (membershipUser) =>
                        {
                            string methodNamespace = String.Format("{0}.{1}", GetType().FullName, System.Reflection.MethodInfo.GetCurrentMethod().Name);
                            Logging.LogLoginBeginMethod(_logger, methodNamespace, LoginIdText);

                            try
                            {
                                if (membershipUser != null)
                                {
                                    Logging.LogLoginMethodParameter(_logger, methodNamespace, membershipUser, 1, _loginIdText);

                                    #region ResetPassword Service Call
                                    _manageLogins.ResetPassword(LoginIdText, SecurityAnswerText, (password) =>
                                    {
                                        string resetMethodNamespace = String.Format("{0}.{1}", GetType().FullName, System.Reflection.MethodInfo.GetCurrentMethod().Name);
                                        Logging.LogLoginBeginMethod(_logger, resetMethodNamespace, LoginIdText);

                                        try
                                        {
                                            if (password != null)
                                            {
                                                Logging.LogLoginMethodParameter(_logger, resetMethodNamespace, password, 1, _loginIdText);
                                                Logging.LogAccountPasswordReset(_logger, LoginIdText);
                                                Prompt.ShowDialog(password); // Password displayed as messagebox, to be sent as email alert later
                                                ResourceManager NotificationManager = new ResourceManager(typeof(Notifications));
                                                NotificationText = NotificationManager.GetString("PasswordResetNotification").Replace("[LoginId]", LoginIdText);

                                                _regionManager.RequestNavigate(RegionNames.MAIN_REGION, new Uri("ViewNotifications", UriKind.Relative));
                                            }
                                            else
                                            {
                                                Logging.LogLoginMethodParameterNull(_logger, resetMethodNamespace, 1, LoginIdText);
                                                SecurityAnswerState = FieldState.InvalidField;
                                            }
                                        }
                                        catch (Exception ex)
                                        {
                                            Prompt.ShowDialog("Message: " + ex.Message + "\nStackTrace: " + Logging.StackTraceToString(ex), "Exception", MessageBoxButton.OK);
                                            Logging.LogLoginException(_logger, ex);
                                        }

                                        Logging.LogLoginEndMethod(_logger, resetMethodNamespace, LoginIdText);
                                    });
                                    #endregion
                                }
                                else
                                {
                                    Logging.LogLoginMethodParameterNull(_logger, methodNamespace, 1, LoginIdText);
                                    LoginIdState = FieldState.InvalidField;
                                }
                            }
                            catch (Exception ex)
                            {
                                Prompt.ShowDialog("Message: " + ex.Message + "\nStackTrace: " + Logging.StackTraceToString(ex), "Exception", MessageBoxButton.OK);
                                Logging.LogLoginException(_logger, ex);
                            }

                            Logging.LogLoginEndMethod(_logger, methodNamespace, LoginIdText);
                        });
                        #endregion
                    }
                }
            }
            catch (Exception ex)
            {
                Prompt.ShowDialog("Message: " + ex.Message + "\nStackTrace: " + Logging.StackTraceToString(ex), "Exception", MessageBoxButton.OK);
                Logging.LogLoginException(_logger, ex);
            }
        }