// Function for converting text to a voiced wav file via text-to-speech
    public bool TextToWav(string FilePath, string text)
    {
        //VA.WriteToLog("creating wav file"); // Output info to event log
        SpFileStream stream = new SpFileStream();                                 // Create new SpFileStream instance

        try                                                                       // Attempt the following code
        {
            if (System.IO.File.Exists(FilePath) == true)                          // Check if voice recognition wav file already exists
            {
                System.IO.File.Delete(FilePath);                                  // Delete existing voice recognition wav file
            }
            stream.Format.Type = SpeechAudioFormatType.SAFT48kHz16BitStereo;      // Set the file stream audio format
            stream.Open(FilePath, SpeechStreamFileMode.SSFMCreateForWrite, true); // Open the specified file for writing with events enabled
            SpVoice voice = new SpVoice();                                        // Create new SPVoice instance
            voice.Volume = 100;                                                   // Set the volume level of the text-to-speech voice
            voice.Rate   = -2;                                                    // Set the rate at which text is spoken by the text-to-speech engine
            string NameAttribute = "Name = " + VA.GetText("~~TextToSpeechVoice");
            voice.Voice = voice.GetVoices(NameAttribute).Item(0);
            //voice.Speak(text);
            voice.AudioOutputStream = stream;                                          // Send the audio output to the file stream
            voice.Speak(text, SpeechVoiceSpeakFlags.SVSFDefault);                      // Internally "speak" the inputted text (which records it in the wav file)
            voice = null;                                                              // Set to null in preparation for garbage collection
        }
        catch                                                                          // Handle exceptions in above code
        {
            VA.SetText("~~RecognitionError", "Error during wav file creation (SAPI)"); // Send error detail back to VoiceAttack as text variable
            return(false);                                                             // Send "false" back to calling code line
        }
        finally                                                                        // Runs whether an exception is encountered or not
        {
            stream.Close();                                                            // Close the file stream
            stream = null;                                                             // Set to null in preparation for garbage collection
        }
        return(true);                                                                  // Send "true" back to calling code line
    }
    // Function for processing voice recognition results
    public void RecognitionProcessing(ISpeechRecoResult Result)
    {
        //VA.WriteToLog("Processing recognition result"); // Output info to event log

        try                                                                                                                 // Attempt the following code
        {
            string  RecognizedText             = Result.PhraseInfo.GetText().Trim();                                        // Store recognized text
            float   confidence                 = Result.PhraseInfo.Elements.Item(0).EngineConfidence;                       // Get confidence of voice recognition result
            decimal RecognitionConfidenceScore = Decimal.Round(Convert.ToDecimal(confidence), (confidence > 0.01 ? 3 : 4)); // Calculate confidence of voice recognition result convert to decimal, and round the result
            string  RecognitionConfidenceLevel = Result.PhraseInfo.Elements.Item(0).ActualConfidence.ToString().Replace("SEC", "").Replace("Confidence", "");
            VA.SetText("~~RecognizedText", RecognizedText);                                                                 // Send recognized text back to VoiceAttack as text variable
            //VA.SetText("~~RecognitionConfidenceLevel", RecognitionConfidenceLevel); // Send speech recognition confidence level back to VoiceAttack as text variable
            //VA.SetDecimal("~~RecognitionConfidence", RecognitionConfidenceScore); // Send recognized confidence back to VoiceAttack as decimal variable

            if (VA.GetBoolean("~~ShowConfidence") == true)
            {
                RecognitionConfidence = "(" + RecognitionConfidenceLevel + " @ " + RecognitionConfidenceScore.ToString() + ")" + RecognitionFlag;
            }
            //VA.SetText("~~RecognitionConfidence", RecognitionConfidenceLevel + " @ " + RecognitionConfidenceScore.ToString()); // Send speech recognition confidence data back to VoiceAttack as text variable
            VA.SetText("~~RecognitionConfidence", RecognitionConfidence); // Send formatted speech recognition confidence data back to VoiceAttack as text variable
            if (UseDictation == true)                                     // Check if pronunciation dictation grammar should be used with speech recognition
            {
                RecognizedText = RecognizedText.Replace("hh", "h");       // Replace any instances of "hh" in recognized phonemes with "h"
                VA.SetText("~~SAPIPhonemes", RecognizedText);             // Send word-delimited SAPI phoneme data back to VoiceAttack as text variable
            }
        }
        catch (Exception e)         // Handle exceptions in above code
        {
            VA.WriteToLog(e.ToString());
            VA.SetText("~~RecognitionError", "Error during processing of recognition result (SAPI)");             // Send error detail back to VoiceAttack as text variable
        }
    }
    // Event handler for reaching the end of an audio input stream
    public void RecoContext_EndStream(int StreamNumber, object StreamPosition, bool StreamReleased)
    {
        // VA.WriteToLog("End of stream, cleaning up now"); // Output info to event log

        // Clean up now that voice recognition is complete
        try         // Attempt the following code
        {
            if (UseDictation == true)
            {
                grammar.DictationSetState(SpeechRuleState.SGDSInactive);                 // Deactivate dictation grammar
            }
            else
            {
                grammar.CmdSetRuleIdState(0, SpeechRuleState.SGDSInactive);                 // Deactivate the loaded grammar
            }
        }
        catch                                                                        // Handle exceptions in above code
        {
            VA.SetText("~~RecognitionError", "Error during cleanup process (SAPI)"); // Send error detail back to VoiceAttack as text variable
        }
        finally                                                                      // Runs whether an exception is encountered or not
        {
            Application.ExitThread();                                                // Terminates the message loop on the current thread
        }
    }
Exemple #4
0
        public void PushDataTo(CycleDataSet cycleDataSet)
        {
            CycleData cycleData;

            Cycle[]          cycles;
            CycleDataGroup[] cycleDataGroups;

            cycleDataGroups = new CycleDataGroup[] { VA, VB, VC, IA, IB, IC };
            cycles          = new Cycle[cycleDataGroups.Length];

            for (int i = 0; i < VA.ToDataGroup().Samples; i++)
            {
                cycleData = new CycleData();

                cycles[0] = cycleData.AN.V;
                cycles[1] = cycleData.BN.V;
                cycles[2] = cycleData.CN.V;
                cycles[3] = cycleData.AN.I;
                cycles[4] = cycleData.BN.I;
                cycles[5] = cycleData.CN.I;

                for (int j = 0; j < cycles.Length; j++)
                {
                    cycles[j].RMS   = cycleDataGroups[j].RMS[i].Value;
                    cycles[j].Phase = cycleDataGroups[j].Phase[i].Value;
                    cycles[j].Peak  = cycleDataGroups[j].Peak[i].Value;
                    cycles[j].Error = cycleDataGroups[j].Error[i].Value;
                }

                cycleDataSet[i] = cycleData;
            }
        }
    // Function for extracting SAPI phonemes from voice recognition results
    public void GetPhonemes(ISpeechRecoResult Result)
    {
        //VA.WriteToLog("Extracting phonemes from voice recognition result"); // Output info to event log

        try                                                                       // Attempt the following code
        {
            SpPhoneConverter MyPhoneConverter = new SpPhoneConverter();           // Create new SPPhoneConverter instance
            MyPhoneConverter.LanguageId = 1033;                                   // Set the phone converter's language (English = 1033)
            string SAPIPhonemesRaw = null;                                        // Initialize string for storing raw SAPI phoneme data
            string SAPIPhonemes    = null;                                        // Initialize string for storing delimited SAPI phoneme data
            int    i             = 1;                                             // Initialize integer for tracking phoneme count
            string WordSeparator = " ";                                           // Initialize string variable for storing the characters used to separate words within the phoneme result

            if (VA.GetBoolean("~~SeparatePhonemes") == true)                      // Check if user wants to have the "-" character separate the words within the phoneme result
            {
                WordSeparator = " - ";                                            // Redefine the WordSeparator
            }
            foreach (ISpeechPhraseElement MyPhrase in Result.PhraseInfo.Elements) // Loop through each element of the recognized text
            {
                if (MyPhrase.DisplayText != " ")
                {
                    SAPIPhonemesRaw += " " + MyPhoneConverter.IdToPhone(MyPhrase.Pronunciation);                             // Build string of SAPI phonemes extracted from the recognized text
                    SAPIPhonemes    += (i++ > 1 ? WordSeparator : " ") + MyPhoneConverter.IdToPhone(MyPhrase.Pronunciation); // Build string of SAPI phonemes extracted from the recognized text, delimited by " "
                }
            }
            MyPhoneConverter = null;                                             // Set to null in preparation for garbage collection

            VA.SetText("~~SAPIPhonemesRaw", SAPIPhonemesRaw.Trim());             // Send raw SAPI phoneme data back to VoiceAttack as text variable
            VA.SetText("~~SAPIPhonemes", SAPIPhonemes.Trim());                   // Send word-delimited SAPI phoneme data back to VoiceAttack as text variable
        }
        catch                                                                    // Handle exceptions in above code
        {
            VA.SetText("~~RecognitionError", "Error during phoneme extraction"); // Send error detail back to VoiceAttack as text variable
        }
    }
Exemple #6
0
        override public bool Intersect(Ray ray, out float distance)
        {
            V3 centerDirection = Center - ray.Origin;

            V3    n = Normal();
            float t = (centerDirection * n) / (ray.Direction * n);

            if (t > DIST_THRES)
            {
                distance = t;

                V3 collisionPoint = ray.Origin + (ray.Direction * distance);
                V3 cornerPoint    = Center - VB / 2 - VA / 2;

                V3 v = collisionPoint - cornerPoint;

                bool inRectangle = (VA * v >= 0) &&
                                   (VA * v <= VA.Norm2()) &&
                                   (VB * v >= 0) &&
                                   (VB * v <= VB.Norm2());

                return(inRectangle);
            }

            distance = float.MaxValue;
            return(false);
        }
Exemple #7
0
 /// <summary>
 /// Constructor
 /// </summary>
 /// <param name="vo">The offset of the sine wave</param>
 /// <param name="va">The amplitude of the sine wave</param>
 /// <param name="freq">The frequency in Hz</param>
 /// <param name="td">The delay in seconds</param>
 /// <param name="theta">The damping factor</param>
 public Sine(double vo, double va, double freq, double td = 0.0, double theta = 0.0) : base("SINE")
 {
     VO.Set(vo);
     VA.Set(va);
     Freq.Set(freq);
     Delay.Set(td);
     Theta.Set(theta);
 }
    // Event handler for voice recognition hypotheses
    public void RecoContext_Hypothesis(int StreamNumber, object StreamPosition, ISpeechRecoResult Result)
    {
        //VA.WriteToLog("Recognition hypothesis"); // Output info to event log

        float confidence = Result.PhraseInfo.Elements.Item(0).EngineConfidence;

        VA.WriteToLog("Hypothesis = " + Result.PhraseInfo.GetText() + " (" + Decimal.Round(Convert.ToDecimal(confidence), (confidence > 0.01 ? 3 : 4)) + ")");         // Output info to event log
    }
Exemple #9
0
 /// <summary>
 /// Constructor
 /// </summary>
 /// <param name="vo">The offset of the sine wave</param>
 /// <param name="va">The amplitude of the sine wave</param>
 /// <param name="freq">The frequency in Hz</param>
 /// <param name="td">The delay in seconds</param>
 /// <param name="theta">The damping factor</param>
 public Sine(double vo, double va, double freq, double td = double.NaN, double theta = double.NaN) : base()
 {
     VO.Set(vo);
     VA.Set(va);
     Freq.Set(freq);
     if (!double.IsNaN(td))
     {
         Delay.Set(td);
     }
     if (!double.IsNaN(theta))
     {
         Theta.Set(theta);
     }
 }
Exemple #10
0
 public void main()
 {
     Console.WriteLine("Making API Call...");
     using (var client = new HttpClient(new HttpClientHandler {
         AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate
     }))
     {
         client.BaseAddress = new Uri("http://127.0.0.1:5000/play/" + VA.GetText("SongUri"));
         HttpResponseMessage response = client.GetAsync("").Result;
         response.EnsureSuccessStatusCode();
         string result = response.Content.ReadAsStringAsync().Result;
         Console.WriteLine("Result: " + result);
     }
     Console.ReadLine();
 }
Exemple #11
0
        public void CalculateMissingLLVoltageChannels()
        {
            Meter      meter;
            DataSeries missingSeries;

            // If all line voltages are already present or there are not
            // atleast 2 lines we will not perform line to line calculations
            if (DefinedLineVoltages == 3 || DefinedNeutralVoltages < 2)
            {
                return;
            }

            // Get the meter associated with the channels in this data group
            meter = (VA ?? VB ?? VC).SeriesInfo.Channel.Meter;

            if (m_vabIndex == -1 && VA != null && VB != null)
            {
                // Calculate VAB = VA - VB
                missingSeries            = VA.Add(VB.Negate());
                missingSeries.SeriesInfo = GetSeriesInfo(meter, m_dataGroup, "Voltage", "AB");
                missingSeries.Calculated = true;
                m_vabIndex = m_dataGroup.DataSeries.Count;
                m_dataGroup.Add(missingSeries);
            }

            if (m_vbcIndex == -1 && VB != null && VC != null)
            {
                // Calculate VBC = VB - VC
                missingSeries            = VB.Add(VC.Negate());
                missingSeries.SeriesInfo = GetSeriesInfo(meter, m_dataGroup, "Voltage", "BC");
                missingSeries.Calculated = true;
                m_vbcIndex = m_dataGroup.DataSeries.Count;
                m_dataGroup.Add(missingSeries);
            }

            if (m_vcaIndex == -1 && VC != null && VA != null)
            {
                // Calculate VCA = VC - VA
                missingSeries            = VC.Add(VA.Negate());
                missingSeries.SeriesInfo = GetSeriesInfo(meter, m_dataGroup, "Voltage", "CA");
                missingSeries.Calculated = true;
                m_vcaIndex = m_dataGroup.DataSeries.Count;
                m_dataGroup.Add(missingSeries);
            }
        }
Exemple #12
0
        /// <summary>
        /// <para>Accepts data array of strictly 1024 values (representing Complex values where Re and Im are alternating)
        /// that will be displayed as single row of spectrum.</para>
        /// <para>X-axis is time</para>
        /// <para>Y-axis is frequency</para>
        /// </summary>
        /// <param name="data"></param>
        /// <param name="basePosition"></param>
        public override void Render(double[] data, Vector2f basePosition, int binsToRender)
        {
            if (VA.VertexCount != binsToRender)
            {
                VA.Resize((uint)binsToRender);
            }

            if (!AudioRecognitionLibrary.Tools.Arithmetics.IsPowOfTwo(data.Length))
            {
                throw new ArgumentException($"Data length: {data.Length} is not power of two.");
            }

            double Yscale = binsToRender / 512d;             //scale so spectagram fits the screen

            for (uint i = 0; i < binsToRender; i++)
            {
                var color = IntensityToColor(data[i * 2], data[i * 2 + 1], 2048);

                VA[i] = new Vertex(basePosition + new Vector2f(0, (float)(-i / Yscale)), color);
            }
        }
Exemple #13
0
        override public V2 UV(V3 p)
        {
            V3 d = p - Center;

            V3 van = new V3(VA);

            van.Normalize();

            V3 vbn = new V3(VB);

            vbn.Normalize();

            // u = ||d -> VA|| / ||VA||
            float u = ((d * van) / VA.Norm1());

            // v = ||d -> VB|| / ||VB||
            float v = ((d * vbn) / VB.Norm1());

            // u & v: [-0.5 ; 0.5] -> [0;1]
            u += 0.5f;
            v += 0.5f;

            return(new V2(u, v));
        }
Exemple #14
0
        /*============================= DrwTxt ==============================*/
        public void DrwTxt(DrawingContext dc, string text = "", double x = 0,
                           double y = 0, double size = 16, HA ha = HA.Left,
                           VA va    = VA.Top)
        {
            FormattedText ft = new FormattedText(text, CultureInfo.CurrentCulture,
                                                 FlowDirection.LeftToRight, Default.Typeface,
                                                 size, Brushes.Black);
            double xOffset = 0;

            switch (ha)
            {
            case HA.Center:
                xOffset = -ft.Width / 2;
                break;

            case HA.Right:
                xOffset = -ft.Width;
                break;
            }

            double yOffset = 0;

            switch (va)
            {
            case VA.Center:
                yOffset = -ft.Height / 2;
                break;

            case VA.Bottom:
                yOffset = -ft.Height;
                break;
            }

            dc.DrawText(ft, new Point(Math.Round(x + xOffset),
                                      Math.Round(y + yOffset)));
        }
            public ConnectionPointCells GetCells(VA.ShapeSheet.CellData<double>[] row)
            {
                var cells = new ConnectionPointCells();
                cells.X = row[this.X.Ordinal];
                cells.Y = row[this.Y.Ordinal];
                cells.DirX = row[this.DirX.Ordinal].ToInt();
                cells.DirY = row[this.DirY.Ordinal].ToInt();
                cells.Type = row[this.Type.Ordinal].ToInt();

                return cells;
            }
 public ShapeLayoutCells GetCells(VA.ShapeSheet.CellData<double>[] row)
 {
     var cells = new ShapeLayoutCells();
     cells.ConFixedCode = row[ConFixedCode.Ordinal].ToInt();
     cells.ConLineJumpCode = row[ConLineJumpCode.Ordinal].ToInt();
     cells.ConLineJumpDirX = row[ConLineJumpDirX.Ordinal].ToInt();
     cells.ConLineJumpDirY = row[ConLineJumpDirY.Ordinal].ToInt();
     cells.ConLineJumpStyle = row[ConLineJumpStyle.Ordinal].ToInt();
     cells.ConLineRouteExt = row[ConLineRouteExt.Ordinal].ToInt();
     cells.ShapeFixedCode = row[ShapeFixedCode.Ordinal].ToInt();
     cells.ShapePermeablePlace = row[ShapePermeablePlace.Ordinal].ToInt();
     cells.ShapePermeableX = row[ShapePermeableX.Ordinal].ToInt();
     cells.ShapePermeableY = row[ShapePermeableY.Ordinal].ToInt();
     cells.ShapePlaceFlip = row[ShapePlaceFlip.Ordinal].ToInt();
     cells.ShapePlaceStyle = row[ShapePlaceStyle.Ordinal].ToInt();
     cells.ShapePlowCode = row[ShapePlowCode.Ordinal].ToInt();
     cells.ShapeRouteStyle = row[ShapeRouteStyle.Ordinal].ToInt();
     cells.ShapeSplit = row[ShapeSplit.Ordinal].ToInt();
     cells.ShapeSplittable = row[ShapeSplittable.Ordinal].ToInt();
     //cells.DisplayLevel = row[DisplayLevel.Ordinal].ToInt();
     //cells.Relationships = row[Relationships.Ordinal].ToInt();
     return cells;
 }
Exemple #17
0
        public ActionResult Login(LoginInfo model)
        {
            //初始化系統參數
            Configer.Init();

            AD AD = new AD();
            VA VA = new VA();
            LoginProcessor LP = new LoginProcessor();
            bool UseCertLogin = false;
            string LDAPName = Configer.LDAPName;
            //string VAVerifyURL = WebConfigurationManager.AppSettings["VAVerifyURL"];
            //string ConnStr = Configer.C_DBConnstring;
            Boolean ContinueLogin = true;

            //Log記錄用
            SYSTEMLOG SL = new SYSTEMLOG();
            SL.UId = model.UserID;
            SL.Controller = "Account";
            SL.Action = "Login";
            SL.StartDateTime = DateTime.Now;
            SL.TotalCount = 1;

            string MailServer = Configer.MailServer;
            int MailServerPort = Configer.MailServerPort;
            string MailSender = Configer.MailSender;
            List<string> MailReceiver = Configer.MailReceiver;
            //string SendResult = string.Empty;

            if (ModelState.IsValid)
            {
                if (LDAPName == "")
                {
                    //缺少系統參數,需記錄錯誤
                    SL.EndDateTime = DateTime.Now;
                    SL.SuccessCount = 0;
                    SL.FailCount = 1;
                    SL.Msg = "登入作業失敗,錯誤訊息:[缺少系統參數LDAPName]";
                    SL.Result = false;
                    SF.log2DB(SL, MailServer, MailServerPort, MailSender, MailReceiver);
                    ContinueLogin = false;
                }
                if (ContinueLogin)
                {
                    AD.UserName = model.UserID;
                    AD.Pwd = model.Pwd;
                    AD.validType = AD.ValidType.Domain;
                    AD.LDAPName = LDAPName;

                    //VA.SignData = model.SignData;
                    //VA.Plaintext = model.Plaintext;
                    //VA.txnCode = "TxnCode";
                    //VA.VAVerifyURL = VAVerifyURL;
                    //VA.Tolerate = 120;

                    DateTime LoginStartTime = DateTime.Now;
                    SF.logandshowInfo("登入開始@" + LoginStartTime.ToString(Configer.SystemDateTimeFormat), log_Info);
                    bool LoginResult = LP.DoLogin(UseCertLogin, AD, VA);
                    DateTime LoginEndTime = DateTime.Now;
                    SF.logandshowInfo("登入結束@" + LoginEndTime.ToString(Configer.SystemDateTimeFormat), log_Info);
                    string LoginSpanTime = OtherProcesser.TimeDiff(LoginStartTime, LoginEndTime, "Milliseconds");
                    SF.logandshowInfo("本次登入共花費@" + LoginSpanTime + "毫秒", log_Info);

                    if (LoginResult == true)
                    {
                        //登入成功,需紀錄
                        SL.EndDateTime = DateTime.Now;
                        SL.SuccessCount = 1;
                        SL.FailCount = 0;
                        SL.Msg = "登入成功";
                        SF.log2DB(SL, MailServer, MailServerPort, MailSender, MailReceiver);
                        Session["UseCertLogin"] = UseCertLogin;
                        //Session["UseCertLogin"] = true;
                        Session["UserID"] = model.UserID;
                        //Session["UserID"] = "TAS191";
                        int UserRole= SF.getUserRole(model.UserID);
                        Session["UserRole"] = UserRole;

                        //主管導向覆核頁面
                        if (UserRole > 3)
                        {
                            return RedirectToAction("Index", "Review");
                        }
                        else
                        {
                            //導向檢查頁面
                            return RedirectToAction("Index", "Process");
                        }
                    }
                    else
                    {
                        //string a=VA.ResultStr;

                        //登入失敗,需記錄錯誤
                        SL.EndDateTime = DateTime.Now;
                        SL.FailCount = 1;
                        if (UseCertLogin)
                        {
                            SL.Msg = "登入失敗,錯誤訊息:[AD或VA驗證失敗]";
                        }
                        else
                        {
                            SL.Msg = "登入失敗,錯誤訊息:[AD驗證失敗]";
                        }
                        SL.Result = false;
                        SF.log2DB(SL, MailServer, MailServerPort, MailSender, MailReceiver);
                        TempData["LoginMsg"] = SL.Msg;

                        return RedirectToAction("Login", "Account");
                    }
                }
                else
                {
                    TempData["LoginMsg"] = "登入失敗,錯誤訊息:[系統登入參數遺失]";
                    return RedirectToAction("Login", "Account");
                }
            }
            else
            {
                return RedirectToAction("Login", "Account");
            }
        }
 public CustomPropertyCells GetCells(VA.ShapeSheet.CellData<double>[] row)
 {
     var cells = new CustomPropertyCells();
     cells.Value = row[Value.Ordinal];
     cells.Calendar = row[Calendar.Ordinal].ToInt();
     cells.Format = row[Format.Ordinal];
     cells.Invisible = row[Invis.Ordinal].ToInt();
     cells.Label = row[Label.Ordinal];
     cells.LangId = row[LangID.Ordinal].ToInt();
     cells.Prompt = row[Prompt.Ordinal];
     cells.SortKey = row[SortKey.Ordinal].ToInt();
     cells.Type = row[Type.Ordinal].ToInt();
     cells.Ask = row[Ask.Ordinal].ToBool();
     return cells;
 }
    public void main()
    {
        // ========================================================================================================================================================================= //
        // --------------------------------------------
        // 1. Initialize AutoHotkey (AHK) Functionality
        // --------------------------------------------

        // 1.1 Determine path to "VA-AHK.Integration" directory in VoiceAttack Apps folder
        // This is needed to locate the included 32 or 64-bit AutoHotkey.dll files as well as other resources
        string AppsPath  = VA.ParseTokens("{VA_APPS}");       // Obtain directory path to VoiceAttack "Apps" folder
        string MyAppName = "VA-AHK.Integration";              // Initialize string variable for storing relevant App (folder) name
        string MyAppPath = Path.Combine(AppsPath, MyAppName); // Initialize variable for storing path to relevant App directory

        // 1.2 Create instance for accessing AHK functionality
        var ahk = new VA.AutoHotkey.Interop.AutoHotkeyEngine(MyAppPath);     // Create an AutoHotkeyEngine instance associated with ahk variable

        // ========================================================================================================================================================================= //
        // -----------------------------------------------------
        // 2. Create an AHK thread that runs an empty AHK script
        // -----------------------------------------------------

        ahk.CreateThread("");     // Creates an AHK thread that runs an empty, #Persistent, and #NoTrayIcon AHK script. Also terminates any other active AHK threads.

        // ========================================================================================================================================================================= //
        // -------------------------------------------------------------------------
        // 3. Execute and manipulate AHK scripts or raw code using active AHK thread
        // -------------------------------------------------------------------------

        /* The methods in this section for executing and manipulating AHK scripts should meet the needs of 95% of users.
         * As long as an AHK thread is active the code in this section will work.
         * Note that AHK processing in this section will be performed in series with the C# code ==> C# will wait for AHK code to finish before continuing. */

        // 3.1 Execute any raw AHK code
        ahk.ExecRaw("MsgBox, Hello World!");

        // 3.2 Create new AHK hotkeys
        ahk.ExecRaw("^a::Send, Hello World!");     // CTRL+A types "Hello World!"

        // 3.3 Suspends all hotkeys and hotstrings (with exceptions, see official AHK documentation for the Suspend command)
        ahk.Suspend();

        // 3.4 Previously defined "Hello World" hotkey should be disabled now

        // 3.5 Unsuspend all hotkeys and hotstrings
        ahk.UnSuspend();

        // 3.6 Set variables in AHK
        ahk.SetVar("x", "1");
        ahk.SetVar("y", "4");
        ahk.SetVar("MyString", "Hello");

        // 3.7 Execute statements in AHK
        ahk.ExecRaw("z:=x+y");
        ahk.ExecRaw(@"MyString := MyString . "" World!"""); // Note that double quotes ("") are needed to encapsulate literal strings
        ahk.ExecRaw("MsgBox, Today is %A_DDDD% %A_MMMM% %A_DD% %A_YYYY%");
        ahk.ExecRaw("Menu, Tray, Icon");                    // Overrides the default #NoTrayIcon and makes the AHK icon appear in the tray
        ahk.ExecRaw("MyScriptName:=A_ScriptName");          // Use this method to store built-in AHK variables within named variables for later AHK processing or retrieval

        // 3.8 Retrieve variables from AHK
        string zValue = ahk.GetVar("z");

        VA.WriteToLog("Value of z = " + zValue, "blue");                        // "Value of z = 5"
        VA.WriteToLog("Value of MyString = " + ahk.GetVar("MyString"), "blue"); // "Value of MyString = Hello World!"
        VA.WriteToLog("AHK version = " + ahk.GetVar("A_AhkVersion"), "blue");   // AHK built-in variables can be retrieved directly using ahk.GetVar
        VA.WriteToLog("ScriptName = " + ahk.GetVar("MyScriptName"), "blue");    // The empty script uses "AutoHotkey.dll" as its script name

        // 3.9 Send AHK value back to VA as a variable
        VA.SetInt("~myInt", Convert.ToInt32(zValue));

        // 3.10 Program and execute statements in AHK with formatting similar to what is inputted natively in AHK scripts
        // Everything between the double quotes contains the AHK script
        ahk.ExecRaw(@"
                a := 6
                b := 7
                c := a + b
                MyLongerString := ""This is another string.""
            ");                                                                             // Note that double quotes ("") are needed to encapsulate literal strings in the above method
        string cValue = ahk.GetVar("c");                                                    // Retrieve the value of "c" from AHK and store in cValue string

        VA.WriteToLog("Value of c = " + cValue, "blue");                                    // "Value of c = 13"
        VA.WriteToLog("Value of MyLongerString = " + ahk.GetVar("MyLongerString"), "blue"); // "Value of MyLongerString = This is another string."
        ahk.ExecRaw(@"
                counter=3
                Loop, %counter%
                {
                    TimerString:=""Message box countdown: "" . (counter-A_Index+1) . "" s""
                    MsgBox,, AHK Processing, %TimerString%, 1
                    Sleep, 1000
                }
                 MsgBox,,AHK Processing, C# execution will now continue
            ");                                                                             // Demonstrates how C# will wait for AHK processing to complete before continuing

        // 3.11 Perform additional calculations with previously defined variables in both AHK and C#
        ahk.ExecRaw(@"
                d = 2
                c := c + d
                MyString := MyString . "" "" . ""It is a good string.""
            ");
        cValue = ahk.GetVar("c");                                               // Retrieve the value of "c" from AHK and store in cValue string
        VA.WriteToLog("Value of c = " + cValue, "blue");                        // "Value of c = 15"
        VA.WriteToLog("Value of MyString = " + ahk.GetVar("MyString"), "blue"); // "Value of MyString = Hello World! It is a good string."
        int c = Convert.ToInt32(cValue);                                        // Convert string cValue to integer and store in c
        int e = c + 2;                                                          // Initialize integer e

        VA.WriteToLog("Value of e = " + e, "blue");                             // "Value of e = 17"

        // 3.12 Load a library or execute scripts found within "AHK Scripts" folder inside of "VA-AHK.Integration" directory
        ahk.Load("HelloWorld.ahk");

        // 3.13 Load a library or execute scripts found within a specified directory
        //string MyFileDirectory = @"C:\Program Files (x86)\VoiceAttack\Apps\VA-AHK.Integration\AHK Scripts\My Directory"; // Just an example to show the syntax needed to provide a raw directory path
        string MyFileDirectory = Path.Combine(MyAppPath, "AHK Scripts", "My Directory");     // Example path that pulls from "My Directory" folder inside the "AHK Scripts" folder

        ahk.Load("HelloWorld2.ahk", MyFileDirectory);

        // 3.14 Determine if a specific function exists (has been loaded) within the current AHK thread and execute it if it exists
        ahk.Load("functions.ahk");                            // Load the script "functions.ahk"
        if (ahk.FunctionExists("MyFunction") == true)         // Check if "MyFunction" function exists within the current AHK thread. Should return TRUE since the function "MyFunction" is found within "functions.ahk" that was previously loaded.
        {
            ahk.ExecFunction("MyFunction", "Hello", "World"); // Execute "MyFunction" (with 2 parameters passed). ExecFunction accepts 1-10 parameters.
        }
        // 3.15 Eval also returns results from functions already loaded in the current AHK thread
        // The number of parameters that can be passed to AHK via Eval may not be as limited as it is for ExecFunction
        string addResults = ahk.Eval("Add(5, 1)");                             // Execute the function "Add" (found within "functions.ahk" which was previously loaded) with 2 parameters passed and store the value in the string addResults

        VA.WriteToLog("Eval: Result of Add function = " + addResults, "blue"); // "Eval: Result of Add function = 6"

        // 3.16 Determine if a specific label exists (has been loaded) within the current AHK thread and execute it if it exists
        if (ahk.LabelExists("DOSTUFF") == true) // Check if "DOSTUFF" label exists within the current AHK thread. Should return TRUE since "DOSTUFF" label is found within "functions.ahk" that was previously loaded.
        {
            ahk.ExecLabel("DOSTUFF");           // Execute "DOSTUFF" label
        }
        // 3.17 Create a new function with formatting similar to what is inputted natively in AHK scripts, then execute it
        // The raw AHK code is first stored within a C# string variable
        string SayHelloFunction = @"
                SayHello(name)
                {
                    MsgBox, Hello %name%
                    return
                }
            ";                                   // Note that the SayHello AHK function requires a "name" parameter

        MessageBox.Show(SayHelloFunction);       // Useful for viewing the string that will be written to the AHK thread
        ahk.ExecRaw(SayHelloFunction);           // This "writes" the created function to the AHK thread
        ahk.ExecFunction("SayHello", "Chester"); // Execute "SayHello" function while passing it "Chester" as the "name" parameter
        ahk.ExecRaw(@"SayHello(""Fluffy"")");    // Another way to execute "SayHello" function while passing it "Fluffy" as the "name" parameter

        // 3.18 Pause the current AHK thread (though hotkeys and hotstrings will still be active). See official AHK documentation for the "Pause" command.
        ahk.Pause("On");

        // 3.19 Unpause the current AHK thread
        ahk.Pause("Off");

        // 3.20 Reload current thread (terminate and restart it) based on parameters used with CreateThread (in section 2)
        // Note that all the scripts and raw code executed in this section were built on top of an empty and persistent script ==> ahk.CreateThread("")
        // Therefore reloading the thread will remove all the previous scripts and code and restart the empty script
        // If you need to directly reload a running script (stop and then restart the script) it must be executed using the method in Section 4
        ahk.Reload(100);     // Reload active AHK thread with a wait time of 100 ms. If no number is provided the wait time will be 0.

        // 3.21 Terminate active AHK thread and thereby stop all AHK scripts.
        // You can specify a time in milliseconds to wait for the thread to terminate. Negative values force an exit after the time is reached. Positive values may take longer but ensures a clean exit. 0 = no time out.
        // If you do not include this at the end of the inline function then any AHK threads, scripts, hotkeys, etc. previously executed will continue to run in the background until VA closes.
        // Pressing the "Stop All Commands" button on the main VA menu will NOT stop AHK processing that is running on an existing background AHK thread.
        // Note though that running a background AHK thread from within VA may have its uses. See the Multi-Function Example for a demonstration of using a background AHK process.
        ahk.Terminate();     // Terminate active AHK thread with a wait time of 100 ms. If no number is provided the wait time will be 0.

        // ========================================================================================================================================================================= //
        // -----------------------------------------------------------
        // 4. Second method for executing and manipulating AHK scripts
        // -----------------------------------------------------------

        /*  There are a few important characteristics about using the method outlined in Section 3 for executing AHK scripts and code:
         *      1.) AHK processing is executed in series with the C# code
         *      2.) Scripts and code cannot be reloaded since the base script (which is the foundation for the rest of the code) that gets reloaded starts out empty
         *  Point 1 is likely advantageous for most applications since it offers more control and ease for communicating back and forth between VA, C#, and AHK.
         *  Point 2 can be overcome with C# conditional logic as needed.
         *  However for the sake of demonstrating all the possible functionality the below examples outline how to execute AHK code or scripts that are directly tied to a thread. */

        // 4.1 Create new AHK thread that runs AHK code. Also terminates any other active AHK threads.
        // Note that as soon as the message box is closed the AHK code execution finishes and the thread is automatically terminated
        // Also note that code executed by this method will use "AutoHotkey.dll" as its script name
        // Just to reiterate, running AHK code (or a script file) directly through the thread as shown above will cause C# and AHK to process in parallel
        ahk.CreateThread("MsgBox,,%A_ScriptName%, Hello World!");
        // Perform additional processing
        Thread.Sleep(2000);                                                                                // Pause C# for 2000 ms. Inserted to keep this section from turning into a message box mess.
        MessageBox.Show(ahk.GetVar("A_ScriptName") + " Thread Exists = " + ahk.ThreadExists().ToString()); // Report if an AHK thread is running
        ahk.Terminate();                                                                                   // Terminate current AHK thread (if available)

        // 4.2 Create new AHK thread that runs a script found in the "AHK Scripts" folder. Also terminates any other active AHK threads.
        ahk.CreateThread("MyScript.ahk");
        // Perform additional processing
        Thread.Sleep(2000);
        MessageBox.Show("MyScript.ahk has hotkeys and is effectively #Persistent, so its thread won't terminate even after the user closes the AHK message box.");
        MessageBox.Show(ahk.GetVar("A_ScriptName") + " Thread Exists = " + ahk.ThreadExists().ToString());     // Report if an AHK thread is running

        // 4.3 Terminate current thread and restart it based on parameters used with CreateThread (in section 4).
        // Note that MyScript.ahk CAN be reloaded since it was launched when the thread was created AND the associated thread is still active
        ahk.Reload();
        // Perform additional processing
        Thread.Sleep(2000);
        MessageBox.Show(ahk.GetVar("A_ScriptName") + " Thread Exists = " + ahk.ThreadExists().ToString());     // Report if an AHK thread is running

        // 4.4 Create an AHK thread that runs a script found in the "My Directory" folder within "AHK Scripts" (or any other directory besides "AHK Scripts"). Also terminates any other active AHK threads.
        string MyScriptPath = Path.Combine(MyAppPath, "AHK Scripts", "My Directory", "HelloWorld2.ahk");     // Again, any AHK script file path will work here

        ahk.CreateThread(MyScriptPath);
        while (ahk.ThreadExists() == true)
        {
        }                    // Do nothing while waiting for the previous AHK thread to terminate. This prevents the C# code from finishing before AHK is done with its processing.
        ahk.Terminate();     // Terminate active AHK thread (if available) and thereby ensure all AHK scripts are stopped

        // ========================================================================================================================================================================= //

        VA.WriteToLog("VA-AHK.Integration inline function complete", "blue");
    }
 public ColorItem(string name, VA.ShapeSheet.SRC src)
 {
     this.Name = name;
     this.SRC = src;
     this.Formula = null;
 }
 public FormatCells GetCells(VA.ShapeSheet.CellData<double>[] row)
 {
     var cells = new FormatCells();
     cells.FillBkgnd = row[ this.FillBkgnd.Ordinal].ToInt();
     cells.FillBkgndTrans = row[ this.FillBkgndTrans.Ordinal];
     cells.FillForegnd = row[ this.FillForegnd.Ordinal].ToInt();
     cells.FillForegndTrans = row[ this.FillForegndTrans.Ordinal];
     cells.FillPattern = row[ this.FillPattern.Ordinal].ToInt();
     cells.ShapeShdwObliqueAngle = row[ this.ShapeShdwObliqueAngle.Ordinal];
     cells.ShapeShdwOffsetX = row[ this.ShapeShdwOffsetX.Ordinal];
     cells.ShapeShdwOffsetY = row[ this.ShapeShdwOffsetY.Ordinal];
     cells.ShapeShdwScaleFactor = row[ this.ShapeShdwScaleFactor.Ordinal];
     cells.ShapeShdwType = row[ this.ShapeShdwType.Ordinal].ToInt();
     cells.ShdwBkgnd = row[ this.ShdwBkgnd.Ordinal].ToInt();
     cells.ShdwBkgndTrans = row[ this.ShdwBkgndTrans.Ordinal];
     cells.ShdwForegnd = row[ this.ShdwForegnd.Ordinal].ToInt();
     cells.ShdwForegndTrans = row[ this.ShdwForegndTrans.Ordinal];
     cells.ShdwPattern = row[ this.ShdwPattern.Ordinal].ToInt();
     cells.BeginArrow = row[ this.BeginArrow.Ordinal].ToInt();
     cells.BeginArrowSize = row[ this.BeginArrowSize.Ordinal];
     cells.EndArrow = row[ this.EndArrow.Ordinal].ToInt();
     cells.EndArrowSize = row[ this.EndArrowSize.Ordinal];
     cells.LineCap = row[ this.LineCap.Ordinal].ToInt();
     cells.LineColor = row[ this.LineColor.Ordinal].ToInt();
     cells.LineColorTrans = row[ this.LineColorTrans.Ordinal];
     cells.LinePattern = row[ this.LinePattern.Ordinal].ToInt();
     cells.LineWeight = row[ this.LineWeight.Ordinal];
     cells.Rounding = row[ this.Rounding.Ordinal];
     return cells;
 }
 public TextCells GetCells(VA.ShapeSheet.CellData<double>[] row)
 {
     var cells = new TextCells();
     cells.BottomMargin = row[BottomMargin.Ordinal];
     cells.LeftMargin = row[LeftMargin.Ordinal];
     cells.RightMargin = row[RightMargin.Ordinal];
     cells.TopMargin = row[TopMargin.Ordinal];
     cells.DefaultTabStop = row[DefaultTabStop.Ordinal];
     cells.TextBkgnd = row[TextBkgnd.Ordinal].ToInt();
     cells.TextBkgndTrans = row[TextBkgndTrans.Ordinal];
     cells.TextDirection = row[TextDirection.Ordinal].ToInt();
     cells.VerticalAlign = row[VerticalAlign.Ordinal].ToInt();
     cells.TxtPinX = row[TxtPinX.Ordinal];
     cells.TxtPinY = row[TxtPinY.Ordinal];
     cells.TxtLocPinX = row[TxtLocPinX.Ordinal];
     cells.TxtLocPinY = row[TxtLocPinY.Ordinal];
     cells.TxtWidth = row[TxtWidth.Ordinal];
     cells.TxtHeight = row[TxtHeight.Ordinal];
     cells.TxtAngle = row[TxtAngle.Ordinal];
     return cells;
 }
            public ParagraphCells GetCells(VA.ShapeSheet.CellData<double>[] row)
            {
                var cells = new ParagraphCells();
                cells.IndentFirst = row[IndentFirst.Ordinal];
                cells.IndentLeft = row[IndentLeft.Ordinal];
                cells.IndentRight = row[IndentRight.Ordinal];
                cells.SpacingAfter = row[SpaceAfter.Ordinal];
                cells.SpacingBefore = row[SpaceBefore.Ordinal];
                cells.SpacingLine = row[SpaceLine.Ordinal];
                cells.HorizontalAlign = row[HorzAlign.Ordinal].ToInt();
                cells.Bullet = row[Bullet.Ordinal].ToInt();
                cells.BulletFont = row[BulletFont.Ordinal].ToInt();
                cells.BulletFontSize = row[BulletFontSize.Ordinal].ToInt();
                cells.LocBulletFont = row[LocalizeBulletFont.Ordinal].ToInt();
                cells.TextPosAfterBullet = row[TextPosAfterBullet.Ordinal];
                cells.Flags = row[Flags.Ordinal].ToInt();
                cells.BulletString = ""; // TODO: Figure out some way of getting this

                return cells;
            }
            public CharacterCells GetCells(VA.ShapeSheet.CellData<double>[] row)
            {
                var cells = new CharacterCells();
                cells.Color = row[this.Color.Ordinal].ToInt();
                cells.Transparency = row[this.Trans.Ordinal];
                cells.Font = row[this.Font.Ordinal].ToInt();
                cells.Size = row[this.Size.Ordinal];
                cells.Style = row[this.Style.Ordinal].ToInt();
                cells.AsianFont = row[this.AsianFont.Ordinal].ToInt();
                cells.AsianFont = row[this.AsianFont.Ordinal].ToInt();
                cells.Case = row[this.Case.Ordinal].ToInt();
                cells.ComplexScriptFont = row[this.ComplexScriptFont.Ordinal].ToInt();
                cells.ComplexScriptSize = row[this.ComplexScriptSize.Ordinal];
                cells.DoubleStrikeThrough = row[this.DoubleStrikethrough.Ordinal].ToBool();
                cells.DoubleUnderline = row[this.DoubleUnderline.Ordinal].ToBool();
                cells.FontScale = row[this.FontScale.Ordinal];
                cells.LangID = row[this.LangID.Ordinal].ToInt();
                cells.Letterspace = row[this.Letterspace.Ordinal];
                cells.Locale = row[this.Locale.Ordinal].ToInt();
                cells.LocalizeFont = row[this.LocalizeFont.Ordinal].ToInt();
                cells.Overline = row[this.Overline.Ordinal].ToBool();
                cells.Perpendicular = row[this.Perpendicular.Ordinal].ToBool();
                cells.Pos = row[this.Pos.Ordinal].ToInt();
                cells.RTLText = row[this.RTLText.Ordinal].ToInt();
                cells.Strikethru = row[this.Strikethru.Ordinal].ToBool();
                cells.UseVertical = row[this.UseVertical.Ordinal].ToInt();

                return cells;
            }
 public XFormCells GetCells(VA.ShapeSheet.CellData<double>[] row)
 {
     var cells = new XFormCells
     {
         PinX = row[this.PinX.Ordinal],
         PinY = row[this.PinY.Ordinal],
         LocPinX = row[this.LocPinX.Ordinal],
         LocPinY = row[this.LocPinY.Ordinal],
         Width = row[this.Width.Ordinal],
         Height = row[this.Height.Ordinal],
         Angle = row[this.Angle.Ordinal]
     };
     return cells;
 }
 public static void Set(IVisio.Shape shape, string name, VA.ShapeSheet.CellData<double> value, VA.ShapeSheet.CellData<double> prompt)
 {
     Set(shape, name, value.Formula.Value, prompt.Formula.Value);
 }
Exemple #27
0
 public static extern bool GetCursorPos(out VA.WindowsHook.NativeStructs.Point p);
Exemple #28
0
 public static extern IntPtr WindowFromPoint(VA.WindowsHook.NativeStructs.Point Point);
 public ControlCells GetCells(VA.ShapeSheet.CellData<double>[] row)
 {
     var cells = new ControlCells();
     cells.CanGlue = row[CanGlue.Ordinal].ToInt();
     cells.Tip = row[Tip.Ordinal].ToInt();
     cells.X = row[X.Ordinal];
     cells.Y = row[Y.Ordinal];
     cells.YBehavior = row[YBehavior.Ordinal].ToInt();
     cells.XBehavior = row[XBehavior.Ordinal].ToInt();
     cells.XDynamics = row[XDynamics.Ordinal].ToInt();
     cells.YDynamics = row[YDynamics.Ordinal].ToInt();
     return cells;
 }
 public UserDefinedCell GetCells(VA.ShapeSheet.CellData<string>[] row)
 {
     var cells = new UserDefinedCell();
     cells.Value = row[Value.Ordinal];
     cells.Prompt = row[Prompt.Ordinal];
     return cells;
 }
Exemple #31
0
        public ActionResult Login(LoginInfo model)
        {
            //初始化系統參數
            Configer.Init();

            AD             AD           = new AD();
            VA             VA           = new VA();
            LoginProcessor LP           = new LoginProcessor();
            bool           UseCertLogin = false;
            string         LDAPName     = Configer.LDAPName;
            //string VAVerifyURL = WebConfigurationManager.AppSettings["VAVerifyURL"];
            //string ConnStr = Configer.C_DBConnstring;
            Boolean ContinueLogin = true;

            //Log記錄用
            SYSTEMLOG SL = new SYSTEMLOG();

            SL.UId           = model.UserID;
            SL.Controller    = "Account";
            SL.Action        = "Login";
            SL.StartDateTime = DateTime.Now;
            SL.TotalCount    = 1;

            string        MailServer     = Configer.MailServer;
            int           MailServerPort = Configer.MailServerPort;
            string        MailSender     = Configer.MailSender;
            List <string> MailReceiver   = Configer.MailReceiver;

            //string SendResult = string.Empty;

            if (ModelState.IsValid)
            {
                if (LDAPName == "")
                {
                    //缺少系統參數,需記錄錯誤
                    SL.EndDateTime  = DateTime.Now;
                    SL.SuccessCount = 0;
                    SL.FailCount    = 1;
                    SL.Msg          = "登入作業失敗,錯誤訊息:[缺少系統參數LDAPName]";
                    SL.Result       = false;
                    SF.log2DB(SL, MailServer, MailServerPort, MailSender, MailReceiver);
                    ContinueLogin = false;
                }
                if (ContinueLogin)
                {
                    AD.UserName  = model.UserID;
                    AD.Pwd       = model.Pwd;
                    AD.validType = AD.ValidType.Domain;
                    AD.LDAPName  = LDAPName;

                    //VA.SignData = model.SignData;
                    //VA.Plaintext = model.Plaintext;
                    //VA.txnCode = "TxnCode";
                    //VA.VAVerifyURL = VAVerifyURL;
                    //VA.Tolerate = 120;

                    DateTime LoginStartTime = DateTime.Now;
                    SF.logandshowInfo("登入開始@" + LoginStartTime.ToString(Configer.SystemDateTimeFormat), log_Info);
                    bool     LoginResult  = LP.DoLogin(UseCertLogin, AD, VA);
                    DateTime LoginEndTime = DateTime.Now;
                    SF.logandshowInfo("登入結束@" + LoginEndTime.ToString(Configer.SystemDateTimeFormat), log_Info);
                    string LoginSpanTime = OtherProcesser.TimeDiff(LoginStartTime, LoginEndTime, "Milliseconds");
                    SF.logandshowInfo("本次登入共花費@" + LoginSpanTime + "毫秒", log_Info);

                    if (LoginResult == true)
                    {
                        //登入成功,需紀錄
                        SL.EndDateTime  = DateTime.Now;
                        SL.SuccessCount = 1;
                        SL.FailCount    = 0;
                        SL.Msg          = "登入成功";
                        SF.log2DB(SL, MailServer, MailServerPort, MailSender, MailReceiver);
                        Session["UseCertLogin"] = UseCertLogin;
                        //Session["UseCertLogin"] = true;
                        Session["UserID"] = model.UserID;
                        //Session["UserID"] = "TAS191";
                        int UserRole = SF.getUserRole(model.UserID);
                        Session["UserRole"] = UserRole;

                        //主管導向覆核頁面
                        if (UserRole > 3)
                        {
                            return(RedirectToAction("Index", "Review"));
                        }
                        else
                        {
                            //導向檢查頁面
                            return(RedirectToAction("Index", "Process"));
                        }
                    }
                    else
                    {
                        //string a=VA.ResultStr;

                        //登入失敗,需記錄錯誤
                        SL.EndDateTime = DateTime.Now;
                        SL.FailCount   = 1;
                        if (UseCertLogin)
                        {
                            SL.Msg = "登入失敗,錯誤訊息:[AD或VA驗證失敗]";
                        }
                        else
                        {
                            SL.Msg = "登入失敗,錯誤訊息:[AD驗證失敗]";
                        }
                        SL.Result = false;
                        SF.log2DB(SL, MailServer, MailServerPort, MailSender, MailReceiver);
                        TempData["LoginMsg"] = SL.Msg;

                        return(RedirectToAction("Login", "Account"));
                    }
                }
                else
                {
                    TempData["LoginMsg"] = "登入失敗,錯誤訊息:[系統登入參數遺失]";
                    return(RedirectToAction("Login", "Account"));
                }
            }
            else
            {
                return(RedirectToAction("Login", "Account"));
            }
        }
 public LockCells GetCells(VA.ShapeSheet.CellData<double>[] row)
 {
     var cells = new LockCells();
     cells.LockAspect = row[this.LockAspect.Ordinal].ToBool();
     cells.LockBegin = row[this.LockBegin.Ordinal].ToBool();
     cells.LockCalcWH = row[this.LockCalcWH.Ordinal].ToBool();
     cells.LockCrop = row[this.LockCrop.Ordinal].ToBool();
     cells.LockCustProp = row[this.LockCustProp.Ordinal].ToBool();
     cells.LockDelete = row[this.LockDelete.Ordinal].ToBool();
     cells.LockEnd = row[this.LockEnd.Ordinal].ToBool();
     cells.LockFormat = row[this.LockFormat.Ordinal].ToBool();
     cells.LockFromGroupFormat = row[this.LockFromGroupFormat.Ordinal].ToBool();
     cells.LockGroup = row[this.LockGroup.Ordinal].ToBool();
     cells.LockHeight = row[this.LockHeight.Ordinal].ToBool();
     cells.LockMoveX = row[this.LockMoveX.Ordinal].ToBool();
     cells.LockMoveY = row[this.LockMoveY.Ordinal].ToBool();
     cells.LockRotate = row[this.LockRotate.Ordinal].ToBool();
     cells.LockSelect = row[this.LockSelect.Ordinal].ToBool();
     cells.LockTextEdit = row[this.LockTextEdit.Ordinal].ToBool();
     cells.LockThemeColors = row[this.LockThemeColors.Ordinal].ToBool();
     cells.LockThemeEffects = row[this.LockThemeEffects.Ordinal].ToBool();
     cells.LockVtxEdit = row[this.LockVtxEdit.Ordinal].ToBool();
     cells.LockWidth = row[this.LockWidth.Ordinal].ToBool();
     return cells;
 }
 public PageCells GetCells(VA.ShapeSheet.CellData<double>[] row)
 {
     var cells = new PageCells();
     cells.PageLeftMargin = row[PageLeftMargin.Ordinal];
     cells.CenterX = row[CenterX.Ordinal];
     cells.CenterY = row[CenterY.Ordinal];
     cells.OnPage = row[OnPage.Ordinal].ToInt();
     cells.PageBottomMargin = row[PageBottomMargin.Ordinal];
     cells.PageRightMargin = row[PageRightMargin.Ordinal];
     cells.PagesX = row[PagesX.Ordinal];
     cells.PagesY = row[PagesY.Ordinal];
     cells.PageTopMargin = row[PageTopMargin.Ordinal];
     cells.PaperKind = row[PaperKind.Ordinal].ToInt();
     cells.PrintGrid = row[PrintGrid.Ordinal].ToInt();
     cells.PrintPageOrientation = row[PrintPageOrientation.Ordinal].ToInt();
     cells.ScaleX = row[ScaleX.Ordinal];
     cells.ScaleY = row[ScaleY.Ordinal];
     cells.PaperSource = row[PaperSource.Ordinal].ToInt();
     cells.DrawingScale = row[DrawingScale.Ordinal];
     cells.DrawingScaleType = row[DrawingScaleType.Ordinal].ToInt();
     cells.DrawingSizeType = row[DrawingSizeType.Ordinal].ToInt();
     cells.InhibitSnap = row[InhibitSnap.Ordinal].ToInt();
     cells.PageHeight = row[PageHeight.Ordinal];
     cells.PageScale = row[PageScale.Ordinal];
     cells.PageWidth = row[PageWidth.Ordinal];
     cells.ShdwObliqueAngle = row[ShdwObliqueAngle.Ordinal];
     cells.ShdwOffsetX = row[ShdwOffsetX.Ordinal];
     cells.ShdwOffsetY = row[ShdwOffsetY.Ordinal];
     cells.ShdwScaleFactor = row[ShdwScaleFactor.Ordinal];
     cells.ShdwType = row[ShdwType.Ordinal].ToInt();
     cells.UIVisibility = row[UIVisibility.Ordinal];
     cells.XGridDensity = row[XGridDensity.Ordinal];
     cells.XGridOrigin = row[XGridOrigin.Ordinal];
     cells.XGridSpacing = row[XGridSpacing.Ordinal];
     cells.XRulerDensity = row[XRulerDensity.Ordinal];
     cells.XRulerOrigin = row[XRulerOrigin.Ordinal];
     cells.YGridDensity = row[YGridDensity.Ordinal];
     cells.YGridOrigin = row[YGridOrigin.Ordinal];
     cells.YGridSpacing = row[YGridSpacing.Ordinal];
     cells.YRulerDensity = row[YRulerDensity.Ordinal];
     cells.YRulerOrigin = row[YRulerOrigin.Ordinal];
     cells.AvenueSizeX = row[AvenueSizeX.Ordinal];
     cells.AvenueSizeY = row[AvenueSizeY.Ordinal];
     cells.BlockSizeX = row[BlockSizeX.Ordinal];
     cells.BlockSizeY = row[BlockSizeY.Ordinal];
     cells.CtrlAsInput = row[CtrlAsInput.Ordinal].ToInt();
     cells.DynamicsOff = row[DynamicsOff.Ordinal].ToInt();
     cells.EnableGrid = row[EnableGrid.Ordinal].ToInt();
     cells.LineAdjustFrom = row[LineAdjustFrom.Ordinal].ToInt();
     cells.LineAdjustTo = row[LineAdjustTo.Ordinal];
     cells.LineJumpCode = row[LineJumpCode.Ordinal];
     cells.LineJumpFactorX = row[LineJumpFactorX.Ordinal];
     cells.LineJumpFactorY = row[LineJumpFactorY.Ordinal];
     cells.LineJumpStyle = row[LineJumpStyle.Ordinal].ToInt();
     cells.LineRouteExt = row[LineRouteExt.Ordinal];
     cells.LineToLineX = row[LineToLineX.Ordinal];
     cells.LineToLineY = row[LineToLineY.Ordinal];
     cells.LineToNodeX = row[LineToNodeX.Ordinal];
     cells.LineToNodeY = row[LineToNodeY.Ordinal];
     cells.PageLineJumpDirX = row[PageLineJumpDirX.Ordinal];
     cells.PageLineJumpDirY = row[PageLineJumpDirY.Ordinal];
     cells.PageShapeSplit = row[PageShapeSplit.Ordinal].ToInt();
     cells.PlaceDepth = row[PlaceDepth.Ordinal].ToInt();
     cells.PlaceFlip = row[PlaceFlip.Ordinal].ToInt();
     cells.PlaceStyle = row[PlaceStyle.Ordinal].ToInt();
     cells.PlowCode = row[PlowCode.Ordinal].ToInt();
     cells.ResizePage = row[ResizePage.Ordinal].ToInt();
     cells.RouteStyle = row[RouteStyle.Ordinal].ToInt();
     //cells.AvoidPageBreaks = row[AvoidPageBreaks.Ordinal].ToInt();
     //cells.DrawingResizeType = row[DrawingResizeType.Ordinal].ToInt();
     return cells;
 }
    bool UseDictation;     // Declare boolean variable for storing pronunciation dictation grammar setting

    public void main()
    {
        // Reset relevant VoiceAttack text variables
        VA.SetText("~~RecognitionError", null);
        VA.SetText("~~RecognizedText", null);
        VA.SetText("~~SAPIPhonemes", null);
        VA.SetText("~~SAPIPhonemesRaw", null);
        //VA.SetText("~~FalseRecognitionFlag", null);

        // Retrieve the desired word data contained within VoiceAttack text variable
        string ProcessText = null;                     // Initialize string variable for storing the text of interest

        if (VA.GetText("~~ProcessText") != null)       // Check if user provided valid text in input variable
        {
            ProcessText = VA.GetText("~~ProcessText"); // Store text of interest held by VA text variable
        }
        else
        {
            VA.SetText("~~RecognitionError", "Error in input text string (SAPI)"); // Send error detail back to VoiceAttack as text variable
            return;                                                                // End code processing
        }

        // Retrieve path to speech grammar XML file from VoiceAttack
        GrammarPath = VA.GetText("~~GrammarFilePath");

        // Retrieve path to voice recognition input wav file from VoiceAttack
        AudioPath = VA.GetText("~~AudioFilePath");

        // Check if TTS engine is voicing the input for the speech recognition engine
        if (VA.GetBoolean("~~UserVoiceInput") == false)
        {
            //VA.WriteToLog("creating wav file");
            if (TextToWav(AudioPath, ProcessText) == false) // Create wav file with specified path that voices specified text (with text-to-speech) and check if the creation was NOT successful
            {
                return;                                     // Stop executing the code
            }
        }

        // Create speech recognizer and associated context
        SpInprocRecognizer  MyRecognizer = new SpInprocRecognizer();                              // Create new instance of SpInprocRecognizer
        SpInProcRecoContext RecoContext  = (SpInProcRecoContext)MyRecognizer.CreateRecoContext(); // Initialize the SpInProcRecoContext (in-process recognition context)

        try                                                                                       // Attempt the following code
        {
            // Open the created wav in a new FileStream
            FileStream = new SpFileStream();                                        // Create new instance of SpFileStream
            FileStream.Open(AudioPath, SpeechStreamFileMode.SSFMOpenForRead, true); // Open the specified file in the FileStream for reading with events enabled

            // Set the voice recognition input as the FileStream
            MyRecognizer.AudioInputStream = FileStream;             // This will internally "speak" the wav file for input into the voice recognition engine

            // Set up recognition event handling
            RecoContext.Recognition      += new _ISpeechRecoContextEvents_RecognitionEventHandler(RecoContext_Recognition);           // Register for successful voice recognition events
            RecoContext.FalseRecognition += new _ISpeechRecoContextEvents_FalseRecognitionEventHandler(RecoContext_FalseRecognition); // Register for failed (low confidence) voice recognition events
            if (VA.GetBoolean("~~ShowRecognitionHypothesis") == true)                                                                 // Check if user wants to show voice recognition hypothesis results
            {
                RecoContext.Hypothesis += new _ISpeechRecoContextEvents_HypothesisEventHandler(RecoContext_Hypothesis);               // Register for voice recognition hypothesis events
            }
            RecoContext.EndStream += new _ISpeechRecoContextEvents_EndStreamEventHandler(RecoContext_EndStream);                      // Register for end of file stream events

            // Set up the grammar
            grammar      = RecoContext.CreateGrammar();                     // Initialize the grammar object
            UseDictation = (bool?)VA.GetBoolean("~~UseDictation") ?? false; // Set UserDictation based on value from VoiceAttack boolean variable
            if (UseDictation == true)                                       // Check if pronunciation dictation grammar should be used with speech recognition
            {
                //grammar.DictationLoad("", SpeechLoadOption.SLOStatic); // Load blank dictation topic into the grammar
                grammar.DictationLoad("Pronunciation", SpeechLoadOption.SLOStatic);    // Load pronunciation dictation topic into the grammar so that the raw (unfiltered) phonemes may be retrieved
                grammar.DictationSetState(SpeechRuleState.SGDSActive);                 // Activate dictation grammar
            }
            else
            {
                grammar.CmdLoadFromFile(GrammarPath, SpeechLoadOption.SLODynamic);           // Load custom XML grammar file
                grammar.CmdSetRuleIdState(0, SpeechRuleState.SGDSActive);                    // Activate the loaded grammar
            }
            Application.Run();                                                               // Starts a standard application message loop on the current thread
        }
        catch                                                                                // Handle exceptions in above code
        {
            VA.SetText("~~RecognitionError", "Error during voice recognition setup (SAPI)"); // Send error detail back to VoiceAttack as text variable
            return;                                                                          // Stop executing the code
        }
        finally                                                                              // Runs whether an exception is encountered or not
        {
            MyRecognizer = null;                                                             // Set to null in preparation for garbage collection
            FileStream.Close();                                                              // Close the input FileStream
            FileStream = null;                                                               // Set to null in preparation for garbage collection

            // Close up recognition event handling
            RecoContext.Recognition      -= new _ISpeechRecoContextEvents_RecognitionEventHandler(RecoContext_Recognition);           // Unregister for successful voice recognition events
            RecoContext.FalseRecognition -= new _ISpeechRecoContextEvents_FalseRecognitionEventHandler(RecoContext_FalseRecognition); // Unregister for failed (low confidence) voice recognition events
            if (VA.GetBoolean("~~ShowRecognitionHypothesis") == true)                                                                 // Check if user wanted to show voice recognition hypothesis results
            {
                RecoContext.Hypothesis -= new _ISpeechRecoContextEvents_HypothesisEventHandler(RecoContext_Hypothesis);               // Unregister for voice recognition hypothesis events
            }
            RecoContext.EndStream -= new _ISpeechRecoContextEvents_EndStreamEventHandler(RecoContext_EndStream);                      // Unregister for end of file stream events
            RecoContext            = null;                                                                                            // Set to null in preparation for garbage collection
        }
        //VA.WriteToLog("voice recognition complete"); // Output info to event log
    }