public void Constructors2()
 {
     var err = new ErrorManager();
     Assert.AreEqual(ErrorMode.ThrowException, err.ErrorMode);
     Assert.AreEqual(0, err.ErrorCount);
     Assert.AreEqual(0, err.Errors.Length);
 }
 public void Constructors()
 {
     var err = new ErrorManager(ErrorMode.IgnoreAndContinue);
     Assert.AreEqual(ErrorMode.IgnoreAndContinue, err.ErrorMode);
     Assert.AreEqual(0, err.ErrorCount);
     Assert.AreEqual(0, err.Errors.Length);
 }
Example #3
0
 public static QupidQuery ParseString(string query, ErrorManager errorManager)
 {
     var lexer = new QuerySyntaxLexer(new ANTLRStringStream(query));
     var parser = new QuerySyntaxParser(new CommonTokenStream {TokenSource = lexer}, errorManager);
     var ast = parser.Parse();
     return ast;
 }
Example #4
0
        public async Task <ActionResult> Login(LoginViewModel model, string returnUrl)
        {
            if (!ModelState.IsValid)
            {
                return(View(model));
            }
            try
            {
                //Kolla om öppet, annars visa stängt-sida
                if (!_portalService.IsOpen())
                {
                    ViewBag.Text = _portalService.HamtaInformationsText("Stangtsida");
                    return(View("Closed"));
                }
                //Add this to check if the email was confirmed.
                var user = await UserManager.FindByNameAsync(model.Email);

                if (user == null)
                {
                    ModelState.AddModelError("", "Felaktigt användarnamn eller pinkod.");
                    return(View(model));
                }
                //Check if users organisation or user has been disabled
                var userOrg = _portalService.HamtaOrgForAnvandare(user.Id);
                if (userOrg.AktivTom <= DateTime.Now)
                {
                    ModelState.AddModelError("", "Organisationen " + userOrg.Organisationsnamn + " är inaktiv, ta kontakt med " + ConfigurationManager.AppSettings["MailSender"]);
                    return(View(model));
                }
                else if (user.AktivTom <= DateTime.Now)
                {
                    model.DisabledAccount = true;
                    ModelState.AddModelError("", "Kontot är inaktiverat. För att återaktivera ditt konto behöver du verifiera din e-postadress.");
                    return(View(model));
                }
                if (!await UserManager.IsEmailConfirmedAsync(user.Id))
                {
                    ModelState.AddModelError("", "Du behöver bekräfta din epostadress. Se mejl från [email protected]");
                    return(View(model));
                }
                // This doesn't count login failures towards account lockout
                // To enable password failures to trigger account lockout, change to shouldLockout: true
                var result = await SignInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe,
                                                                     shouldLockout : false);

                switch (result)
                {
                case SignInStatus.Success:
                    //var user = UserManager.FindByEmail(model.Email);
                    _portalService.SaveToLoginLog(user.Id, user.UserName);
                    return(RedirectToLocal(returnUrl));

                case SignInStatus.LockedOut:
                    return(View("Lockout"));

                case SignInStatus.RequiresVerification:
                    if (!await UserManager.IsPhoneNumberConfirmedAsync(user.Id))
                    {
                        var phoneNumber = UserManager.GetPhoneNumberAsync(user.Id);
                        //Skicka användaren till AddPhoneNumber
                        var phoneNumberModel = new RegisterPhoneNumberViewModel()
                        {
                            Id     = user.Id,
                            Number = phoneNumber.Result
                        };
                        if (phoneNumberModel.Number == null)
                        {
                            return(View("AddPhoneNumber", phoneNumberModel));
                        }
                        else
                        {
                            return(await this.AddPhoneNumber(phoneNumberModel));
                        }
                    }
                    else
                    {
                        return(RedirectToAction("SendCode", new SendCodeViewModel
                        {
                            Providers = null,
                            ReturnUrl = returnUrl,
                            RememberMe = model.RememberMe,
                            SelectedProvider = "Phone Code",
                            UserEmail = model.Email
                        }));
                    }

                case SignInStatus.Failure:
                default:
                    ModelState.AddModelError("", "Felaktigt användarnamn eller pinkod.");
                    return(View(model));
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                ErrorManager.WriteToErrorLog("AccountController", "Login", e.ToString(), e.HResult, model.Email);
                var errorModel = new CustomErrorPageModel
                {
                    Information  = "Ett fel inträffade vid inloggningen",
                    ContactEmail = ConfigurationManager.AppSettings["ContactEmail"],
                };
                return(View("CustomError", errorModel));
            }
        }
Example #5
0
 /// <summary>
 /// Applies theme colors to the control based on type.
 /// </summary>
 private static void ThemeControl(Object obj, Type type)
 {
     try
     {
         // Apply colors of base type before applying for this type
         Boolean useIn = GetThemeValue("ThemeManager.UseInheritance") == "True";
         if (useIn && type.BaseType != null)
         {
             ThemeControl(obj, type.BaseType);
         }
         // Handle type with full name, with or without suffix 'Ex'
         String       name    = type.Name.EndsWithOrdinal("Ex") ? type.Name.Remove(type.Name.Length - 2) : type.Name;
         PropertyInfo ground  = type.GetProperty("BackgroundColor");
         PropertyInfo alink   = type.GetProperty("ActiveLinkColor");
         PropertyInfo dlink   = type.GetProperty("DisabledLinkColor");
         PropertyInfo dborder = type.GetProperty("DisabledBorderColor");
         PropertyInfo curpos  = type.GetProperty("CurrentPositionColor");
         PropertyInfo dback   = type.GetProperty("DisabledBackColor");
         PropertyInfo afore   = type.GetProperty("ActiveForeColor");
         PropertyInfo border  = type.GetProperty("BorderColor");
         PropertyInfo hfore   = type.GetProperty("HotForeColor");
         PropertyInfo harrow  = type.GetProperty("HotArrowColor");
         PropertyInfo aarrow  = type.GetProperty("ActiveArrowColor");
         PropertyInfo arrow   = type.GetProperty("ArrowColor");
         PropertyInfo link    = type.GetProperty("LinkColor");
         PropertyInfo back    = type.GetProperty("BackColor");
         PropertyInfo fore    = type.GetProperty("ForeColor");
         if (back != null)
         {
             String key   = name + ".BackColor";
             Color  color = GetThemeColor(key);
             if (color != Color.Empty)
             {
                 back.SetValue(obj, color, null);
             }
         }
         if (fore != null)
         {
             String key   = name + ".ForeColor";
             Color  color = GetThemeColor(key);
             if (color != Color.Empty)
             {
                 fore.SetValue(obj, color, null);
             }
         }
         if (ground != null)
         {
             String key   = name + ".BackgroundColor";
             Color  color = GetThemeColor(key);
             if (color != Color.Empty)
             {
                 ground.SetValue(obj, color, null);
             }
         }
         if (alink != null)
         {
             String key   = name + ".ActiveLinkColor";
             Color  color = GetThemeColor(key);
             if (color != Color.Empty)
             {
                 alink.SetValue(obj, color, null);
             }
         }
         if (dlink != null)
         {
             String key   = name + ".DisabledLinkColor";
             Color  color = GetThemeColor(key);
             if (color != Color.Empty)
             {
                 dlink.SetValue(obj, color, null);
             }
         }
         if (link != null)
         {
             String key   = name + ".LinkColor";
             Color  color = GetThemeColor(key);
             if (color != Color.Empty)
             {
                 link.SetValue(obj, color, null);
             }
         }
         if (border != null)
         {
             String key   = name + ".BorderColor";
             Color  color = GetThemeColor(key);
             if (color != Color.Empty)
             {
                 border.SetValue(obj, color, null);
             }
         }
         if (afore != null)
         {
             String key   = name + ".ActiveForeColor";
             Color  color = GetThemeColor(key);
             if (color != Color.Empty)
             {
                 afore.SetValue(obj, color, null);
             }
         }
         if (dborder != null)
         {
             String key   = name + ".DisabledBorderColor";
             Color  color = GetThemeColor(key);
             if (color != Color.Empty)
             {
                 dborder.SetValue(obj, color, null);
             }
         }
         if (curpos != null)
         {
             String key   = name + ".CurrentPositionColor";
             Color  color = GetThemeColor(key);
             if (color != Color.Empty)
             {
                 curpos.SetValue(obj, color, null);
             }
         }
         if (dback != null)
         {
             String key   = name + ".DisabledBackColor";
             Color  color = GetThemeColor(key);
             if (color != Color.Empty)
             {
                 dback.SetValue(obj, color, null);
             }
         }
         if (hfore != null)
         {
             String key   = name + ".HotForeColor";
             Color  color = GetThemeColor(key);
             if (color != Color.Empty)
             {
                 hfore.SetValue(obj, color, null);
             }
         }
         if (harrow != null)
         {
             String key   = name + ".HotArrowColor";
             Color  color = GetThemeColor(key);
             if (color != Color.Empty)
             {
                 harrow.SetValue(obj, color, null);
             }
         }
         if (aarrow != null)
         {
             String key   = name + ".ActiveArrowColor";
             Color  color = GetThemeColor(key);
             if (color != Color.Empty)
             {
                 aarrow.SetValue(obj, color, null);
             }
         }
         if (arrow != null)
         {
             String key   = name + ".ArrowColor";
             Color  color = GetThemeColor(key);
             if (color != Color.Empty)
             {
                 arrow.SetValue(obj, color, null);
             }
         }
     }
     catch (Exception ex)
     {
         ErrorManager.ShowError(ex);
     }
 }
Example #6
0
        /// <summary>
        /// Handles the received data and fires XmlReceived event
        /// </summary>
        public void OnReceivedData(IAsyncResult result)
        {
            StateObject so = (StateObject)result.AsyncState;

            try
            {
                Int32 bytesReceived = so.Client.EndReceive(result);
                if (bytesReceived > 0)
                {
                    /**
                     * Recieve data
                     */
                    so.Data.Append(Encoding.ASCII.GetString(so.Buffer, 0, bytesReceived));
                    String contents = so.Data.ToString();
                    if (this.DataReceived != null)
                    {
                        this.DataReceived(this, new DataReceivedEventArgs(contents, so.Client));
                    }

                    /**
                     * Check packet
                     */
                    if (packets != null)
                    {
                        packets.Append(contents);
                    }
                    else if (contents.StartsWith('<'))
                    {
                        packets = new StringBuilder(contents);
                    }
                    else
                    {
                        ErrorManager.ShowWarning(INCORRECT_PKT + contents, null);
                    }

                    /**
                     * Validate message
                     */
                    if (packets != null && contents.EndsWith('\0'))
                    {
                        String msg = packets.ToString(); packets = null;
                        if (msg == "<policy-file-request/>\0")
                        {
                            String policy = "<cross-domain-policy><site-control permitted-cross-domain-policies=\"master-only\"/><allow-access-from domain=\"*\" to-ports=\"*\" /></cross-domain-policy>\0";
                            so.Client.Send(Encoding.ASCII.GetBytes(policy));
                        }
                        else if (msg.EndsWithOrdinal("</flashconnect>\0"))
                        {
                            this.XmlReceived(this, new XmlReceivedEventArgs(msg, so.Client));
                        }
                        else
                        {
                            ErrorManager.ShowWarning(INCORRECT_PKT + msg, null);
                        }
                    }
                    this.SetupReceiveCallback(so.Client);
                }
                else
                {
                    so.Client.Shutdown(SocketShutdown.Both);
                    so.Client.Close();
                }
            }
            catch (SocketException)
            {
                so.Client.Shutdown(SocketShutdown.Both);
                so.Client.Close();
            }
            catch (Exception ex)
            {
                ErrorManager.ShowError(ex);
            }
        }
        /// <summary>
        /// Shows the completion list
        /// </summary>
        static public void Show(List <ICompletionListItem> itemList, bool autoHide)
        {
            ITabbedDocument doc = PluginBase.MainForm.CurrentDocument;

            if (!doc.IsEditable)
            {
                return;
            }
            ScintillaControl sci = doc.SciControl;
            ListBox          cl  = completionList;

            try
            {
                if ((itemList == null) || (itemList.Count == 0))
                {
                    if (isActive)
                    {
                        Hide();
                    }
                    return;
                }
                if (sci == null)
                {
                    if (isActive)
                    {
                        Hide();
                    }
                    return;
                }
            }
            catch (Exception ex)
            {
                ErrorManager.ShowError(ex);
            }
            // state
            allItems     = itemList;
            autoHideList = autoHide;
            noAutoInsert = false;
            word         = "";
            if (currentWord != null)
            {
                word        = currentWord;
                currentWord = null;
            }
            MinWordLength    = 1;
            fullList         = (word.Length == 0) || !autoHide || !PluginBase.MainForm.Settings.AutoFilterList;
            lastIndex        = 0;
            exactMatchInList = false;
            if (sci.SelectionStart == sci.SelectionEnd)
            {
                startPos = sci.CurrentPos - word.Length;
            }
            else
            {
                startPos = sci.SelectionStart;
            }
            currentPos  = sci.SelectionEnd; // sci.CurrentPos;
            defaultItem = null;
            // populate list
            needResize    = true;
            tempo.Enabled = autoHide && (PluginBase.MainForm.Settings.DisplayDelay > 0);
            if (tempo.Enabled)
            {
                tempo.Interval = PluginBase.MainForm.Settings.DisplayDelay;
            }
            FindWordStartingWith(word);
            // state
            isActive          = true;
            tempoTip.Enabled  = false;
            showTime          = DateTime.Now.Ticks;
            disableSmartMatch = noAutoInsert || PluginBase.MainForm.Settings.DisableSmartMatch;
            UITools.Manager.LockControl(sci);
            faded = false;
        }
Example #8
0
        public void QuickBuild(FileModel theFile, string flex2Path, bool requireTag, bool playAfterBuild)
        {
            if (running)
            {
                return;
            }
            // environment
            string filename    = theFile.FileName;
            string currentPath = Environment.CurrentDirectory;
            string buildPath   = PluginBase.MainForm.ProcessArgString("$(ProjectDir)");

            if (!Directory.Exists(buildPath) ||
                !filename.StartsWith(buildPath, StringComparison.OrdinalIgnoreCase))
            {
                buildPath = theFile.BasePath;
                if (!Directory.Exists(buildPath))
                {
                    buildPath = Path.GetDirectoryName(filename);
                }
            }
            // command
            debugMode = false;
            bool   hasOutput = false;
            string cmd       = "";
            Match  mCmd      = Regex.Match(PluginBase.MainForm.CurrentDocument.SciControl.Text, "\\s@mxmlc\\s(?<cmd>.*)");

            if (mCmd.Success)
            {
                try
                {
                    // cleanup tag
                    string tag = mCmd.Groups["cmd"].Value;
                    if (tag.IndexOf("-->") > 0)
                    {
                        tag = tag.Substring(0, tag.IndexOf("-->"));
                    }
                    if (tag.IndexOf("]]>") > 0)
                    {
                        tag = tag.Substring(0, tag.IndexOf("]]>"));
                    }
                    tag = " " + tag.Trim() + " --";

                    // split
                    MatchCollection mPar = re_SplitParams.Matches(tag);
                    if (mPar.Count > 0)
                    {
                        cmd = "";
                        string op;
                        string arg;
                        for (int i = 0; i < mPar.Count; i++)
                        {
                            op = mPar[i].Groups["switch"].Value;
                            if (op == "--")
                            {
                                break;
                            }
                            if (op == "-noplay")
                            {
                                playAfterBuild = false;
                                continue;
                            }
                            if (op == "-debug")
                            {
                                debugMode = true;
                            }

                            int start = mPar[i].Index + mPar[i].Length;
                            int end   = (i < mPar.Count - 1) ? mPar[i + 1].Index : 0;
                            if (end > start)
                            {
                                string concat = ";";
                                arg = tag.Substring(start, end - start).Trim();
                                if (arg.StartsWith("+=") || arg.StartsWith("="))
                                {
                                    concat = arg.Substring(0, arg.IndexOf('=') + 1);
                                    arg    = arg.Substring(concat.Length);
                                }
                                bool isPath = false;
                                foreach (string pswitch in PATH_SWITCHES)
                                {
                                    if (pswitch == op)
                                    {
                                        if (op.EndsWith("namespace"))
                                        {
                                            int sp = arg.IndexOf(' ');
                                            if (sp > 0)
                                            {
                                                concat += arg.Substring(0, sp) + ";";
                                                arg     = arg.Substring(sp + 1).TrimStart();
                                            }
                                        }
                                        isPath = true;
                                        if (!arg.StartsWith("\\") && !Path.IsPathRooted(arg))
                                        {
                                            arg = Path.Combine(buildPath, arg);
                                        }
                                    }
                                }
                                if (op == "-o" || op == "-output")
                                {
                                    builtSWF  = arg;
                                    hasOutput = true;
                                }
                                if (!isPath)
                                {
                                    arg = arg.Replace(" ", ";");
                                }
                                cmd += op + concat + arg + ";";
                            }
                            else
                            {
                                cmd += op + ";";
                            }
                        }
                    }
                }
                catch
                {
                    ErrorManager.ShowInfo(TextHelper.GetString("Info.InvalidForQuickBuild"));
                }
            }
            else if (requireTag)
            {
                return;
            }

            // Flex4 static linking
            if (isFlex4SDK && cmd.IndexOf("-static-link-runtime-shared-libraries") < 0)
            {
                cmd += ";-static-link-runtime-shared-libraries=true";
            }

            // add current class sourcepath and global classpaths
            cmd += ";-sp+=" + theFile.BasePath;
            if (Context.Context.Settings.UserClasspath != null)
            {
                foreach (string cp in Context.Context.Settings.UserClasspath)
                {
                    cmd += ";-sp+=" + cp;
                }
            }
            // add output filename
            if (!hasOutput)
            {
                builtSWF = Path.Combine(buildPath, Path.GetFileNameWithoutExtension(filename) + ".swf");
                cmd      = "-o;" + builtSWF + ";" + cmd;
            }
            // add current file
            cmd += ";--;" + filename;

            // build
            cmd = cmd.Replace(";;", ";");
            RunMxmlc(cmd, flex2Path);
            if (!playAfterBuild)
            {
                builtSWF = null;
            }

            // restaure working directory
            Environment.CurrentDirectory = currentPath;
        }
Example #9
0
        public override CodeModel Build(out IEnumerable <ValidationMessage> messages)
        {
            Logger.LogInfo(Resources.ParsingSwagger);
            if (string.IsNullOrWhiteSpace(Settings.Input))
            {
                throw ErrorManager.CreateError(Resources.InputRequired);
            }
            ServiceDefinition = SwaggerParser.Load(Settings.Input, Settings.FileSystem);

            // Look for semantic errors and warnings in the document.
            var validator = new RecursiveObjectValidator(PropertyNameResolver.JsonName);

            messages = validator.GetValidationExceptions(ServiceDefinition).ToList();

            Logger.LogInfo(Resources.GeneratingClient);
            // Update settings
            UpdateSettings();

            InitializeClientModel();
            BuildCompositeTypes();

            // Build client parameters
            foreach (var swaggerParameter in ServiceDefinition.Parameters.Values)
            {
                var parameter = ((ParameterBuilder)swaggerParameter.GetBuilder(this)).Build();

                var clientProperty = New <Property>();
                clientProperty.LoadFrom(parameter);

                CodeModel.Add(clientProperty);
            }

            var methods = new List <Method>();

            // Build methods
            foreach (var path in ServiceDefinition.Paths.Concat(ServiceDefinition.CustomPaths))
            {
                foreach (var verb in path.Value.Keys)
                {
                    var operation = path.Value[verb];
                    if (string.IsNullOrWhiteSpace(operation.OperationId))
                    {
                        throw ErrorManager.CreateError(
                                  string.Format(CultureInfo.InvariantCulture,
                                                Resources.OperationIdMissing,
                                                verb,
                                                path.Key));
                    }
                    var methodName  = GetMethodName(operation);
                    var methodGroup = GetMethodGroup(operation);

                    if (verb.ToHttpMethod() != HttpMethod.Options)
                    {
                        string url = path.Key;
                        if (url.Contains("?"))
                        {
                            url = url.Substring(0, url.IndexOf('?'));
                        }
                        var method = BuildMethod(verb.ToHttpMethod(), url, methodName, operation);
                        method.Group = methodGroup;

                        methods.Add(method);
                        if (method.DefaultResponse.Body is CompositeType)
                        {
                            CodeModel.AddError((CompositeType)method.DefaultResponse.Body);
                        }
                    }
                    else
                    {
                        Logger.LogWarning(Resources.OptionsNotSupported);
                    }
                }
            }

            // Set base type
            foreach (var typeName in GeneratedTypes.Keys)
            {
                var objectType = GeneratedTypes[typeName];
                if (ExtendedTypes.ContainsKey(typeName))
                {
                    objectType.BaseModelType = GeneratedTypes[ExtendedTypes[typeName]];
                }

                CodeModel.Add(objectType);
            }
            CodeModel.AddRange(methods);


            return(CodeModel);
        }
Example #10
0
 public QueryExecutor(ErrorManager errorManager, IEnumerable<IQupidJoinPlugin> plugins)
 {
     _errorManager = errorManager;
     _joinPlugins = plugins.ToList();
 }
Example #11
0
        public void CheckAS3(string filename, string flexPath, string src)
        {
            if (running)
            {
                return;
            }

            // let other plugins preprocess source/handle checking
            Hashtable data = new Hashtable();

            data["filename"] = filename;
            data["src"]      = src;
            data["ext"]      = Path.GetExtension(filename);
            DataEvent de = new DataEvent(EventType.Command, "AS3Context.CheckSyntax", data);

            EventManager.DispatchEvent(this, de);
            if (de.Handled)
            {
                return;
            }

            src      = (string)data["src"];
            filename = (string)data["filename"];
            if (".mxml" == (string)data["ext"]) // MXML not supported by ASC without preprocessing
            {
                return;
            }

            string basePath = null;

            if (PluginBase.CurrentProject != null)
            {
                basePath = Path.GetDirectoryName(PluginBase.CurrentProject.ProjectPath);
            }
            flexPath = PathHelper.ResolvePath(flexPath, basePath);
            // asc.jar in FlexSDK
            if (flexPath != null && Directory.Exists(Path.Combine(flexPath, "lib")))
            {
                ascPath = Path.Combine(flexPath, "lib\\asc.jar");
            }
            // included asc.jar
            if (ascPath == null || !File.Exists(ascPath))
            {
                ascPath = PathHelper.ResolvePath(Path.Combine(PathHelper.ToolDir, "flexlibs/lib/asc.jar"));
            }

            if (ascPath == null)
            {
                if (src != null)
                {
                    return;              // silent checking
                }
                DialogResult result = MessageBox.Show(TextHelper.GetString("Info.SetFlex2OrCS3Path"), TextHelper.GetString("Title.ConfigurationRequired"), MessageBoxButtons.YesNoCancel);
                if (result == DialogResult.Yes)
                {
                    IASContext context = ASContext.GetLanguageContext("as3");
                    if (context == null)
                    {
                        return;
                    }
                    PluginBase.MainForm.ShowSettingsDialog("AS3Context", "SDK");
                }
                else if (result == DialogResult.No)
                {
                    PluginBase.MainForm.ShowSettingsDialog("ASCompletion", "Flash");
                }
                return;
            }

            flexShellsPath = CheckResource("FlexShells.jar", flexShellsJar);
            if (!File.Exists(flexShellsPath))
            {
                if (src != null)
                {
                    return;              // silent checking
                }
                ErrorManager.ShowInfo(TextHelper.GetString("Info.ResourceError"));
                return;
            }

            jvmConfig = JvmConfigHelper.ReadConfig(flexPath);

            try
            {
                running = true;
                if (src == null)
                {
                    EventManager.DispatchEvent(this, new NotifyEvent(EventType.ProcessStart));
                }
                if (ascRunner == null || !ascRunner.IsRunning || currentSDK != flexPath)
                {
                    StartAscRunner(flexPath);
                }

                notificationSent = false;
                if (src == null)
                {
                    silentChecking = false;
                    //TraceManager.Add("Checking: " + filename, -1);
                    ASContext.SetStatusText(TextHelper.GetString("Info.AscRunning"));
                    ascRunner.HostedProcess.StandardInput.WriteLine(filename);
                }
                else
                {
                    silentChecking = true;
                    ascRunner.HostedProcess.StandardInput.WriteLine(filename + "$raw$");
                    ascRunner.HostedProcess.StandardInput.WriteLine(src);
                    ascRunner.HostedProcess.StandardInput.WriteLine(filename + "$raw$");
                }
            }
            catch (Exception ex)
            {
                ErrorManager.AddToLog(TextHelper.GetString("Info.CheckError"), ex);
                TraceManager.AddAsync(TextHelper.GetString("Info.CheckError") + "\n" + ex.Message);
            }
        }
Example #12
0
        public bool ValidateSDK(InstalledSDK sdk)
        {
            sdk.Owner = this;
            string path = sdk.Path;

            if (path == null)
            {
                return(false);
            }
            Match mBin = Regex.Match(path, "[/\\\\]bin$", RegexOptions.IgnoreCase);

            if (mBin.Success)
            {
                sdk.Path = path = path.Substring(0, mBin.Index);
            }

            IProject project = PluginBase.CurrentProject;

            if (project != null)
            {
                path = PathHelper.ResolvePath(path, Path.GetDirectoryName(project.ProjectPath));
            }
            else
            {
                path = PathHelper.ResolvePath(path);
            }

            try
            {
                if (path == null || !Directory.Exists(path))
                {
                    ErrorManager.ShowInfo("Path not found:\n" + sdk.Path);
                    return(false);
                }
            }
            catch (Exception ex)
            {
                ErrorManager.ShowInfo("Invalid path (" + ex.Message + "):\n" + sdk.Path);
                return(false);
            }

            string descriptor = Path.Combine(path, "flex-sdk-description.xml");

            if (!File.Exists(descriptor))
            {
                descriptor = Path.Combine(path, "air-sdk-description.xml");
            }

            if (File.Exists(descriptor))
            {
                string raw   = File.ReadAllText(descriptor);
                Match  mName = Regex.Match(raw, "<name>([^<]+)</name>");
                Match  mVer  = Regex.Match(raw, "<version>([^<]+)</version>");
                if (mName.Success && mVer.Success)
                {
                    sdk.Name    = mName.Groups[1].Value;
                    sdk.Version = mVer.Groups[1].Value;

                    descriptor = Path.Combine(path, "AIR SDK Readme.txt");
                    if (sdk.Name.StartsWith("Flex") && File.Exists(descriptor))
                    {
                        raw = File.ReadAllText(descriptor);
                        Match mAIR = Regex.Match(raw, "Adobe AIR ([0-9.]+) SDK");
                        if (mAIR.Success)
                        {
                            sdk.Name    += ", AIR " + mAIR.Groups[1].Value;
                            sdk.Version += ", " + mAIR.Groups[1].Value;
                        }
                    }
                    return(true);
                }
                else
                {
                    ErrorManager.ShowInfo("Invalid SDK descriptor:\n" + descriptor);
                }
            }
            else
            {
                ErrorManager.ShowInfo("No SDK descriptor found:\n" + descriptor);
            }
            return(false);
        }
Example #13
0
        public async Task <ActionResult> Register(RegisterViewModel model)
        {
            if (ModelState.IsValid)
            {
                try
                {
                    var organisation = GetOrganisationForEmailDomain(model.Email);
                    if (organisation == null)
                    {
                        ModelState.AddModelError("",
                                                 "Epostdomänen saknas i vårt register. Kontakta Socialstyrelsen för mer information. Support, epost: " +
                                                 ConfigurationManager.AppSettings["ContactEmail"]);
                    }
                    else
                    {
                        var user = new ApplicationUser {
                            UserName = model.Email, Email = model.Email
                        };
                        user.OrganisationId = organisation.Id;
                        user.SkapadAv       = model.Email;
                        user.SkapadDatum    = DateTime.Now;
                        user.AndradAv       = model.Email;
                        user.AndradDatum    = DateTime.Now;
                        user.Namn           = model.Namn;
                        user.Kontaktnummer  = model.Telefonnummer;

                        var result = await UserManager.CreateAsync(user, model.Password);

                        if (result.Succeeded)
                        {
                            await UserManager.SetTwoFactorEnabledAsync(user.Id, true);

                            //Spara valda register
                            //_portalService.SparaValdaRegistersForAnvandare(user.Id, user.UserName, model.RegisterList);
                            //Verifiera epostadress
                            var code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id);

                            var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code },
                                                         protocol: Request.Url.Scheme);
                            //TODO mail/utvecklingsmiljön
                            await UserManager.SendEmailAsync(user.Id, "Bekräfta e-postadress", "Bekräfta din e-postadress i Socialstyrelsens inrapporteringsportal genom att klicka <a href=\"" + callbackUrl + "\">här</a>");

                            ViewBag.Email = model.Email;
                            return(View("DisplayEmail"));
                        }
                        AddErrors(result);
                    }
                }
                catch (System.Net.Mail.SmtpException e)
                {
                    Console.WriteLine(e);
                    ErrorManager.WriteToErrorLog("AccountController", "Register", e.ToString(), e.HResult, model.Email);
                    var errorModel = new CustomErrorPageModel
                    {
                        Information  = "Ett fel inträffade vid registreringen. Mail kunde ej skickas.",
                        ContactEmail = ConfigurationManager.AppSettings["ContactEmail"],
                    };
                    return(View("CustomError", errorModel));
                }
                catch (Exception e)
                {
                    Console.WriteLine(e);
                    ErrorManager.WriteToErrorLog("AccountController", "Register", e.ToString(), e.HResult, model.Email);
                    var errorModel = new CustomErrorPageModel
                    {
                        Information  = "Ett fel inträffade vid registreringen.",
                        ContactEmail = ConfigurationManager.AppSettings["ContactEmail"],
                    };
                    return(View("CustomError", errorModel));
                }
            }
            // If we got this far, something failed, redisplay form
            return(View(model));
        }
Example #14
0
        private void PatchFbProject(AS3Project project)
        {
            if (project == null || !project.MovieOptions.Platform.StartsWith("AIR"))
            {
                return;
            }

            // We do this because the batch files cannot automatically detect the path changes caused by debug/release differences
            bool trace = project.TraceEnabled;

            project.TraceEnabled = false;
            project.OutputPath   = project.FixDebugReleasePath(project.OutputPath);
            project.TraceEnabled = trace;

            string path       = Path.GetDirectoryName(project.ProjectPath);
            string descriptor = "src\\" + Path.GetFileNameWithoutExtension(project.OutputPath) + "-app.xml";

            project.TestMovieBehavior = TestMovieBehavior.Custom;
            project.TestMovieCommand  = "bat\\RunApp.bat";

            // CrossOver template related mod
            if (Win32.isRunningOnWine())
            {
                project.TestMovieCommand += " $(TargetBuild)";
            }

            if (!File.Exists(Path.Combine(path, descriptor)))
            {
                // Either it's some library project (we'll deal with these later)
                // or it's placed in some folder different to the default one (same as above)
                return;
            }

            // We copy the needed project template files
            bool   isFlex = project.CompileTargets.Count > 0 && Path.GetExtension(project.CompileTargets[0]).ToLower() == ".mxml";
            string projectPath;
            var    excludedFiles = new List <string>(); // This could be a setting, in any case, decided to do this in case someone added custom files to the project templates...

            if (project.MovieOptions.Platform == "AIR Mobile")
            {
                projectPath = isFlex ? project.MovieOptions.PlatformSupport.GetProjectTemplate("flex") : project.MovieOptions.PlatformSupport.GetProjectTemplate("as3");
                excludedFiles.AddRange(new[] { "application.xml.template", "Project.as3proj", "Project.png", "Project.txt", "bin", "cert", "icons", "src" });
            }
            else
            {
                // The files are the same for Flex 3 and 4, so no need to discern them
                projectPath = isFlex ? project.MovieOptions.PlatformSupport.GetProjectTemplate("flex4") : project.MovieOptions.PlatformSupport.GetProjectTemplate("as3");
                excludedFiles.AddRange(new[] { "application.xml.template", "Project.as3proj", "Project.png", "Project.txt", "bin", "src" });
            }

            if (projectPath == null || !Directory.Exists(projectPath = Path.Combine(PathHelper.ProjectsDir, projectPath)))
            {
                string info = TextHelper.GetString("Info.TemplateDirNotFound");
                ErrorManager.ShowWarning(info, null);
                return;
            }
            var creator = new ProjectCreator();

            creator.SetContext(Path.GetFileNameWithoutExtension(project.OutputPath), string.Empty);
            foreach (var file in Directory.GetFiles(projectPath, "*.*", SearchOption.AllDirectories))
            {
                bool excluded = false;
                foreach (var excludedFile in excludedFiles)
                {
                    if (file.StartsWith(Path.Combine(projectPath, excludedFile)))
                    {
                        excluded = true;
                        break;
                    }
                }

                if (excluded)
                {
                    continue;
                }
                var fileDirectory = Path.GetDirectoryName(file).Replace(projectPath, string.Empty);
                if (fileDirectory.StartsWith("\\"))
                {
                    fileDirectory = fileDirectory.Substring(1);
                }
                var folder = Path.Combine(path, fileDirectory);
                if (!Directory.Exists(folder))
                {
                    Directory.CreateDirectory(folder);
                }
                string newFile = Path.Combine(folder, Path.GetFileName(file));
                if (Path.GetExtension(file).ToLower() == ".template")
                {
                    creator.CopyFile(file, newFile);
                }
                else
                {
                    File.Copy(file, newFile, true);
                }
            }

            // We configure the batch files
            var configurator = new AirConfigurator {
                ApplicationSetupBatch = Path.Combine(path, "bat\\SetupApp.bat")
            };

            configurator.ApplicationSetupParams[AirConfigurator.DescriptorPath] = descriptor;
            configurator.ApplicationSetupParams[AirConfigurator.PackageDir]     = Path.GetFileName(Path.GetDirectoryName(project.OutputPath));
            configurator.SetUp();

            // We change the descriptor file so it targets our output file. FB does this dynamically.
            descriptor = Path.Combine(path, descriptor);
            var    fileInfo = FileHelper.GetEncodingFileInfo(descriptor);
            string contents = Regex.Replace(fileInfo.Contents, "<content>\\[This value will be overwritten by (Flex|Flash) Builder in the output app.xml]</content>", "<content>" + Path.GetFileName(project.OutputPath) + "</content>");

            FileHelper.WriteFile(descriptor, contents, Encoding.GetEncoding(fileInfo.CodePage), fileInfo.ContainsBOM);
        }
Example #15
0
        public void GenerateDeltaTable()
        {
            try
            {
                if (!m_isLoginUserSQLEditor)
                {
                    ValidateIsSQLEditor();
                    m_isLoginUserSQLEditor = true;
                }

                // load high watermark; as for CQ, we store local time for queries
                m_hwmDelta.Reload();
                DateTime hwmDeltaValue = m_hwmDelta.Value;
                if (hwmDeltaValue.Equals(default(DateTime)))
                {
                    hwmDeltaValue = new DateTime(1900, 1, 1);
                }
                hwmDeltaValue = hwmDeltaValue.AddSeconds(-1);   // go back 1 second as we'll drop the millisec below

                m_migrationContext.CurrentHWMBaseLine = hwmDeltaValue;
                string hwmDeltaValueStr = hwmDeltaValue.ToString(m_migrationContext.CQQueryDateTimeFormat, CultureInfo.InvariantCulture);

                DateTime newHwmValue = CQUtilityMethods.GetTimeForNewHighWaterMark(m_migrationContext.CQTimeOffsetFromServerHistoryTimesInMinutes);

                foreach (CQRecordFilter filter in m_filters)
                {
                    ComputeDeltaPerRecordType(filter, hwmDeltaValueStr);
                }

                // persist results and hwm
                TraceManager.TraceInformation("Promote delta to pending.");
                m_changeGroupService.PromoteDeltaToPending();

                m_hwmDelta.Update(newHwmValue);
                TraceManager.TraceInformation("Persisted CQ HWM: {0}", ClearQuestConstants.CqRecordHwm);
                TraceManager.TraceInformation("Updated CQ HWM: {0}", newHwmValue.ToString());
            }
            catch (ClearQuestInsufficientPrivilegeException privEx)
            {
                ConflictResolutionResult rslt = UtilityMethods.HandleInsufficientPriviledgeException(privEx, m_conflictManagerService);
                if (rslt.Resolved)
                {
                    // todo: currently not expected, as we only enabled manual/skip resolution action
                }
            }
            catch (ClearQuestCOMDllNotFoundException cqComNotFoundEx)
            {
                UtilityMethods.HandleCOMDllNotFoundException(cqComNotFoundEx, ErrorManager, m_conflictManagerService);
            }
            catch (ClearQuestCOMCallException cqComCallEx)
            {
                UtilityMethods.HandleCQComCallException(cqComCallEx, ErrorManager, m_conflictManagerService);
            }
            catch (Exception ex)
            {
                ErrorManager errMgr = null;
                if (m_analysisServiceContainer != null)
                {
                    errMgr = m_analysisServiceContainer.GetService(typeof(ErrorManager)) as ErrorManager;
                }
                UtilityMethods.HandleGeneralException(ex, errMgr, m_conflictManagerService);
            }
        }
Example #16
0
        public void Start()
        {
            while (true)
            {
                try
                {
                    if (_cancelToken.IsCancellationRequested)
                    {
                        break;
                    }

                    if (LongProcessesConfiguration.GetConfig().AllConfiguredProcessNames.Count == 0)
                    {
                        LogError(addedQueue, $"[{DateTime.Now:dd.MM.yyyy HH:mm:ss}]: WorkerStarter: Не сконфигурирован ни один процесс");
                        return;
                    }

                    List <long> addedProcessTypeIds = new List <long>();

                    // Первый добавлен - первый отправлен на обработку
                    List <OMQueue> addedQueueList = OMQueue.Where(x => x.Status_Code == Status.Added &&
                                                                  LongProcessesConfiguration.GetConfig().AllConfiguredProcessNames.Contains(x.ParentProcessType.ProcessName))
                                                    .SelectAll()
                                                    .OrderBy(x => x.CreateDate)
                                                    .Execute();

                    // Отмечаем задачи в очереди - на запуск
                    foreach (OMQueue addedQueue in addedQueueList)
                    {
                        if (!WorkerCommon.ProcessTypeCache.ContainsKey(addedQueue.ProcessTypeId))
                        {
                            LogError(addedQueue, "Не найден тип процесса с ИД: " + addedQueue.ProcessTypeId);
                            continue;
                        }

                        OMProcessType processType = WorkerCommon.ProcessTypeCache[addedQueue.ProcessTypeId];

                        //RSMSUPPORT-1097 проверка на максимальное количество запущенных потоков для типа процесса
                        if (IsMaxRunningTasks(processType, addedProcessTypeIds))
                        {
                            continue;
                        }

                        addedQueue.Status_Code   = Status.PrepareToRun;
                        addedQueue.ServiceLogId  = _workerData.ApplicationId;
                        addedQueue.LastCheckDate = DateTime.Now;
                        addedQueue.Save();

                        addedProcessTypeIds.Add(processType.Id);
                    }

                    // Запускаем отмеченные задачи
                    List <OMQueue> queueList =
                        OMQueue.Where(
                            x =>
                            x.Status_Code == Status.PrepareToRun &&
                            x.ServiceLogId == _workerData.ApplicationId).SelectAll().Execute();

                    foreach (OMQueue queue in queueList)
                    {
                        StartTask(queue);
                    }
                }
                catch (Exception ex)
                {
                    int errorId = ErrorManager.LogError(ex);
                }

                Thread.Sleep(TimeSpan.FromMilliseconds(_workerData.TaskStartTimerInterval));
            }
        }
Example #17
0
        /// <summary>
        /// Создает новую таску
        /// </summary>
        /// <param name="queue"></param>
        private void StartTask(OMQueue queue)
        {
            if (!WorkerCommon.ProcessTypeCache.ContainsKey(queue.ProcessTypeId))
            {
                LogError(queue, "Не найден тип процесса с ИД: " + queue.ProcessTypeId);
                return;
            }

            OMProcessType processType = WorkerCommon.ProcessTypeCache[queue.ProcessTypeId];

            ILongProcess longProcess;

            try
            {
                longProcess = WorkerCommon.GetLongProcessObject(queue.ProcessTypeId);
            }
            catch (Exception ex)
            {
                LogError(queue, ex.Message);
                return;
            }

            if (longProcess == null)
            {
                LogError(queue, "Не удалось создать объект типа: " + processType.ClassName);
                return;
            }

            CancellationTokenSource cancelTokenSource = new CancellationTokenSource();

            queue.StartDate     = DateTime.Now;
            queue.LastCheckDate = DateTime.Now;
            queue.Status_Code   = Status.Running;
            queue.Save();

            Task task = new Task(() =>
            {
                try
                {
                    _workerData.СurrentTasks[queue.Id].CurrentThread = Thread.CurrentThread;

                    // Так как данный процесс запускается в отдельном потоке в него необходимо передать данные об авторизованном пользователе,
                    // иначе работа будет выполняться под учетной записью пула приложений
                    if (queue.UserId > 0 && SRDCache.Users.ContainsKey((int)queue.UserId.Value))
                    {
                        SRDSession.SetThreadCurrentPrincipal(queue.UserId.Value);
                    }

                    queue.CleanPropertyChangedList();

                    longProcess.StartProcess(processType, queue, cancelTokenSource.Token);

                    processType.LastStartDate = queue.StartDate;
                    processType.Save();

                    queue.EndDate       = DateTime.Now;
                    queue.LastCheckDate = DateTime.Now;
                    queue.Status_Code   = Status.Completed;
                    queue.Save();

                    _workerData.СurrentTasks.Remove(queue.Id);
                }
                catch (Exception ex)
                {
                    _workerData.СurrentTasks.Remove(queue.Id);

                    int errorId = ErrorManager.LogError(ex);

                    queue.EndDate     = DateTime.Now;
                    queue.Status_Code = Status.Faulted;
                    queue.ErrorId     = errorId;

                    var message = ex.Message;
                    if (message.Length >= 4000)
                    {
                        message = message.Substring(0, 4000);
                    }

                    queue.Message = message;
                    queue.Save();

                    try
                    {
                        longProcess.LogError(queue.ObjectId, ex, errorId);
                    }
                    catch (Exception) { }
                }
            }, cancelTokenSource.Token);

            TaskData taskData = new TaskData
            {
                Task = task,
                CancellationTokenSource = cancelTokenSource,
                LongProcess             = longProcess,
                ProcessTypeId           = processType.Id
            };

            _workerData.СurrentTasks.Add(queue.Id, taskData);

            taskData.Task.Start();
        }
        public bool Build(Project project, bool runOutput, bool releaseMode)
        {
            // save modified files
            mainForm.CallCommand("SaveAllModified", null);

            string       compiler = null;
            InstalledSDK sdk      = null;

            if (project.IsCompilable)
            {
                sdk      = GetProjectSDK(project);
                compiler = GetCompilerPath(project, sdk);
            }
            project.TraceEnabled = !releaseMode;

            if (project.OutputType == OutputType.OtherIDE)
            {
                // compile using associated IDE
                string error;
                string command = project.GetOtherIDE(runOutput, releaseMode, out error);

                if (error != null)
                {
                    ErrorManager.ShowInfo(TextHelper.GetString(error));
                }
                else
                {
                    if (command == "FlashIDE")
                    {
                        RunFlashIDE(project, runOutput, releaseMode);
                    }
                    else
                    {
                        Hashtable data = new Hashtable();
                        data["command"]     = command;
                        data["project"]     = project;
                        data["runOutput"]   = runOutput;
                        data["releaseMode"] = releaseMode;
                        DataEvent de = new DataEvent(EventType.Command, "ProjectManager.RunWithAssociatedIDE", data);
                        EventManager.DispatchEvent(project, de);
                        if (de.Handled)
                        {
                            return(true);
                        }
                    }
                }
                return(false);
            }
            else if (project.OutputType == OutputType.CustomBuild)
            {
                // validate commands not empty
                if (project.PreBuildEvent.Trim().Length == 0 && project.PostBuildEvent.Trim().Length == 0)
                {
                    String info = TextHelper.GetString("Info.NoOutputAndNoBuild");
                    TraceManager.Add(info);
                }
            }
            else if (project.IsCompilable)
            {
                // ask the project to validate itself
                string error;
                project.ValidateBuild(out error);

                if (error != null)
                {
                    ErrorManager.ShowInfo(TextHelper.GetString(error));
                    return(false);
                }

                if (project.OutputPath.Length < 1)
                {
                    String info = TextHelper.GetString("Info.SpecifyValidOutputSWF");
                    ErrorManager.ShowInfo(info);
                    return(false);
                }

                if (compiler == null || (!Directory.Exists(compiler) && !File.Exists(compiler)))
                {
                    string info = TextHelper.GetString("Info.CheckSDKSettings");
                    MessageBox.Show(info, TextHelper.GetString("Title.ConfigurationRequired"), MessageBoxButtons.OK);
                    return(false);
                }
            }

            // close running AIR projector
            if (project.MovieOptions.Platform.StartsWith("AIR"))
            {
                foreach (Process proc in Process.GetProcessesByName("adl"))
                {
                    try { proc.Kill(); proc.WaitForExit(10 * 1000); }
                    catch { }
                }
            }

            return(FDBuild(project, runOutput, releaseMode, sdk));
        }
        /// <summary>
        /// Acquires encoding related info on one read.
        /// </summary>
        public static EncodingFileInfo GetEncodingFileInfo(String file)
        {
            Int32            startIndex = 0;
            EncodingFileInfo info       = new EncodingFileInfo();

            try
            {
                if (File.Exists(file))
                {
                    Byte[] bytes = File.ReadAllBytes(file);
                    if (bytes.Length > 2 && (bytes[0] == 0xef && bytes[1] == 0xbb && bytes[2] == 0xbf))
                    {
                        startIndex       = 3;
                        info.ContainsBOM = true;
                        info.CodePage    = Encoding.UTF8.CodePage;
                    }
                    else if (bytes.Length > 3 && (bytes[0] == 0xff && bytes[1] == 0xfe && bytes[2] == 0x00 && bytes[3] == 0x00))
                    {
                        startIndex       = 4;
                        info.ContainsBOM = true;
                        info.CodePage    = Encoding.UTF32.CodePage;
                    }
                    else if (bytes.Length > 3 && ((bytes[0] == 0x2b && bytes[1] == 0x2f && bytes[2] == 0x76) || bytes[3] == 0x38 || bytes[3] == 0x39 || bytes[3] == 0x2b || bytes[3] == 2f))
                    {
                        startIndex       = 4;
                        info.ContainsBOM = true;
                        info.CodePage    = Encoding.UTF7.CodePage;
                    }
                    else if (bytes.Length > 1 && (bytes[0] == 0xff && bytes[1] == 0xfe))
                    {
                        startIndex       = 2;
                        info.ContainsBOM = true;
                        info.CodePage    = Encoding.Unicode.CodePage;
                    }
                    else if (bytes.Length > 1 && (bytes[0] == 0xfe && bytes[1] == 0xff))
                    {
                        startIndex       = 2;
                        info.ContainsBOM = true;
                        info.CodePage    = Encoding.BigEndianUnicode.CodePage;
                    }
                    else
                    {
                        if (!ContainsInvalidUTF8Bytes(bytes))
                        {
                            info.CodePage = Encoding.UTF8.CodePage;
                        }
                        else
                        {
                            info.CodePage = Encoding.Default.CodePage;
                        }
                    }
                    Int32 contentLength = bytes.Length - startIndex;
                    if (bytes.Length > 0 && bytes.Length > startIndex)
                    {
                        Encoding encoding = Encoding.GetEncoding(info.CodePage);
                        info.Contents = encoding.GetString(bytes, startIndex, contentLength);
                    }
                }
            }
            catch (Exception ex)
            {
                info = new EncodingFileInfo();
                ErrorManager.ShowError(ex);
            }
            return(info);
        }
Example #20
0
        public SettingRegRespObj DeleteLeaveType(DeleteLeaveTypeObj regObj)
        {
            var response = new SettingRegRespObj
            {
                Status = new APIResponseStatus
                {
                    IsSuccessful = false,
                    Message      = new APIResponseMessage()
                }
            };

            try
            {
                if (regObj.Equals(null))
                {
                    response.Status.Message.FriendlyMessage  = "Error Occurred! Unable to proceed with your request";
                    response.Status.Message.TechnicalMessage = "Registration Object is empty / invalid";
                    return(response);
                }

                if (!EntityValidatorHelper.Validate(regObj, out var valResults))
                {
                    var errorDetail = new StringBuilder();
                    if (!valResults.IsNullOrEmpty())
                    {
                        errorDetail.AppendLine("Following error occurred:");
                        valResults.ForEachx(m => errorDetail.AppendLine(m.ErrorMessage));
                    }
                    else
                    {
                        errorDetail.AppendLine(
                            "Validation error occurred! Please check all supplied parameters and try again");
                    }
                    response.Status.Message.FriendlyMessage  = errorDetail.ToString();
                    response.Status.Message.TechnicalMessage = errorDetail.ToString();
                    response.Status.IsSuccessful             = false;
                    return(response);
                }

                if (!HelperMethods.IsUserValid(regObj.AdminUserId, regObj.SysPathCode,
                                               HelperMethods.getSeniorAccountant(), ref response.Status.Message))
                {
                    return(response);
                }
                var thisLeaveType = getLeaveTypeInfo(regObj.LeaveTypeId);

                if (thisLeaveType == null)
                {
                    response.Status.Message.FriendlyMessage =
                        "No Leave Type Information found for the specified LeaveType Id";
                    response.Status.Message.TechnicalMessage = "No Leave Type Information found!";
                    return(response);
                }
                thisLeaveType.Name   = thisLeaveType.Name + "_Deleted_" + DateTime.Now.ToString("yyyy_MM_dd_hh_mm_ss");
                thisLeaveType.Status = ItemStatus.Deleted;
                var added = _repository.Update(thisLeaveType);
                _uoWork.SaveChanges();

                if (added.LeaveTypeId < 1)
                {
                    response.Status.Message.FriendlyMessage =
                        "Error Occurred! Unable to complete your request. Please try again later";
                    response.Status.Message.TechnicalMessage = "Unable to save to database";
                    return(response);
                }
                resetCache();
                response.Status.IsSuccessful = true;
                response.SettingId           = added.LeaveTypeId;
            }
            catch (DbEntityValidationException ex)
            {
                ErrorManager.LogApplicationError(ex.StackTrace, ex.Source, ex.Message);
                response.Status.Message.FriendlyMessage  = "Error Occurred! Please try again later";
                response.Status.Message.TechnicalMessage = "Error: " + ex.GetBaseException().Message;
                response.Status.IsSuccessful             = false;
                return(response);
            }
            catch (Exception ex)
            {
                ErrorManager.LogApplicationError(ex.StackTrace, ex.Source, ex.Message);
                response.Status.Message.FriendlyMessage  = "Error Occurred! Please try again later";
                response.Status.Message.TechnicalMessage = "Error: " + ex.GetBaseException().Message;
                response.Status.IsSuccessful             = false;
                return(response);
            }
            return(response);
        }
Example #21
0
        public void RunMxmlc(string cmd, string flexPath)
        {
            if (running)
            {
                return;
            }
            string basePath = null;

            if (PluginBase.CurrentProject != null)
            {
                basePath = Path.GetDirectoryName(PluginBase.CurrentProject.ProjectPath);
            }
            flexPath = PathHelper.ResolvePath(flexPath, basePath);

            if (flexPath != null && Directory.Exists(flexPath))
            {
                mxmlcPath = Path.Combine(Path.Combine(flexPath, "lib"), "mxmlc.jar");
            }
            if (mxmlcPath == null || !File.Exists(mxmlcPath))
            {
                DialogResult result = MessageBox.Show(TextHelper.GetString("Info.OpenCompilerSettings"), TextHelper.GetString("Title.ConfigurationRequired"), MessageBoxButtons.OKCancel);
                if (result == DialogResult.OK)
                {
                    IASContext context = ASContext.GetLanguageContext("as3");
                    if (context == null)
                    {
                        return;
                    }
                    PluginBase.MainForm.ShowSettingsDialog("AS3Context", "SDK");
                }
                return;
            }

            flexShellsPath = CheckResource("FlexShells.jar", flexShellsJar);
            if (!File.Exists(flexShellsPath))
            {
                ErrorManager.ShowInfo(TextHelper.GetString("Info.ResourceError"));
                return;
            }

            jvmConfig = JvmConfigHelper.ReadConfig(flexPath);

            try
            {
                running = true;
                EventManager.DispatchEvent(this, new NotifyEvent(EventType.ProcessStart));

                if (mxmlcRunner == null || !mxmlcRunner.IsRunning || currentSDK != flexPath)
                {
                    StartMxmlcRunner(flexPath);
                }

                //cmd = mainForm.ProcessArgString(cmd);
                //TraceManager.Add("MxmlcShell command: "+cmd, -1);

                ASContext.SetStatusText(TextHelper.GetString("Info.MxmlcRunning"));
                notificationSent = false;
                mxmlcRunner.HostedProcess.StandardInput.WriteLine(cmd);
            }
            catch (Exception ex)
            {
                ErrorManager.ShowError(ex);
            }
        }
Example #22
0
        public LeaveTypeRespObj LoadLeaveTypes(CommonSettingSearchObj searchObj)
        {
            var response = new LeaveTypeRespObj
            {
                Status = new APIResponseStatus
                {
                    IsSuccessful = false,
                    Message      = new APIResponseMessage()
                }
            };

            try
            {
                if (searchObj.Equals(null))
                {
                    response.Status.Message.FriendlyMessage  = "Error Occurred! Unable to proceed with your request";
                    response.Status.Message.TechnicalMessage = "Registration Object is empty / invalid";
                    return(response);
                }

                if (!EntityValidatorHelper.Validate(searchObj, out var valResults))
                {
                    var errorDetail = new StringBuilder();
                    if (!valResults.IsNullOrEmpty())
                    {
                        errorDetail.AppendLine("Following error occurred:");
                        valResults.ForEachx(m => errorDetail.AppendLine(m.ErrorMessage));
                    }

                    else
                    {
                        errorDetail.AppendLine(
                            "Validation error occurred! Please check all supplied parameters and try again");
                    }
                    response.Status.Message.FriendlyMessage  = errorDetail.ToString();
                    response.Status.Message.TechnicalMessage = errorDetail.ToString();
                    response.Status.IsSuccessful             = false;
                    return(response);
                }

                //if (!HelperMethods.IsUserValid(searchObj.AdminUserId, searchObj.SysPathCode, HelperMethods.getAllRoles(), ref response.Status.Message))
                //{
                //    return response;
                //}
                var thisLeaveTypes = GetLeaveTypes();
                if (!thisLeaveTypes.Any())
                {
                    response.Status.Message.FriendlyMessage  = "No Leave Type Information found!";
                    response.Status.Message.TechnicalMessage = "No Leave Type  Information found!";
                    return(response);
                }

                if (searchObj.Status > -1)
                {
                    thisLeaveTypes = thisLeaveTypes.FindAll(p => p.Status == (ItemStatus)searchObj.Status);
                }

                var leaveTypeItems = new List <LeaveTypeObj>();
                thisLeaveTypes.ForEachx(m =>
                {
                    leaveTypeItems.Add(new LeaveTypeObj
                    {
                        LeaveTypeId = m.LeaveTypeId,
                        Name        = m.Name,
                        MinDays     = m.MinDays,
                        MaxDays     = m.MaxDays,
                        Status      = (int)m.Status,
                        StatusLabel = m.Status.ToString().Replace("_", " ")
                    });
                });

                response.Status.IsSuccessful = true;
                response.LeaveTypes          = leaveTypeItems;
                return(response);
            }

            catch (DbEntityValidationException ex)
            {
                ErrorManager.LogApplicationError(ex.StackTrace, ex.Source, ex.Message);
                response.Status.Message.FriendlyMessage  = "Error Occurred! Please try again later";
                response.Status.Message.TechnicalMessage = "Error: " + ex.GetBaseException().Message;
                response.Status.IsSuccessful             = false;
                return(response);
            }

            catch (Exception ex)
            {
                ErrorManager.LogApplicationError(ex.StackTrace, ex.Source, ex.Message);
                response.Status.Message.FriendlyMessage  = "Error Occurred! Please try again later";
                response.Status.Message.TechnicalMessage = "Error: " + ex.GetBaseException().Message;
                response.Status.IsSuccessful             = false;
                return(response);
            }
        }
Example #23
0
        internal static void Initialize()
        {
            if (Initialized)
            {
                return;
            }
            Trace.AutoFlush = true;
            var logDir  = Path.Combine(Config.Instance.DataDir, "Logs");
            var logFile = Path.Combine(logDir, "hdt_log.txt");

            if (!Directory.Exists(logDir))
            {
                Directory.CreateDirectory(logDir);
            }
            else
            {
                try
                {
                    var fileInfo = new FileInfo(logFile);
                    if (fileInfo.Exists)
                    {
                        using (var fs = new FileStream(logFile, FileMode.Open, FileAccess.Read, FileShare.None))
                        {
                            //can access log file => no other instance of same installation running
                        }
                        File.Move(logFile, logFile.Replace(".txt", "_" + DateTime.Now.ToUnixTime() + ".txt"));
                        //keep logs from the last 2 days plus 25 before that
                        foreach (var file in
                                 new DirectoryInfo(logDir).GetFiles("hdt_log*")
                                 .Where(x => x.LastWriteTime < DateTime.Now.AddDays(-MaxLogFileAge))
                                 .OrderByDescending(x => x.LastWriteTime)
                                 .Skip(KeepOldLogs))
                        {
                            try
                            {
                                File.Delete(file.FullName);
                            }
                            catch
                            {
                            }
                        }
                    }
                    else
                    {
                        File.Create(logFile).Dispose();
                    }
                }
                catch (Exception)
                {
                    MessageBox.Show("Another instance of Hearthstone Deck Tracker is already running.",
                                    "Error starting Hearthstone Deck Tracker", MessageBoxButton.OK, MessageBoxImage.Error);
                    Application.Current.Shutdown();
                    return;
                }
            }
            try
            {
                Trace.Listeners.Add(new TextWriterTraceListener(new StreamWriter(logFile, false)));
                CurrentLogFile = logFile;
            }
            catch (Exception ex)
            {
                ErrorManager.AddError("Can not access log file.", ex.ToString());
            }

            Initialized = true;
            try
            {
                foreach (var line in LogQueue)
                {
                    Trace.WriteLine(line);
                }
            }
            catch (Exception e)
            {
                HandleWriteToTraceException(e);
            }
        }
Example #24
0
        private bool AddBeneficiary()
        {
            try
            {
                var newBeneficiary = new Beneficiary
                {
                    FullName       = txtFullName.Text.Trim(),
                    CompanyName    = txtCompanyName.Text.Trim(),
                    GSMNO1         = txtPhone1.Text,
                    GSMNO2         = txtPhone2.Text,
                    Email          = txtEmail.Text,
                    Sex            = int.Parse(ddlSex.SelectedValue),
                    Status         = chkBeneficiary.Checked ? 1 : 0,
                    DateRegistered = DateMap.GetLocalDate(),
                    TimeRegistered = DateMap.GetLocalTime()
                };

                var k = ServiceProvider.Instance().GetBeneficiaryServices().AddBeneficiaryCheckDuplicate(newBeneficiary);
                if (k < 1)
                {
                    if (k == -3)
                    {
                        ConfirmAlertBox1.Attributes.CssStyle.Add("z-index", "20000001");
                        ConfirmAlertBox1.ShowMessage("The Beneficiary information already exists.", ConfirmAlertBox.PopupMessageType.Error);
                        mpeSelectDateRangePopup.Show();
                        return(false);
                    }

                    if (k == -4)
                    {
                        ConfirmAlertBox1.Attributes.CssStyle.Add("z-index", "20000001");
                        ConfirmAlertBox1.ShowMessage("Another Beneficiary with similar email already exists.", ConfirmAlertBox.PopupMessageType.Error);
                        mpeSelectDateRangePopup.Show();
                        return(false);
                    }
                    if (k == -5)
                    {
                        ConfirmAlertBox1.Attributes.CssStyle.Add("z-index", "20000001");
                        ConfirmAlertBox1.ShowMessage("Another Beneficiary with similar phone number already exists.", ConfirmAlertBox.PopupMessageType.Error);
                        mpeSelectDateRangePopup.Show();
                        return(false);
                    }
                    //if (k == -6)
                    //{
                    //    ConfirmAlertBox1.Attributes.CssStyle.Add("z-index", "20000001");
                    //    ConfirmAlertBox1.ShowMessage("Another Beneficiary with similar second phone number already exists.", ConfirmAlertBox.PopupMessageType.Error);
                    //    mpeSelectDateRangePopup.Show();
                    //    return false;
                    //}

                    ConfirmAlertBox1.Attributes.CssStyle.Add("z-index", "20000001");
                    ConfirmAlertBox1.ShowMessage("The Beneficiary Information could not be Added.", ConfirmAlertBox.PopupMessageType.Error);
                    mpeSelectDateRangePopup.Show();
                    return(false);
                }
                ClearControls();
                return(true);
            }


            catch (Exception ex)
            {
                ErrorManager.LogApplicationError(ex.StackTrace, ex.Source, ex.Message);
                ConfirmAlertBox1.ShowMessage("An unknown error was encountered. Please contact the Administrator.", ConfirmAlertBox.PopupMessageType.Error);
                return(false);
            }
        }
Example #25
0
        private bool GetTransactionPaymentsByDate()
        {
            ErrorDisplay1.ClearError();
            try
            {
                string date;
                var    transactionPaymentsByDate = new List <StaffExpenseTransactionPayment>();
                dgAllTransactionPayments.DataSource = new List <StaffExpenseTransactionPayment>();
                dgAllTransactionPayments.DataBind();
                lblFilterReport.InnerHtml = "Data list is empty.";

                if (btnRefresh.CommandArgument == "2")
                {
                    if (Session["_uncompletedPaymentsList"] == null)
                    {
                        ErrorDisplay1.ShowError("Uncompleted Transaction Payment list is empty or session has expired.");
                        return(false);
                    }

                    var uncompletedExpTransactionPayments = (List <StaffExpenseTransactionPayment>)Session["_uncompletedPaymentsList"];

                    if (!uncompletedExpTransactionPayments.Any())
                    {
                        ErrorDisplay1.ShowError("Uncompleted Transaction Payment list list is empty or session has expired.");
                        return(false);
                    }

                    transactionPaymentsByDate = new List <StaffExpenseTransactionPayment>();

                    if (!string.IsNullOrEmpty(txtStart.Text.Trim()) && !string.IsNullOrEmpty(txtEndDate.Text.Trim()))
                    {
                        var startDateString = DateMap.ReverseToServerDate(txtStart.Text.Trim());
                        var startDate       = DateTime.Parse(startDateString);
                        var endDateString   = DateMap.ReverseToServerDate(txtEndDate.Text.Trim());
                        var endDate         = DateTime.Parse(endDateString);

                        transactionPaymentsByDate = ServiceProvider.Instance().GetStaffExpenseTransactionPaymentServices().FilterStaffExpenseTransactionPaymentsByDateRange(uncompletedExpTransactionPayments, startDate, endDate);
                    }

                    else
                    {
                        if (!string.IsNullOrEmpty(txtEndDate.Text.Trim()) && string.IsNullOrEmpty(txtStart.Text.Trim()))
                        {
                            date = DateMap.ReverseToServerDate(txtEndDate.Text.Trim());
                            transactionPaymentsByDate = ServiceProvider.Instance().GetStaffExpenseTransactionPaymentServices().FilterStaffExpenseTransactionPaymentsByLastPaymentDate(uncompletedExpTransactionPayments, date);
                        }

                        if (string.IsNullOrEmpty(txtEndDate.Text.Trim()) && !string.IsNullOrEmpty(txtStart.Text.Trim()))
                        {
                            date = DateMap.ReverseToServerDate(txtStart.Text.Trim());
                            transactionPaymentsByDate = ServiceProvider.Instance().GetStaffExpenseTransactionPaymentServices().FilterStaffExpenseTransactionPaymentsByLastPaymentDate(uncompletedExpTransactionPayments, date);
                        }
                    }

                    if (!transactionPaymentsByDate.Any())
                    {
                        ErrorDisplay1.ShowError("No record found.");
                        return(false);
                    }
                }

                if (btnRefresh.CommandArgument == "1")
                {
                    if (Session["_completedPaymentsList"] == null)
                    {
                        ErrorDisplay1.ShowError("Uncompleted Transaction Payment list list is empty or session has expired.");
                        return(false);
                    }

                    var completedPaymentsList = (List <StaffExpenseTransactionPayment>)Session["_completedPaymentsList"];

                    if (!completedPaymentsList.Any())
                    {
                        ErrorDisplay1.ShowError("Completed Transaction Payment list is empty or session has expired.");
                        return(false);
                    }

                    transactionPaymentsByDate = new List <StaffExpenseTransactionPayment>();

                    if (!string.IsNullOrEmpty(txtStart.Text.Trim()) && !string.IsNullOrEmpty(txtEndDate.Text.Trim()))
                    {
                        var startDateString = DateMap.ReverseToServerDate(txtStart.Text.Trim());
                        var startDate       = DateTime.Parse(startDateString);
                        var endDateString   = DateMap.ReverseToServerDate(txtEndDate.Text.Trim());
                        var endDate         = DateTime.Parse(endDateString);
                        transactionPaymentsByDate = ServiceProvider.Instance().GetStaffExpenseTransactionPaymentServices().FilterStaffExpenseTransactionPaymentsByDateRange(completedPaymentsList, startDate, endDate);
                    }

                    else
                    {
                        if (string.IsNullOrEmpty(txtStart.Text.Trim()) && !string.IsNullOrEmpty(txtEndDate.Text.Trim()))
                        {
                            date = DateMap.ReverseToServerDate(txtEndDate.Text.Trim());
                            transactionPaymentsByDate = ServiceProvider.Instance().GetStaffExpenseTransactionPaymentServices().FilterStaffExpenseTransactionPaymentsByLastPaymentDate(completedPaymentsList, date);
                        }

                        if (!string.IsNullOrEmpty(txtStart.Text.Trim()) && string.IsNullOrEmpty(txtEndDate.Text.Trim()))
                        {
                            date = DateMap.ReverseToServerDate(txtStart.Text.Trim());
                            transactionPaymentsByDate = ServiceProvider.Instance().GetStaffExpenseTransactionPaymentServices().FilterStaffExpenseTransactionPaymentsByLastPaymentDate(completedPaymentsList, date);
                        }
                    }
                }

                if (btnRefresh.CommandArgument == "0")
                {
                    var allExpensePaymentsList = ServiceProvider.Instance().GetStaffExpenseTransactionPaymentServices().GetStaffExpenseTransactionPayments();

                    if (!allExpensePaymentsList.Any())
                    {
                        ErrorDisplay1.ShowError("Transaction Payment list is empty or session has expired.");
                        return(false);
                    }


                    if (!string.IsNullOrEmpty(txtStart.Text.Trim()) && !string.IsNullOrEmpty(txtEndDate.Text.Trim()))
                    {
                        var startDateString = DateMap.ReverseToServerDate(txtStart.Text.Trim());
                        var startDate       = DateTime.Parse(startDateString);
                        var endDateString   = DateMap.ReverseToServerDate(txtEndDate.Text.Trim());
                        var endDate         = DateTime.Parse(endDateString);

                        transactionPaymentsByDate = ServiceProvider.Instance().GetStaffExpenseTransactionPaymentServices().FilterStaffExpenseTransactionPaymentsByDateRange(startDate, endDate);
                    }

                    else
                    {
                        if (string.IsNullOrEmpty(txtStart.Text.Trim()) && !string.IsNullOrEmpty(txtEndDate.Text.Trim()))
                        {
                            date = DateMap.ReverseToServerDate(txtEndDate.Text.Trim());
                            transactionPaymentsByDate = ServiceProvider.Instance().GetStaffExpenseTransactionPaymentServices().FilterStaffExpenseTransactionPaymentsByLastPaymentDate(date);
                        }

                        if (!string.IsNullOrEmpty(txtStart.Text.Trim()) && string.IsNullOrEmpty(txtEndDate.Text.Trim()))
                        {
                            date = DateMap.ReverseToServerDate(txtStart.Text.Trim());
                            transactionPaymentsByDate = ServiceProvider.Instance().GetStaffExpenseTransactionPaymentServices().FilterStaffExpenseTransactionPaymentsByLastPaymentDate(date);
                        }
                    }
                }

                if (!transactionPaymentsByDate.Any())
                {
                    ErrorDisplay1.ShowError("No record found.");
                    return(false);
                }

                dgAllTransactionPayments.DataSource = transactionPaymentsByDate;
                dgAllTransactionPayments.DataBind();
                SetApprovedTransactionStyle();
                SetApprovedTransactionStyle();
                Session["_expensePaymentsList"] = transactionPaymentsByDate;
                var itemCount = transactionPaymentsByDate.Count;
                lblFilterReport.InnerHtml = itemCount + " " + " item(s) found!";
                return(true);
            }
            catch (Exception ex)
            {
                ErrorDisplay1.ShowError("An unknown error was encountered. Please try again soon or contact the Admin.");
                ErrorManager.LogApplicationError(ex.StackTrace, ex.Source, ex.Message);
                return(false);
            }
        }
Example #26
0
        private bool UpdateBeneficiary()
        {
            try
            {
                if (Session["_beneficiary"] == null)
                {
                    ConfirmAlertBox1.Attributes.CssStyle.Add("z-index", "20000001");
                    ConfirmAlertBox1.ShowMessage("Beneficiary list is empty or session has expired.", ConfirmAlertBox.PopupMessageType.Error);
                    mpeSelectDateRangePopup.Show();
                    return(false);
                }

                var beneficiary = Session["_beneficiary"] as Beneficiary;
                if (beneficiary == null || beneficiary.BeneficiaryId < 1)
                {
                    ConfirmAlertBox1.Attributes.CssStyle.Add("z-index", "20000001");
                    ConfirmAlertBox1.ShowMessage("Invalid selection!", ConfirmAlertBox.PopupMessageType.Error);
                    mpeSelectDateRangePopup.Show();
                    return(false);
                }

                beneficiary.FullName    = txtFullName.Text.Trim();
                beneficiary.CompanyName = txtCompanyName.Text.Trim();
                beneficiary.GSMNO1      = txtPhone1.Text.Trim();
                beneficiary.GSMNO2      = txtPhone2.Text.Trim();
                beneficiary.Email       = txtEmail.Text.Trim();
                beneficiary.Sex         = int.Parse(ddlSex.SelectedValue);
                beneficiary.Status      = chkBeneficiary.Checked ? 1 : 0;
                var k = ServiceProvider.Instance().GetBeneficiaryServices().UpdateBeneficiaryCheckDuplicate(beneficiary);
                if (k < 1)
                {
                    if (k == -3)
                    {
                        ConfirmAlertBox1.Attributes.CssStyle.Add("z-index", "20000001");
                        ConfirmAlertBox1.ShowMessage("The Beneficiary information already exists.", ConfirmAlertBox.PopupMessageType.Error);
                        mpeSelectDateRangePopup.Show();
                        return(false);
                    }
                    if (k == -4)
                    {
                        ConfirmAlertBox1.Attributes.CssStyle.Add("z-index", "20000001");
                        ConfirmAlertBox1.ShowMessage("Another Beneficiary with similar email already exists.", ConfirmAlertBox.PopupMessageType.Error);
                        mpeSelectDateRangePopup.Show();
                        return(false);
                    }

                    if (k == -5)
                    {
                        ConfirmAlertBox1.Attributes.CssStyle.Add("z-index", "20000001");
                        ConfirmAlertBox1.ShowMessage("Another Beneficiary with similar phone number already exists.", ConfirmAlertBox.PopupMessageType.Error);
                        mpeSelectDateRangePopup.Show();
                        return(false);
                    }

                    //if (k == -6)
                    //{
                    //    ConfirmAlertBox1.Attributes.CssStyle.Add("z-index", "20000001");
                    //    ConfirmAlertBox1.ShowMessage("Another Beneficiary with similar phone number 2 already exists.", ConfirmAlertBox.PopupMessageType.Error);
                    //    mpeSelectDateRangePopup.Show();
                    //    return false;
                    //}

                    ConfirmAlertBox1.Attributes.CssStyle.Add("z-index", "20000001");
                    ConfirmAlertBox1.ShowMessage("The Beneficiary Information could not be modified!", ConfirmAlertBox.PopupMessageType.Error);
                    mpeSelectDateRangePopup.Show();
                    return(false);
                }
                txtFullName.Text       = string.Empty;
                txtCompanyName.Text    = string.Empty;
                txtPhone1.Text         = string.Empty;
                txtPhone2.Text         = string.Empty;
                txtEmail.Text          = string.Empty;
                ddlSex.SelectedValue   = "0";
                chkBeneficiary.Checked = false;
                return(true);
            }
            catch (Exception ex)
            {
                ErrorManager.LogApplicationError(ex.StackTrace, ex.Source, ex.Message);
                ConfirmAlertBox1.ShowMessage("An unknown error was encountered. Please contact the Administrator.", ConfirmAlertBox.PopupMessageType.Error);
                return(false);
            }
        }
Example #27
0
        /**
         * Handles the incoming events
         */
        public void HandleEvent(Object sender, NotifyEvent e, HandlingPriority prority)
        {
            try
            {
                // ignore all events when leaving
                if (PluginBase.MainForm.ClosingEntirely)
                {
                    return;
                }
                // current active document
                ITabbedDocument doc = PluginBase.MainForm.CurrentDocument;

                // application start
                if (!started && e.Type == EventType.UIStarted)
                {
                    started = true;
                    PathExplorer.OnUIStarted();
                    // associate context to initial document
                    e = new NotifyEvent(EventType.SyntaxChange);
                }

                // editor ready?
                if (doc == null)
                {
                    return;
                }
                ScintillaNet.ScintillaControl sci = doc.IsEditable ? doc.SciControl : null;

                //
                //  Events always handled
                //
                bool      isValid;
                DataEvent de;
                switch (e.Type)
                {
                // caret position in editor
                case EventType.UIRefresh:
                    if (!doc.IsEditable)
                    {
                        return;
                    }
                    timerPosition.Enabled = false;
                    timerPosition.Enabled = true;
                    return;

                // key combinations
                case EventType.Keys:
                    Keys key = (e as KeyEvent).Value;
                    if (ModelsExplorer.HasFocus)
                    {
                        e.Handled = ModelsExplorer.Instance.OnShortcut(key);
                        return;
                    }
                    if (!doc.IsEditable)
                    {
                        return;
                    }
                    e.Handled = ASComplete.OnShortcut(key, sci);
                    return;

                // user-customized shortcuts
                case EventType.Shortcut:
                    de = e as DataEvent;
                    if (de.Action == "Completion.ShowHelp")
                    {
                        ASComplete.HelpKeys = (Keys)de.Data;
                        de.Handled          = true;
                    }
                    return;

                //
                // File management
                //
                case EventType.FileSave:
                    if (!doc.IsEditable)
                    {
                        return;
                    }
                    ASContext.Context.CheckModel(false);
                    // toolbar
                    isValid = ASContext.Context.IsFileValid;
                    if (isValid && !PluginBase.MainForm.SavingMultiple)
                    {
                        if (ASContext.Context.Settings.CheckSyntaxOnSave)
                        {
                            CheckSyntax(null, null);
                        }
                        ASContext.Context.RemoveClassCompilerCache();
                    }
                    return;

                case EventType.SyntaxDetect:
                    // detect Actionscript language version
                    if (!doc.IsEditable)
                    {
                        return;
                    }
                    if (doc.FileName.ToLower().EndsWith(".as"))
                    {
                        settingObject.LastASVersion = DetectActionscriptVersion(doc);
                        (e as TextEvent).Value      = settingObject.LastASVersion;
                        e.Handled = true;
                    }
                    break;

                case EventType.ApplySettings:
                case EventType.SyntaxChange:
                case EventType.FileSwitch:
                    if (!doc.IsEditable)
                    {
                        ASContext.SetCurrentFile(null, true);
                        ContextChanged();
                        return;
                    }
                    currentDoc = doc.FileName;
                    currentPos = sci.CurrentPos;
                    // check file
                    bool ignoreFile = !doc.IsEditable;
                    ASContext.SetCurrentFile(doc, ignoreFile);
                    // UI
                    ContextChanged();
                    return;

                case EventType.Completion:
                    if (ASContext.Context.IsFileValid)
                    {
                        e.Handled = true;
                    }
                    return;

                // some commands work all the time
                case EventType.Command:
                    de = e as DataEvent;
                    string command = de.Action ?? "";

                    if (command.StartsWith("ASCompletion."))
                    {
                        string cmdData = (de.Data is string) ? (string)de.Data : null;

                        // add a custom classpath
                        if (command == "ASCompletion.ClassPath")
                        {
                            Hashtable info = de.Data as Hashtable;
                            if (info != null)
                            {
                                ContextSetupInfos setup = new ContextSetupInfos();
                                setup.Platform    = (string)info["platform"];
                                setup.Lang        = (string)info["lang"];
                                setup.Version     = (string)info["version"];
                                setup.TargetBuild = (string)info["targetBuild"];
                                setup.Classpath   = (string[])info["classpath"];
                                setup.HiddenPaths = (string[])info["hidden"];
                                ASContext.SetLanguageClassPath(setup);
                                if (setup.AdditionalPaths != null)     // report custom classpath
                                {
                                    info["additional"] = setup.AdditionalPaths.ToArray();
                                }
                            }
                            e.Handled = true;
                        }

                        // send a UserClasspath
                        else if (command == "ASCompletion.GetUserClasspath")
                        {
                            Hashtable info = de.Data as Hashtable;
                            if (info != null && info.ContainsKey("language"))
                            {
                                IASContext context = ASContext.GetLanguageContext(info["language"] as string);
                                if (context != null && context.Settings != null &&
                                    context.Settings.UserClasspath != null)
                                {
                                    info["cp"] = new List <string>(context.Settings.UserClasspath);
                                }
                            }
                            e.Handled = true;
                        }
                        // update a UserClasspath
                        else if (command == "ASCompletion.SetUserClasspath")
                        {
                            Hashtable info = de.Data as Hashtable;
                            if (info != null && info.ContainsKey("language") && info.ContainsKey("cp"))
                            {
                                IASContext    context = ASContext.GetLanguageContext(info["language"] as string);
                                List <string> cp      = info["cp"] as List <string>;
                                if (cp != null && context != null && context.Settings != null)
                                {
                                    string[] pathes = new string[cp.Count];
                                    cp.CopyTo(pathes);
                                    context.Settings.UserClasspath = pathes;
                                }
                            }
                            e.Handled = true;
                        }
                        // send the language's default compiler path
                        else if (command == "ASCompletion.GetCompilerPath")
                        {
                            Hashtable info = de.Data as Hashtable;
                            if (info != null && info.ContainsKey("language"))
                            {
                                IASContext context = ASContext.GetLanguageContext(info["language"] as string);
                                if (context != null)
                                {
                                    info["compiler"] = context.GetCompilerPath();
                                }
                            }
                            e.Handled = true;
                        }

                        // show a language's compiler settings
                        else if (command == "ASCompletion.ShowSettings")
                        {
                            e.Handled = true;
                            IASContext context = ASContext.GetLanguageContext(cmdData);
                            if (context == null)
                            {
                                return;
                            }
                            string filter = "";
                            string name   = "";
                            switch (cmdData.ToUpper())
                            {
                            case "AS2": name = "AS2Context"; filter = "SDK"; break;

                            case "AS3": name = "AS3Context"; filter = "SDK"; break;

                            case "HAXE": name = "HaxeContext"; filter = "SDK"; break;

                            default: name = cmdData.ToUpper() + "Context"; break;
                            }
                            PluginBase.MainForm.ShowSettingsDialog(name, filter);
                        }

                        // Open types explorer dialog
                        else if (command == "ASCompletion.TypesExplorer")
                        {
                            TypesExplorer(null, null);
                        }

                        // call the Flash IDE
                        else if (command == "ASCompletion.CallFlashIDE")
                        {
                            if (flashErrorsWatcher == null)
                            {
                                flashErrorsWatcher = new FlashErrorsWatcher();
                            }
                            e.Handled = Commands.CallFlashIDE.Run(settingObject.PathToFlashIDE, cmdData);
                        }

                        // create Flash 8+ trust file
                        else if (command == "ASCompletion.CreateTrustFile")
                        {
                            if (cmdData != null)
                            {
                                string[] args = cmdData.Split(';');
                                if (args.Length == 2)
                                {
                                    e.Handled = Commands.CreateTrustFile.Run(args[0], args[1]);
                                }
                            }
                        }

                        //
                        else if (command == "ASCompletion.GetClassPath")
                        {
                            if (cmdData != null)
                            {
                                string[] args = cmdData.Split(';');
                                if (args.Length == 1)
                                {
                                    FileModel  model  = ASContext.Context.GetFileModel(args[0]);
                                    ClassModel aClass = model.GetPublicClass();
                                    if (!aClass.IsVoid())
                                    {
                                        Clipboard.SetText(aClass.QualifiedName);
                                        e.Handled = true;
                                    }
                                }
                            }
                        }

                        // Return requested language SDK list
                        else if (command == "ASCompletion.InstalledSDKs")
                        {
                            Hashtable info = de.Data as Hashtable;
                            if (info != null && info.ContainsKey("language"))
                            {
                                IASContext context = ASContext.GetLanguageContext(info["language"] as string);
                                if (context != null)
                                {
                                    info["sdks"] = context.Settings.InstalledSDKs;
                                }
                            }
                            e.Handled = true;
                        }
                    }

                    // Create a fake document from a FileModel
                    else if (command == "ProjectManager.OpenVirtualFile")
                    {
                        string cmdData = de.Data as string;
                        if (reVirtualFile.IsMatch(cmdData))
                        {
                            string[] path     = Regex.Split(cmdData, "::");
                            string   fileName = path[0] + Path.DirectorySeparatorChar
                                                + path[1].Replace('.', Path.DirectorySeparatorChar).Replace("::", Path.DirectorySeparatorChar.ToString());
                            FileModel found = ModelsExplorer.Instance.OpenFile(fileName);
                            if (found != null)
                            {
                                e.Handled = true;
                            }
                        }
                    }
                    else if (command == "ProjectManager.UserRefreshTree")
                    {
                        ASContext.Context.UserRefreshRequest();
                    }
                    break;
                }

                //
                // Actionscript context specific
                //
                if (ASContext.Context.IsFileValid)
                {
                    switch (e.Type)
                    {
                    case EventType.ProcessArgs:
                        TextEvent te = (TextEvent)e;
                        if (reArgs.IsMatch(te.Value))
                        {
                            // resolve current element
                            Hashtable details = ASComplete.ResolveElement(sci, null);
                            te.Value = ArgumentsProcessor.Process(te.Value, details);

                            if (te.Value.IndexOf("$") >= 0 && reCostlyArgs.IsMatch(te.Value))
                            {
                                ASResult result = ASComplete.CurrentResolvedContext.Result ?? new ASResult();
                                details = new Hashtable();
                                // Get closest list (Array or Vector)
                                string closestListName = "", closestListItemType = "";
                                ASComplete.FindClosestList(ASContext.Context, result.Context, sci.LineFromPosition(sci.CurrentPos), ref closestListName, ref closestListItemType);
                                details.Add("TypClosestListName", closestListName);
                                details.Add("TypClosestListItemType", closestListItemType);
                                // get free iterator index
                                string iterator = ASComplete.FindFreeIterator(ASContext.Context, ASContext.Context.CurrentClass, result.Context);
                                details.Add("ItmUniqueVar", iterator);
                                te.Value = ArgumentsProcessor.Process(te.Value, details);
                            }
                        }
                        break;

                    // menu commands
                    case EventType.Command:
                        string command = (e as DataEvent).Action ?? "";
                        if (command.StartsWith("ASCompletion."))
                        {
                            string cmdData = (e as DataEvent).Data as string;
                            // run MTASC
                            if (command == "ASCompletion.CustomBuild")
                            {
                                if (cmdData != null)
                                {
                                    ASContext.Context.RunCMD(cmdData);
                                }
                                else
                                {
                                    ASContext.Context.RunCMD("");
                                }
                                e.Handled = true;
                            }

                            // build the SWF using MTASC
                            else if (command == "ASCompletion.QuickBuild")
                            {
                                ASContext.Context.BuildCMD(false);
                                e.Handled = true;
                            }

                            // resolve element under cusor and open declaration
                            else if (command == "ASCompletion.GotoDeclaration")
                            {
                                ASComplete.DeclarationLookup(sci);
                                e.Handled = true;
                            }

                            // resolve element under cursor and send a CustomData event
                            else if (command == "ASCompletion.ResolveElement")
                            {
                                ASComplete.ResolveElement(sci, cmdData);
                                e.Handled = true;
                            }
                            else if (command == "ASCompletion.MakeIntrinsic")
                            {
                                ASContext.Context.MakeIntrinsic(cmdData);
                                e.Handled = true;
                            }

                            // alternative to default shortcuts
                            else if (command == "ASCompletion.CtrlSpace")
                            {
                                ASComplete.OnShortcut(Keys.Control | Keys.Space, ASContext.CurSciControl);
                                e.Handled = true;
                            }
                            else if (command == "ASCompletion.CtrlShiftSpace")
                            {
                                ASComplete.OnShortcut(Keys.Control | Keys.Shift | Keys.Space, ASContext.CurSciControl);
                                e.Handled = true;
                            }
                            else if (command == "ASCompletion.CtrlAltSpace")
                            {
                                ASComplete.OnShortcut(Keys.Control | Keys.Alt | Keys.Space, ASContext.CurSciControl);
                                e.Handled = true;
                            }
                            else if (command == "ASCompletion.ContextualGenerator")
                            {
                                if (ASContext.HasContext && ASContext.Context.IsFileValid)
                                {
                                    ASGenerator.ContextualGenerator(ASContext.CurSciControl);
                                }
                            }
                        }
                        return;

                    case EventType.ProcessEnd:
                        string procResult = (e as TextEvent).Value;
                        ASContext.Context.OnProcessEnd(procResult);
                        break;
                    }
                }
            }
            catch (Exception ex)
            {
                ErrorManager.ShowError(ex);
            }
        }
Example #28
0
        private void SpinnerWatcherOnRunWorkerCompleted(object sender, RunWorkerCompletedEventArgs runWorkerCompletedEventArgs)
        {
            try
            {
                if (_states == null || !_states.Any())
                {
                    MessageBox.Show(@"State list is empty!", "", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }

                if (_localAreas == null || !_localAreas.Any())
                {
                    MessageBox.Show(@"Local govt list is empty!", "", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }

                if (_occupations == null || !_occupations.Any())
                {
                    MessageBox.Show(@"Occupation list is empty!", "", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }

                if (_marital == null || !_marital.Any())
                {
                    MessageBox.Show(@"Marital Status list is empty!", "", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }

                _states.Insert(0, new State {
                    StateId = 0, Name = @"-- Please Select --"
                });
                bdsState.DataSource    = new List <State>();
                bdsState.DataSource    = _states;
                cmbState.SelectedIndex = 0;

                _occupations.Insert(0, new Occupation {
                    OccupationId = 0, Name = @"-- Please Select --"
                });
                bdsOccupation.DataSource    = new List <Occupation>();
                bdsOccupation.DataSource    = _occupations;
                cmbOccupation.SelectedIndex = 0;

                _marital.Insert(0, new NameAndValueObject {
                    Id = 0, Name = @"-- Please Select --"
                });
                bdsMaritalStatus.DataSource    = new List <NameAndValueObject>();
                bdsMaritalStatus.DataSource    = _marital;
                cmbMaritalStatus.SelectedIndex = 0;

                bindItems();
                _firstLoad = false;
                //_maritalStatus.Insert(0, new MaritalStatus { MaritalStatusId = 0, Name = @"-- Please Select --" });
                //bdsMaritalStatus.DataSource = new List<MaritalStatus>();
                //bdsMaritalStatus.DataSource = _maritalStatus;
                //cmbMaritalStatus.SelectedIndex = 0;

                //RetrieveCacheInfo();
            }
            catch (Exception ex)
            {
                ErrorManager.LogApplicationError(ex.StackTrace, ex.Source, ex.Message);
            }
        }
        /// <summary>
        /// Filter the completion list with the letter typed
        /// </summary>
        static public void FindWordStartingWith(String word)
        {
            if (word == null)
            {
                word = "";
            }
            Int32 len       = word.Length;
            Int32 maxLen    = 0;
            Int32 lastScore = 0;

            /// <summary>
            /// FILTER ITEMS
            /// </summary>
            if (PluginBase.MainForm.Settings.AutoFilterList || fullList)
            {
                List <ICompletionListItem> found;
                if (len == 0)
                {
                    found            = allItems;
                    lastIndex        = 0;
                    exactMatchInList = false;
                    smartMatchInList = true;
                }
                else
                {
                    List <ItemMatch> temp = new List <ItemMatch>(allItems.Count);
                    Int32            n    = allItems.Count;
                    Int32            i    = 0;
                    Int32            score;
                    lastScore = 99;
                    ICompletionListItem item;
                    exactMatchInList = false;
                    smartMatchInList = false;
                    while (i < n)
                    {
                        item = allItems[i];
                        // compare item's label with the searched word
                        score = SmartMatch(item.Label, word, len);
                        if (score > 0)
                        {
                            // first match found
                            if (!smartMatchInList || score < lastScore)
                            {
                                lastScore        = score;
                                lastIndex        = temp.Count;
                                smartMatchInList = true;
                                exactMatchInList = score < 5 && word == CompletionList.word;
                            }
                            temp.Add(new ItemMatch(score, item));
                            if (item.Label.Length > maxLen)
                            {
                                widestLabel = item.Label;
                                maxLen      = widestLabel.Length;
                            }
                        }
                        else if (fullList)
                        {
                            temp.Add(new ItemMatch(0, item));
                        }
                        i++;
                    }
                    // filter
                    found = new List <ICompletionListItem>(temp.Count);
                    for (int j = 0; j < temp.Count; j++)
                    {
                        if (j == lastIndex)
                        {
                            lastIndex = found.Count;
                        }
                        if (temp[j].Score - lastScore < 3)
                        {
                            found.Add(temp[j].Item);
                        }
                    }
                }
                // no match?
                if (!smartMatchInList)
                {
                    if (autoHideList && PluginBase.MainForm.Settings.EnableAutoHide && (len == 0 || len > 255))
                    {
                        Hide('\0');
                    }
                    else
                    {
                        // smart match
                        if (word.Length > 0)
                        {
                            FindWordStartingWith(word.Substring(0, len - 1));
                        }
                        if (!smartMatchInList && autoHideList && PluginBase.MainForm.Settings.EnableAutoHide)
                        {
                            Hide('\0');
                        }
                    }
                    return;
                }
                fullList = false;
                // reset timer
                if (tempo.Enabled)
                {
                    tempo.Enabled = false;
                    tempo.Enabled = true;
                }
                // is update needed?
                if (completionList.Items.Count == found.Count)
                {
                    int  n       = completionList.Items.Count;
                    bool changed = false;
                    for (int i = 0; i < n; i++)
                    {
                        if (completionList.Items[i] != found[i])
                        {
                            changed = true;
                            break;
                        }
                    }
                    if (!changed)
                    {
                        // preselected item
                        if (defaultItem != null)
                        {
                            if (lastScore > 3 || (lastScore > 2 && defaultItem.Label.StartsWith(word, StringComparison.OrdinalIgnoreCase)))
                            {
                                lastIndex = lastIndex = TestDefaultItem(lastIndex, word, len);
                            }
                        }
                        completionList.SelectedIndex = lastIndex;
                        return;
                    }
                }
                // update
                try
                {
                    completionList.BeginUpdate();
                    completionList.Items.Clear();
                    foreach (ICompletionListItem item in found)
                    {
                        completionList.Items.Add(item);
                        if (item.Label.Length > maxLen)
                        {
                            widestLabel = item.Label;
                            maxLen      = widestLabel.Length;
                        }
                    }
                    Int32 topIndex = lastIndex;
                    if (defaultItem != null)
                    {
                        if (lastScore > 3 || (lastScore > 2 && defaultItem.Label.StartsWith(word, StringComparison.OrdinalIgnoreCase)))
                        {
                            lastIndex = TestDefaultItem(lastIndex, word, len);
                        }
                    }
                    // select first item
                    completionList.TopIndex      = topIndex;
                    completionList.SelectedIndex = lastIndex;
                }
                catch (Exception ex)
                {
                    Hide('\0');
                    ErrorManager.ShowError(/*"Completion list populate error.", */ ex);
                    return;
                }
                finally
                {
                    completionList.EndUpdate();
                }
                // update list
                if (!tempo.Enabled)
                {
                    DisplayList(null, null);
                }
            }
            /// <summary>
            /// NO FILTER
            /// </summary>
            else
            {
                int n = completionList.Items.Count;
                ICompletionListItem item;
                while (lastIndex < n)
                {
                    item = completionList.Items[lastIndex] as ICompletionListItem;
                    if (String.Compare(item.Label, 0, word, 0, len, true) == 0)
                    {
                        completionList.SelectedIndex = lastIndex;
                        completionList.TopIndex      = lastIndex;
                        exactMatchInList             = true;
                        return;
                    }
                    lastIndex++;
                }
                // no match
                if (autoHideList && PluginBase.MainForm.Settings.EnableAutoHide)
                {
                    Hide('\0');
                }
                else
                {
                    exactMatchInList = false;
                }
            }
        }
Example #30
0
        private bool ValidateSubmission()
        {
            try
            {
                if (txtSurname.Text.Trim().Length < 3)
                {
                    MessageBox.Show(@"Surname cannot be empty", @"Validation Error", MessageBoxButtons.OK, MessageBoxIcon.Hand);
                    txtSurname.Focus();
                    return(false);
                }
                if (txtFirstName.Text.Trim().Length < 3)
                {
                    MessageBox.Show(@"First name cannot be empty", @"Validation Error", MessageBoxButtons.OK, MessageBoxIcon.Hand);
                    txtFirstName.Focus();
                    return(false);
                }

                // Validate D.O.B
                if (dtpDateOfBirth.Value.Date == DateTime.Now.Date)
                {
                    MessageBox.Show(@"Please select valid date of birth", @"Process Validation", MessageBoxButtons.OK, MessageBoxIcon.Hand);
                    return(false);
                }

                // Validate Gender
                if (!rbbFemale.Checked && !rbbMale.Checked)
                {
                    MessageBox.Show(@"Please select valid gender", @"Process Validation", MessageBoxButtons.OK, MessageBoxIcon.Hand);
                    return(false);
                }

                if (cmbOccupation.SelectedValue == null)
                {
                    MessageBox.Show(@"Please select valid occupation", @"Process Validation", MessageBoxButtons.OK, MessageBoxIcon.Hand);
                    cmbOccupation.Focus();
                    return(false);
                }

                if (cmbOccupation.SelectedValue != null && int.Parse(cmbOccupation.SelectedValue.ToString()) < 1)
                {
                    MessageBox.Show(@"Please select valid occupation", @"Process Validation", MessageBoxButtons.OK, MessageBoxIcon.Hand);
                    cmbOccupation.Focus();
                    return(false);
                }

                if (cmbMaritalStatus.SelectedValue == null)
                {
                    MessageBox.Show(@"Please select valid marital status", @"Process Validation", MessageBoxButtons.OK, MessageBoxIcon.Hand);
                    cmbMaritalStatus.Focus();
                    return(false);
                }

                if (cmbMaritalStatus.SelectedValue != null && int.Parse(cmbMaritalStatus.SelectedValue.ToString()) < 1)
                {
                    MessageBox.Show(@"Please select valid marital status", @"Process Validation", MessageBoxButtons.OK, MessageBoxIcon.Hand);
                    cmbMaritalStatus.Focus();
                    return(false);
                }

                if (txtHomeAddress.Text.Trim().Length < 5)
                {
                    MessageBox.Show(@"Residential address cannot be empty and must be more than 5 character long", @"Validation Error", MessageBoxButtons.OK, MessageBoxIcon.Hand);
                    txtHomeAddress.Focus();
                    return(false);
                }

                if (cmbState.SelectedValue == null)
                {
                    MessageBox.Show(@"Please select valid state of origin", @"Process Validation", MessageBoxButtons.OK, MessageBoxIcon.Hand);
                    cmbState.Focus();
                    return(false);
                }

                if (cmbState.SelectedValue != null && int.Parse(cmbState.SelectedValue.ToString()) < 1)
                {
                    MessageBox.Show(@"Please select valid state of origin", @"Process Validation", MessageBoxButtons.OK, MessageBoxIcon.Hand);
                    cmbState.Focus();
                    return(false);
                }

                if (cmbLocalArea.SelectedValue == null)
                {
                    MessageBox.Show(@"Please select valid LGA", @"Process Validation", MessageBoxButtons.OK, MessageBoxIcon.Hand);
                    cmbLocalArea.Focus();
                    return(false);
                }

                if (cmbLocalArea.SelectedValue != null && int.Parse(cmbLocalArea.SelectedValue.ToString()) < 1)
                {
                    MessageBox.Show(@"Please select valid LGA", @"Process Validation", MessageBoxButtons.OK, MessageBoxIcon.Hand);
                    cmbLocalArea.Focus();
                    return(false);
                }


                //if (txtMobileNo.Text.Trim().Equals(string.Empty))
                //{
                //    MessageBox.Show(@"Mobile number cannot be empty", @"Validation Error", MessageBoxButtons.OK, MessageBoxIcon.Hand);
                //    txtMobileNo.Focus();
                //    return false;
                //}

                //if (!GSMHelper.ValidateMobileNumber(this.txtMobileNumber.Text))
                //{
                //    MessageBox.Show("Invalid Station Mobile Number", "Validation Error", MessageBoxButtons.OK, MessageBoxIcon.Hand);
                //    return false;
                //}

                //if (txtMobileNo.Text.Length >= 7 && txtMobileNo.Text.Length <= 15)
                //    return true;
                //    MessageBox.Show(@"Invalid Mobile Number", @"Validation Error", MessageBoxButtons.OK, MessageBoxIcon.Hand);
                //    txtMobileNo.Focus();
                //if (picImage.Image != null)
                return(true);
                //MessageBox.Show(@"Please take the image of the person", @"Validation Error", MessageBoxButtons.OK, MessageBoxIcon.Hand);
                //return false;
            }
            catch (Exception ex)
            {
                ErrorManager.LogApplicationError(ex.StackTrace, ex.Source, ex.Message);
                MessageBox.Show(@"Unable to validate your inputs. Please check all inputs and try again later", @"Process Error", MessageBoxButtons.OK, MessageBoxIcon.Hand);
                return(false);
            }
        }
Example #31
0
 public QuerySyntaxParser(ITokenStream stream, ErrorManager em)
     : this(stream)
 {
     _errorManager = em;
 }
        public SettingRegRespObj AddLocalArea(RegLocalAreaObj regObj)
        {
            var response = new SettingRegRespObj
            {
                Status = new APIResponseStatus
                {
                    IsSuccessful = false,
                    Message      = new APIResponseMessage()
                }
            };

            try
            {
                if (regObj.Equals(null))
                {
                    response.Status.Message.FriendlyMessage  = "Error Occurred! Unable to proceed with your request";
                    response.Status.Message.TechnicalMessage = "Registration Object is empty / invalid";
                    return(response);
                }

                if (!EntityValidatorHelper.Validate(regObj, out var valResults))
                {
                    var errorDetail = new StringBuilder();
                    if (!valResults.IsNullOrEmpty())
                    {
                        errorDetail.AppendLine("Following error occurred:");
                        valResults.ForEachx(m => errorDetail.AppendLine(m.ErrorMessage));
                    }

                    else
                    {
                        errorDetail.AppendLine(
                            "Validation error occurred! Please check all supplied parameters and try again");
                    }
                    response.Status.Message.FriendlyMessage  = errorDetail.ToString();
                    response.Status.Message.TechnicalMessage = errorDetail.ToString();
                    response.Status.IsSuccessful             = false;
                    return(response);
                }

                if (!HelperMethods.IsUserValid(regObj.AdminUserId, regObj.SysPathCode,
                                               HelperMethods.getSeniorAccountant(), ref response.Status.Message))
                {
                    return(response);
                }

                if (IsLocalAreaDuplicate(regObj.Name, 1, ref response))
                {
                    return(response);
                }

                var localArea = new LocalArea
                {
                    Name    = regObj.Name,
                    StateId = regObj.StateId,
                    Status  = (ItemStatus)regObj.Status
                };

                var added = _repository.Add(localArea);

                _uoWork.SaveChanges();

                if (added.LocalAreaId < 1)
                {
                    response.Status.Message.FriendlyMessage =
                        "Error Occurred! Unable to complete your request. Please try again later";
                    response.Status.Message.TechnicalMessage = "Unable to save to database";
                    return(response);
                }
                resetCache();
                response.Status.IsSuccessful = true;
                response.SettingId           = added.LocalAreaId;
            }
            catch (DbEntityValidationException ex)
            {
                ErrorManager.LogApplicationError(ex.StackTrace, ex.Source, ex.Message);
                response.Status.Message.FriendlyMessage  = "Error Occurred! Please try again later";
                response.Status.Message.TechnicalMessage = "Error: " + ex.GetBaseException().Message;
                response.Status.IsSuccessful             = false;
                return(response);
            }
            catch (Exception ex)
            {
                ErrorManager.LogApplicationError(ex.StackTrace, ex.Source, ex.Message);
                response.Status.Message.FriendlyMessage  = "Error Occurred! Please try again later";
                response.Status.Message.TechnicalMessage = "Error: " + ex.GetBaseException().Message;
                response.Status.IsSuccessful             = false;
                return(response);
            }
            return(response);
        }
Example #33
0
 /// <summary>
 ///  Display errors from Artistic Style.
 /// </summary>
 private void OnAStyleError(int errorNumber, String errorMessage)
 {
     ErrorManager.ShowError(errorMessage, null);
 }
Example #34
0
        /** <summary>
         * Load a template from dir or group file.  Group file is given
         * precedence over dir with same name. <paramref name="name"/> is
         * always fully qualified.
         * </summary>
         */
        protected override CompiledTemplate Load(string name)
        {
            if (Verbose)
            {
                Console.WriteLine("STGroupDir.load(" + name + ")");
            }

            string parent = Utility.GetParent(name); // must have parent; it's fully-qualified
            string prefix = Utility.GetPrefix(name);

            //      if (parent.isEmpty()) {
            //          // no need to check for a group file as name has no parent
            //            return loadTemplateFile("/", name+TemplateFileExtension); // load t.st file
            //      }

            if (!Path.IsPathRooted(parent))
            {
                throw new ArgumentException();
            }

            Uri groupFileURL = null;

            try
            {
                // see if parent of template name is a group file
                groupFileURL = new Uri(TemplateName.GetTemplatePath(root.LocalPath, parent) + GroupFileExtension);
            }
            catch (UriFormatException e)
            {
                ErrorManager.InternalError(null, "bad URL: " + TemplateName.GetTemplatePath(root.LocalPath, parent) + GroupFileExtension, e);
                return(null);
            }

            if (!File.Exists(groupFileURL.LocalPath))
            {
                string unqualifiedName = Path.GetFileName(name);
                return(LoadTemplateFile(prefix, unqualifiedName + TemplateFileExtension)); // load t.st file
            }
#if false
            InputStream @is = null;
            try
            {
                @is = groupFileURL.openStream();
            }
            catch (FileNotFoundException fnfe)
            {
                // must not be in a group file
                return(loadTemplateFile(parent, name + TemplateFileExtension)); // load t.st file
            }
            catch (IOException ioe)
            {
                errMgr.internalError(null, "can't load template file " + name, ioe);
            }

            try
            {
                // clean up
                if (@is != null)
                {
                    @is.close();
                }
            }
            catch (IOException ioe)
            {
                errMgr.internalError(null, "can't close template file stream " + name, ioe);
            }
#endif

            LoadGroupFile(prefix, groupFileURL.LocalPath);

            return(RawGetTemplate(name));
        }
Example #35
0
 public QueryExecutor(ErrorManager errorManager)
     : this(errorManager, new List<IQupidJoinPlugin>())
 {
 }
Example #36
0
        static void Main(string[] args)
        {
            var errorManager = new ErrorManager();

            string inputQueue = null;
            string messageId  = null;

            if (args != null && args.Length > 0)
            {
                inputQueue = args[0];
            }

            if (args != null && args.Length > 1)
            {
                messageId = args[1];
            }

            var script = true;

            if (inputQueue == null)
            {
                Console.WriteLine("NServiceBus ReturnToSource for MSMQ");
                Console.WriteLine("by Particular Software Ltd. \n");

                Console.WriteLine("Please enter the error queue you would like to use:");
                inputQueue = Console.ReadLine();
                if (string.IsNullOrWhiteSpace(inputQueue))
                {
                    Console.WriteLine("No error queue specified");
                    Console.WriteLine("\nPress 'Enter' to exit.");
                    Console.ReadLine();
                    return;
                }
                script = false;
            }

            var errorQueueAddress = Address.Parse(inputQueue);

            if (!IsLocalIpAddress(errorQueueAddress.Machine))
            {
                Console.WriteLine("Input queue [{0}] resides on a remote machine: [{1}].", errorQueueAddress.Queue, errorQueueAddress.Machine);
                Console.WriteLine("Due to networking load, it is advised to refrain from using ReturnToSourceQueue on a remote error queue, unless the error queue resides on a clustered machine.");
                if (!script)
                {
                    Console.WriteLine(
                        "Press 'y' if the error queue resides on a Clustered Machine, otherwise press any key to exit.");
                    if (Console.ReadKey().Key.ToString().ToLower() != "y")
                    {
                        return;
                    }
                }
                Console.WriteLine(string.Empty);
                errorManager.ClusteredQueue = true;
            }

            if (messageId == null)
            {
                Console.WriteLine("Please enter the id of the message you'd like to return to its source queue, or 'all' to do so for all messages in the queue.");
                messageId = Console.ReadLine();
            }

            errorManager.InputQueue = errorQueueAddress;
            Console.WriteLine("Attempting to return message to source queue. Queue: [{0}], message id: [{1}]. Please stand by.",
                              errorQueueAddress, messageId);

            try
            {
                if (messageId == "all")
                {
                    errorManager.ReturnAll();
                }
                else
                {
                    errorManager.ReturnMessageToSourceQueue(messageId);
                }

                if (args == null || args.Length == 0)
                {
                    Console.WriteLine("Press 'Enter' to exit.");
                    Console.ReadLine();
                }
            }
            catch (Exception e)
            {
                Console.WriteLine("Could not return message to source queue. Reason: " + e.Message);
                Console.WriteLine(e.StackTrace);

                Console.WriteLine("\nPress 'Enter' to exit.");
                Console.ReadLine();
            }
        }
Example #37
0
 public Compiler(ICollectionFinder collectionFinder, ErrorManager errorManager)
 {
     MaxCollectionSizeWithNoIndex = DefaultMaxSize;
     _collectionFinder = collectionFinder;
     _errorManager = errorManager;
 }
    static void Main(string[] args)
    {
        var errorManager = new ErrorManager();

        string inputQueue = null;
        string messageId = null;

        if (args != null && args.Length > 0)
            inputQueue = args[0];

        if (args != null && args.Length > 1)
            messageId = args[1];

        var script = true;

        if (inputQueue == null)
        {
            Console.WriteLine("NServiceBus ReturnToSource for MSMQ");
            Console.WriteLine("by Particular Software Ltd. \n");

            Console.WriteLine("Please enter the error queue you would like to use:");
            inputQueue = Console.ReadLine();
            if (string.IsNullOrWhiteSpace(inputQueue))
            {
                Console.WriteLine("No error queue specified");
                Console.WriteLine("\nPress 'Enter' to exit.");
                Console.ReadLine();
                return;
            }
            script = false;
        }

        var errorQueueAddress = MsmqAddress.Parse(inputQueue);

        if (!IsLocalIpAddress(errorQueueAddress.Machine))
        {
            Console.WriteLine("Input queue [{0}] resides on a remote machine: [{1}].", errorQueueAddress.Queue, errorQueueAddress.Machine);
            Console.WriteLine("Due to networking load, it is advised to refrain from using ReturnToSourceQueue on a remote error queue, unless the error queue resides on a clustered machine.");
            if (!script)
            {
                Console.WriteLine(
                    "Press 'y' if the error queue resides on a Clustered Machine, otherwise press any key to exit.");
                if (Console.ReadKey().Key.ToString().ToLower() != "y")
                    return;
            }
            Console.WriteLine(string.Empty);
            errorManager.ClusteredQueue = true;
        }

        if (messageId == null)
        {
            Console.WriteLine("Please enter the id of the message you'd like to return to its source queue, or 'all' to do so for all messages in the queue.");
            messageId = Console.ReadLine();
        }

        errorManager.InputQueue = errorQueueAddress;
        Console.WriteLine("Attempting to return message to source queue. Queue: [{0}], message id: [{1}]. Please stand by.",
            errorQueueAddress, messageId);

        try
        {
            if (messageId == "all")
                errorManager.ReturnAll();
            else
                errorManager.ReturnMessageToSourceQueue(messageId);

            if (args == null || args.Length == 0)
            {
                Console.WriteLine("Press 'Enter' to exit.");
                Console.ReadLine();
            }
        }
        catch (Exception e)
        {
            Console.WriteLine("Could not return message to source queue. Reason: " + e.Message);
            Console.WriteLine(e.StackTrace);

            Console.WriteLine("\nPress 'Enter' to exit.");
            Console.ReadLine();
        }
    }