Example #1
0
 public static string ReturnCode(ReturnCodes code)
 { 
     string result = string.Empty;
     switch (code)
     {
         case ReturnCodes.AddressNotFound:
             result = "Address was not found";
             break;
         case ReturnCodes.DefaultResponse:
             break;
         case ReturnCodes.ExactMatch:
             result = "Exact match found";
             break;
         case ReturnCodes.InvalidAddress:
             result = "Invalid Address";
             break;
         case ReturnCodes.InvalidCity:
             result = "Invalid City";
             break;
         case ReturnCodes.InvalidStateCode:
             result = "Invalid StateCode";
             break;
         case ReturnCodes.InvalidZipCode:
             result = "Invalid ZipCode";
             break;
         case ReturnCodes.MultipleResponse:
             result = "Multiple Response";
             break;
         default:
             break;
     }
     return result;
 }
Example #2
0
        public async Task <XElement> Page(long pageId, string sessionKey, long requestId)
        {
            #region Заглушка
            var hubConn  = new HubConnection(Settings.Default.ResponseHubUrl);
            var hubProxy = hubConn.CreateHubProxy("ResponseHub");
            await hubConn.Start();

            ObjectAccessResult access = new ObjectAccessResult()
            {
                Id     = pageId,
                Access = new CheckAccessResult()
                {
                    Read           = true,
                    Update         = true,
                    InsertChildren = true,
                    Delete         = true
                }
            };

            hubProxy.Invoke("OperationCallback", sessionKey, requestId,
                            ReturnCodes.BuildRcAnswer(0, "Успешно", ObjectAccessResult.ToXElement(access)));
            return(ReturnCodes.BuildRcAnswer(0, "Успешно"));

            #endregion
        }
        /// <summary>
        /// Processes window message and indicates wether it is a twain event or not
        /// </summary>
        /// <param name="m">Message send to the application</param>
        /// <returns>The translates TwainMessage if suitable</returns>
        internal Messages ProcessMessage(ref System.Windows.Forms.Message m)
        {
            Messages result = Messages.Null;

            if (dataSource.IsOpen)
            {
                int pos = User32.GetMessagePos();

                windowsMessage.hwnd    = m.HWnd;
                windowsMessage.message = m.Msg;
                windowsMessage.wParam  = m.WParam;
                windowsMessage.lParam  = m.LParam;
                windowsMessage.time    = User32.GetMessageTime();
                windowsMessage.pt_x    = (short)pos;
                windowsMessage.pt_y    = (short)(pos >> 16);

                Marshal.StructureToPtr(windowsMessage, interopStruct.WindowsMessagePointer, false);
                interopStruct.Message = 0;
                ReturnCodes rc = Twain32.ProcessMessage(dataSourceManager.Identity, dataSource.Identity, ref interopStruct);

                if (rc == ReturnCodes.DataSourceEvent)
                {
                    result = (Messages)interopStruct.Message;
                }
            }

            return(result);
        }
Example #4
0
        static int Main(string[] args)
        {
            ReturnCodes code  = 0;
            InputType   type  = InputType.Empty;
            string      input = args.Length < 1 ? null : args[0].ToLower().Substring(0, 1);

            if (input != null)
            {
                type = Regex.Match(input, "[a-zA-Z]").Success ? InputType.Switch : InputType.Invalid;
            }

            switch (type)
            {
            case InputType.Switch:
                string        command    = args[0];
                List <string> paramaters = GetParameters(args);
                code = CommandManager.SelectSwitch(command, paramaters) ? ReturnCodes.SwitchSucceed : ReturnCodes.SwitchFailed;
                break;

            case InputType.Empty:
                Console.WriteLine("Welcome to VBA! Write 'help' for more information or try 'VBA generate project'.");
                code = ReturnCodes.NoInput;
                break;

            case InputType.Invalid:
                Console.WriteLine($"Input '{args[0]}' invalid");
                code = ReturnCodes.NonValidInput;
                break;
            }

            return((int)code);
        }
        public override string ToString()
        {
            var returnCodesText = string.Join(",", ReturnCodes.Select(f => f.ToString()));
            var reasonCodesText = string.Join(",", ReasonCodes.Select(f => f.ToString()));

            return(string.Concat("SubAck: [PacketIdentifier=", PacketIdentifier, "] [ReturnCodes=", returnCodesText, "] [ReasonCode=", reasonCodesText, "]"));
        }
        internal static ReturnCodes LoadSequencesFromFiles(ref Alignment alignmentObject, bool append, string[] fileNames, out List <Tuple <string, int, ReturnCodes> > fileErrors)
        // This method provides the main interface for loading sequences. It takes an array of file names and calls LoadSequencesFromFile.
        // It then checks the return codes and the number of sequences loaded, then clears the alignment if not appending, then adds the
        // new sequences to the alignment. In addition to the main return code, it returns as an output parameter a list containing the error codes.
        {
            ReturnCodes returnCode = ReturnCodes.OK;

            fileErrors = new List <Tuple <string, int, ReturnCodes> >();
            //List<Tuple<Macromolecule, int[]>> loadedAlignedMacromolecules = new List<Tuple<Macromolecule, int[]>>();
            List <AlignedMacromolecule> loadedAlignedMacromolecules = new List <AlignedMacromolecule>();

            foreach (string fileName in fileNames)
            {
                //List<Tuple<Macromolecule, int[]>> fileAlignedMacromolecules;
                List <AlignedMacromolecule> fileAlignedMacromolecules;
                ReturnCodes fileReturnCode = ReturnCodes.OK;
                fileReturnCode = LoadSequencesFromFile(fileName, out fileAlignedMacromolecules);

                if (fileReturnCode != ReturnCodes.OK)
                {
                    // Add any errors to the array
                    fileErrors.Add(Tuple.Create(fileName, fileAlignedMacromolecules.Count, fileReturnCode));
                    returnCode = ReturnCodes.FileErrors;
                }

                if (fileReturnCode == ReturnCodes.OK || fileReturnCode == ReturnCodes.EmptySequencesRemoved)
                {
                    // These codes mean it is okay to add their macromolecules to the main list.
                    //foreach (Tuple<Macromolecule, int[]> alignedMacromolecule in fileAlignedMacromolecules)
                    foreach (AlignedMacromolecule alignedMacromolecule in fileAlignedMacromolecules)
                    {
                        loadedAlignedMacromolecules.Add(alignedMacromolecule);
                    }
                }
            }

            // Ensure that some sequences were loaded.
            if (loadedAlignedMacromolecules.Count > 0)
            {
                // Check that all are the same type, force the minority to conform to the majority, and append to the error list.
                int         numChanged;
                ReturnCodes typeReturnCode = EnsureAllSameType(loadedAlignedMacromolecules, out numChanged);
                if (typeReturnCode != ReturnCodes.OK) //
                {
                    fileErrors.Add(Tuple.Create("DNA to Protein", numChanged, typeReturnCode));
                    returnCode = ReturnCodes.FileErrors;
                }

                if (!append)
                {
                    alignmentObject.Clear();
                }

                // It's now okay to add macromolecules to the alignment object
                alignmentObject.AddAlignedMacromolecules(loadedAlignedMacromolecules);
            }

            return(returnCode);
        }
Example #7
0
        public async Task <XElement> IsAuthentificated(string sessionKey)
        {
            #region Заглушка
            // SignalR не используем, т.к. запрос идет только до WebHostCache
            return(ReturnCodes.BuildRcAnswer(0, "Аутентифицирован")); // Не-ноль - иначе

            #endregion
        }
Example #8
0
        //todo: CDS_UPDATEREGISTRY

        // Change the settings to the values of the DEVMODE passed
        public string ChangeSettings(DISPLAY_DEVICE a_dev, DevMode devmode, bool bSetPrimary)
        {
            string errorMessage = "";
            ChangeDisplaySettingsFlags flags = new ChangeDisplaySettingsFlags();

            flags = ChangeDisplaySettingsFlags.CDS_UPDATEREGISTRY | ChangeDisplaySettingsFlags.CDS_GLOBAL;

            ReturnCodes iRet = NativeMethods.ChangeDisplaySettingsEx(a_dev.DeviceName, ref devmode, IntPtr.Zero, flags, IntPtr.Zero);

            //same again, but with PRIMARY
            if (bSetPrimary && iRet == ReturnCodes.DISP_CHANGE_SUCCESSFUL)
            {
                SetAsPrimaryMonitor(a_dev);
            }//if primary

            if (iRet == ReturnCodes.DISP_CHANGE_SUCCESSFUL)
            {
                AdjustMonitorPosition(a_dev);
            }

            switch (iRet)
            {
            case ReturnCodes.DISP_CHANGE_SUCCESSFUL:
                break;

            case ReturnCodes.DISP_CHANGE_RESTART:
                errorMessage = "Please restart your system";
                break;

            case ReturnCodes.DISP_CHANGE_FAILED:
                errorMessage = "ChangeDisplaySettigns API failed";
                break;

            case ReturnCodes.DISP_CHANGE_BADDUALVIEW:
                errorMessage = "The settings change was unsuccessful because system is DualView capable.";
                break;

            case ReturnCodes.DISP_CHANGE_BADFLAGS:
                errorMessage = "An invalid set of flags was passed in.";
                break;

            case ReturnCodes.DISP_CHANGE_BADPARAM:
                errorMessage = "An invalid parameter was passed in. This can include an invalid flag or combination of flags.";
                break;

            case ReturnCodes.DISP_CHANGE_NOTUPDATED:
                errorMessage = "Unable to write settings to the registry.";
                break;

            default:
                errorMessage = "Unknown return value from ChangeDisplaySettings API";
                break;
            }
            return(errorMessage);
        }
Example #9
0
        public async Task <XElement> logout(string sessionKey, long requestId)
        {
            #region Заглушка
            var hubConn  = new HubConnection(Settings.Default.ResponseHubUrl);
            var hubProxy = hubConn.CreateHubProxy("ResponseHub");
            await hubConn.Start();

            hubProxy.Invoke("OperationCallback", sessionKey, requestId, ReturnCodes.BuildRcAnswer(0, "Успешно"));
            return(ReturnCodes.BuildRcAnswer(0, "Успешно"));

            #endregion
        }
Example #10
0
        static int Main(string[] args)
        {
            ReturnCodes returnCode = ParseInputString(args);

            if (returnCode == ReturnCodes.success)
            {
                CalculateSalaryBonus();
                GetResult();
            }

            return((int)returnCode);
        }
Example #11
0
        public async Task <XElement> GetUsersById(int id, string sessionKey, long requestId)
        {
            #region Заглушка
            var hubConn  = new HubConnection(Settings.Default.ResponseHubUrl);
            var hubProxy = hubConn.CreateHubProxy("ResponseHub");
            await hubConn.Start();

            hubProxy.Invoke("OperationCallback", sessionKey, requestId,
                            ReturnCodes.BuildRcAnswer(0, "Успешно", UserInfo.ArrayToXElement(users.Where(u => u.UserId == id).ToArray())));
            return(ReturnCodes.BuildRcAnswer(0, "Успешно"));

            #endregion
        }
Example #12
0
        /// <summary>
        /// Closes the data source that is represeted by an instance of this class
        /// </summary>
        /// <returns>Response of the twain driver</returns>
        internal ReturnCodes Close()
        {
            ReturnCodes result = ReturnCodes.Success;

            if (isOpen)
            {
                result = Twain32.DisableDataSource(dataSourceManager.Identity, this.Identity, new UserInterface());
                result = Twain32.CloseDataSource(dataSourceManager.Identity, this.Identity);
                isOpen = false;
            }

            return(result);
        }
        /// <summary>
        /// Closes the datasourcemanager for the current application
        /// </summary>
        /// <returns></returns>
        internal ReturnCodes Close()
        {
            ReturnCodes result = ReturnCodes.Success;

            if (IsOpen)
            {
                result = Twain32.CloseDataSourceManager(this.Identity, ref this.parentWindowHandle);
            }

            this.Identity.Id = IntPtr.Zero;

            return(result);
        }
Example #14
0
        /// <summary>
        /// Shows an userinterface from which one can choose a suitable twain data source
        /// </summary>
        /// <returns>Resonse of the twain driver</returns>
        internal ReturnCodes Select()
        {
            ReturnCodes result = ReturnCodes.Failure;

            Close();

            if (IsClosed)
            {
                result = Twain32.UserSelectDataSource(dataSourceManager.Identity, this.Identity);
            }

            return(result);
        }
        /// <summary>
        /// Opens the data source manager for the current application
        /// </summary>
        /// <param name="parentWindowHandle"></param>
        /// <returns></returns>
        internal ReturnCodes Open(ref IntPtr parentWindowHandle)
        {
            ReturnCodes result = Twain32.OpenDataSourceManager(this.Identity, ref parentWindowHandle);

            if (
                result == ReturnCodes.Success &&
                this.Identity.Id != IntPtr.Zero
                )
            {
                this.parentWindowHandle = parentWindowHandle;
                this.isOpen             = true;
            }

            return(result);
        }
Example #16
0
        /// <summary>
        /// Starts the scanning process
        /// </summary>
        /// <param name="parentWindowHandle">Parent window of the twain driver's userinterface</param>
        /// <returns>Resonse of the twain driver</returns>
        internal ReturnCodes Enable(IntPtr parentWindowHandle)
        {
            ReturnCodes result = ReturnCodes.Failure;

            if (IsOpen)
            {
                UserInterface guif = new UserInterface();
                guif.ShowUserInterface  = 1;
                guif.ModalUserInterface = 1;
                guif.ParentHandle       = parentWindowHandle;

                result = Twain32.EnableDataSource(dataSourceManager.Identity, this.Identity, guif);
            }

            return(result);
        }
Example #17
0
        public async Task <XElement> UpdateUserLastActivity([FromBody] XElement request)
        {
            // Параметры запроса
            string sessionKey = request.Element("sessionKey").Value;
            long   requestId  = long.Parse(request.Element("requestId").Value);
            int    userId     = int.Parse(request.Element("userId").Value);

            #region Заглушка
            var hubConn  = new HubConnection(Settings.Default.ResponseHubUrl);
            var hubProxy = hubConn.CreateHubProxy("ResponseHub");
            await hubConn.Start();

            hubProxy.Invoke("OperationCallback", sessionKey, requestId, ReturnCodes.BuildRcAnswer(0, "Успешно"));
            return(ReturnCodes.BuildRcAnswer(0, "Успешно"));

            #endregion
        }
Example #18
0
        protected ReturnCodes ProcessTemplate(DirectoryName pathName, ITemplateInput originalTemplateInputSource, ITemplateInput compareToTemplateInputSource, string outputPath)
        {
            var filesEndingInHbs = Directory.EnumerateFiles(pathName).Where(f => f.EndsWith("hbs", StringComparison.InvariantCulture)).ToList();
            var returnCodeList   = new ReturnCodes();

            foreach (var _templateFullFileName in filesEndingInHbs)
            {
                string templateFullFileName = (FileName)_templateFullFileName;
                if ((this.TemplateFileNameFilter.Length > 0) && (Path.GetFileNameWithoutExtension(templateFullFileName).IsIn(this.TemplateFileNameFilter)))
                {
                    CurrentTask = string.Format("Template {0} will be ignored because it matches a pattern in TemplateFileNameFilter", Path.GetFileNameWithoutExtension(templateFullFileName));
                }
                else
                {
                    returnCodeList.Merge(ProcessTemplate((FileName)_templateFullFileName, originalTemplateInputSource, compareToTemplateInputSource, outputPath));
                }
            }
            return(returnCodeList);
        }
Example #19
0
        public async Task <XElement> UpdateAnonymousSession([FromBody] XElement request)
        {
            // Выполнить необходимые операции и передать ответ хабу.
            // Долгие операции выполнять в отдельном потоке
            // Статус код отправителю вернуть через ответ на запрос немедленно после передачи запроса дальше по цепочке или начала обработки данным сервисом

            // Параметры запроса
            string sessionKey = request.Element("sessionKey").Value;
            long   requestId  = long.Parse(request.Element("requestId").Value);

            #region Заглушка
            var hubConn  = new HubConnection(Settings.Default.ResponseHubUrl);
            var hubProxy = hubConn.CreateHubProxy("ResponseHub");
            await hubConn.Start();

            hubProxy.Invoke("OperationCallback", sessionKey, requestId, ReturnCodes.BuildRcAnswer(0, "Успешно"));
            return(ReturnCodes.BuildRcAnswer(0, "Успешно"));

            #endregion
        }
Example #20
0
        public XElement PageTransfer(string sessionKey, long pageId)
        {
            #region Заглушка

            ObjectAccessResult access = new ObjectAccessResult()
            {
                Id     = pageId,
                Access = new CheckAccessResult()
                {
                    Read           = true,
                    Update         = true,
                    InsertChildren = true,
                    Delete         = true
                }
            };

            return(ReturnCodes.BuildRcAnswer(0, "Успешно", ObjectAccessResult.ToXElement(access)));

            #endregion
        }
Example #21
0
        public async Task <XElement> activate_email([FromBody] XElement request)
        {
            // Параметры запроса
            string   sessionKey = request.Element("sessionKey").Value;
            long     requestId  = long.Parse(request.Element("requestId").Value);
            UserInfo user       = UserInfo.FromXElement(request.Element("UserInfo"));

            #region Заглушка
            var hubConn  = new HubConnection(Settings.Default.ResponseHubUrl);
            var hubProxy = hubConn.CreateHubProxy("ResponseHub");

            var lu = users.Where(u => u.UserId == user.UserId).FirstOrDefault();
            lu.IsActivatedEMail = true;

            await hubConn.Start();

            hubProxy.Invoke("OperationCallback", sessionKey, requestId, ReturnCodes.BuildRcAnswer(0, "Успешно"));
            return(ReturnCodes.BuildRcAnswer(0, "Успешно"));

            #endregion
        }
Example #22
0
        /// <summary>
        /// Opens the data source represented by an object of this class
        /// </summary>
        /// <returns>Response of the twain driver</returns>
        internal ReturnCodes Open()
        {
            Close();

            ReturnCodes openResult = Twain32.OpenDataSource(dataSourceManager.Identity, this.Identity);

            Capability  capability      = new Capability(dataSourceManager, this, Capabilities.XferCount, -1);
            ReturnCodes xferCountResult = capability.Set();

            ReturnCodes result = ReturnCodes.Failure;

            if (
                openResult == ReturnCodes.Success &&
                xferCountResult == ReturnCodes.Success &&
                this.Identity.Id != IntPtr.Zero
                )
            {
                result = ReturnCodes.Success;
                isOpen = true;
            }

            return(result);
        }
Example #23
0
        //internal override ReturnCodes ReadFile(out List<Tuple<Macromolecule, int[]>> loadedAlignedMacromolecules)
        internal override ReturnCodes ReadFile(out List <AlignedMacromolecule> loadedAlignedMacromolecules)
        {
            //loadedAlignedMacromolecules = new List<Tuple<Macromolecule, int[]>>();
            loadedAlignedMacromolecules = new List <AlignedMacromolecule>();
            ReturnCodes returnCode = ReturnCodes.OK;
            string      lineIn     = "";
            Dictionary <string, StringBuilder> alignedSequenceBuilderDict = new Dictionary <string, StringBuilder>();

            // Find the first non-whitespace line. This is the header, and can be ignored.
            while (!fileReader.EndOfStream)
            {
                lineIn = fileReader.ReadLine();
                if (!String.IsNullOrWhiteSpace(lineIn))
                {
                    break;
                }
            }

            // Scan through the remainder of the file to read the sequences.
            while (!fileReader.EndOfStream)
            {
                lineIn = fileReader.ReadLine();

                // Discard uninformative lines
                if (IsClustalBlankLine(lineIn))
                {
                    continue;
                }

                // Get the first two space-separated elements, name and up to 60 bases of sequence
                string[] lineElements = lineIn.Split(new char[] { ' ' }, 2, StringSplitOptions.RemoveEmptyEntries);

                string name         = lineElements[0];
                string sequenceLine = lineElements[1];

                if (!alignedSequenceBuilderDict.ContainsKey(name))
                {
                    alignedSequenceBuilderDict.Add(name, new StringBuilder(sequenceLine));
                }
                else
                {
                    alignedSequenceBuilderDict[name].Append(sequenceLine);
                }
            }

            // Now that the sequences have been read, load them into the Macromolecule object,
            // create the aligned positions array, and determine if it is a protein or DNA.
            foreach (KeyValuePair <string, StringBuilder> alignedSeqBuilderItem in alignedSequenceBuilderDict)
            {
                Macromolecule macromolecule = new Macromolecule();
                int[]         alignedPos;

                macromolecule.Name     = alignedSeqBuilderItem.Key;
                macromolecule.Sequence = Alignment.ToSequence(alignedSeqBuilderItem.Value.ToString(), out alignedPos);
                //alignedMacromolecule.Macromolecule.Sequence = Alignment.ToSequence(alignedSeqBuilderItem.Value.ToString(), out alignedPos);
                macromolecule.IsNucleicAcid = Routines.IsNucleicAcid(macromolecule.Sequence);

                //loadedAlignedMacromolecules.Add(Tuple.Create(macromolecule, alignedPos));
                loadedAlignedMacromolecules.Add(new AlignedMacromolecule(macromolecule, alignedPos));
            }

            return(returnCode);
        }
Example #24
0
        public static void Enable(CommandLineApplication app)
        {
            app.Name             = "ezdb.codegen.cli";
            app.Description      = "EzDbCodeGen - Code Generation Utility";
            app.ExtendedHelpText = "This application will allow you to trigger code generation based on a template file or a list of template files."
                                   + Environment.NewLine + "";

            app.HelpOption("-?|-h|--help");

            var sampleFilesOption = app.Option("-i|--init-files <path>",
                                               "This option will download the template files and required powerscript to the [path] directory, renaming assets using the value sent through -a/--app-name ",
                                               CommandOptionType.SingleValue);

            var appNameOption = app.Option("-a|--app-name <appame>",
                                           "This option will be used to customize the name and files on --init-files,  this default value will be MyApp",
                                           CommandOptionType.SingleValue);

            var verboseOption = app.Option("-v|--verbose",
                                           "Will output more detailed message about what is happening during application processing.  This parm is optional and will override the value in appsettings.json.   ",
                                           CommandOptionType.NoValue);

            var versionOption = app.Option("-ver|--version",
                                           "Will output the current version of the utility.",
                                           CommandOptionType.NoValue);

            var templateFileNameOrDirectoryOption = app.Option("-t|--template <value>",
                                                               "The template file name or path that you wish to render.  If you choose aa path,  ",
                                                               CommandOptionType.SingleValue);

            var pathNameOption = app.Option("-p|--outpath <value>",
                                            "The template that you wish to render.  This is required uniless you use the <OUTPUT_PATH> specifier in the template file.",
                                            CommandOptionType.SingleValue);

            var sourceConnectionStringOption = app.Option("-sc|--connection-string <optionvalue>",
                                                          "Connection String pass via the appline.  This parm is optional and this value will override the value in appsettings.json. ",
                                                          CommandOptionType.SingleValue);

            var sourceSchemaFileNameOption = app.Option("-sf|--schema-file <optionvalue>",
                                                        "Specify a schema json dump to perform the code generation (as opposed to a connection string).  This parm is optional and parm is present, it will override the appsettings and the -sc app line parm",
                                                        CommandOptionType.SingleValue);

            var configFileOption = app.Option("-cf|--configfile",
                                              "The configuration file this template render will use.  This is optional, the default search path will be in the same path as this assembly of this applicaiton. ",
                                              CommandOptionType.SingleValue);

            var compareToConnectionStringOption = app.Option("-tc|--compare-connection-string <optionvalue>",
                                                             "Connection String to compare to.  This parm is optional.  If it is present,  This schema will be compared to either the -sc or -sf and the only the changes will be updated.",
                                                             CommandOptionType.SingleValue);

            var compareToSchemaFileNameOption = app.Option("-tf|--compare-schema-file <optionvalue>",
                                                           "OPTIONAL: Specify a compare schema json dump to perform the (as opposed to a compare connection string).  This parm is optional and parm is present, it will override the -ts command line parameter and will be used to compare,  affecting only those entities that have changed.",
                                                           CommandOptionType.SingleValue);

            var schemaNameOption = app.Option("-sn|--schemaName",
                                              "the Name of the schema,  a decent standard could be <DatabaseName>Entites.",
                                              CommandOptionType.SingleValue);

            var projectFileToModifyOption = app.Option("-pf|--project-file <optionvalue>",
                                                       "Option to pass a project file that will be altered with the ouputpath that the template files will be written to.  This only pertains to older version of a visual studio project file.",
                                                       CommandOptionType.SingleValue);

            var templateFilterFileMasks = app.Option("-f|--filter <optionvalue>",
                                                     "Option to ignore template file names (seperated by comma, wildcards are acceptable) for those runs where a path is sent through parm -t (or --template).",
                                                     CommandOptionType.SingleValue);

            app.OnExecute(() =>
            {
                var pfx = "EzDbCodeGen: ";
                if (versionOption.HasValue())
                {
                    var version_ = Assembly.GetAssembly(typeof(CodeGenerator)).GetName().Version;
                    Console.WriteLine(version_);
                    Environment.ExitCode = 0;
                    Environment.Exit(Environment.ExitCode);
                    return(Environment.ExitCode);
                }

                if (verboseOption.HasValue())
                {
                    AppSettings.Instance.VerboseMessages = verboseOption.HasValue();
                }
                try
                {
                    var sampleFilesPath = (sampleFilesOption.HasValue() ? sampleFilesOption.Value().ResolvePathVars() : "%THIS%".ResolvePathVars());
                    if (!sampleFilesPath.EndsWith(Path.DirectorySeparatorChar))
                    {
                        sampleFilesPath += Path.DirectorySeparatorChar;
                    }
                    if (sampleFilesOption.HasValue())
                    {
                        var workPath = Path.GetTempPath() + @"EzDbCodeGen\";
                        var appName  = (appNameOption.HasValue() ? appNameOption.Value() : "MyApp");
                        Directory.Delete(workPath, true);
                        Console.WriteLine(pfx + "Sample Files to be downloaded from https://github.com/rvegajr/ez-db-codegen-core to " + workPath);
                        WebFileHelper.CurlGitRepoZip(workPath);
                        if (Directory.Exists(workPath))
                        {
                            var rootPath = workPath + @"ez-db-codegen-core-master\Src\EzDbCodeGen.Cli\";
                            WebFileHelper.CopyTo(@"Templates\SchemaRender.hbs", rootPath, sampleFilesPath);
                            WebFileHelper.CopyTo(@"Templates\SchemaRenderAsFiles.hbs", rootPath, sampleFilesPath);
                            WebFileHelper.CopyTo(@"Templates\SchemaRenderAsFilesNoOutput.hbs", rootPath, sampleFilesPath);
                            WebFileHelper.CopyTo(@"ezdbcodegen.config.json", rootPath, sampleFilesPath);
                            WebFileHelper.CopyTo(@"ezdbcodegen.ps1", rootPath, sampleFilesPath);

                            WebFileHelper.CopyTo(@"ezdbcodegen.config.json", rootPath, sampleFilesPath, appName + ".config.json")
                            .ReplaceAll("MyEntities", appName + "Entities");
                            WebFileHelper.CopyTo(@"ezdbcodegen.ps1", rootPath, sampleFilesPath, appName + ".codegen.ps1")
                            .ReplaceAll("ezdbcodegen", appName);;
                            WebFileHelper.CopyTo(@"readme.txt", rootPath, sampleFilesPath)
                            .ReplaceAll("SuperApp", appName)
                            .ReplaceAll("%PSPATH%", sampleFilesPath)
                            ;
                        }
                    }

                    var schemaName = "MySchema";

                    if (schemaNameOption.HasValue())
                    {
                        schemaName = schemaNameOption.Value();
                    }
                    if (sourceConnectionStringOption.HasValue())
                    {
                        AppSettings.Instance.ConnectionString = sourceConnectionStringOption.Value().SettingResolution();
                    }

                    if (configFileOption.HasValue())
                    {
                        AppSettings.Instance.ConfigurationFileName = configFileOption.Value();
                    }

                    var Errors     = new StringBuilder();
                    var OutputPath = string.Empty;
                    if ((!templateFileNameOrDirectoryOption.HasValue()) || (templateFileNameOrDirectoryOption.Value().Length == 0))
                    {
                        Errors.AppendLine("TemplateName is missing or empty. ");
                    }
                    if ((pathNameOption.HasValue()) && (pathNameOption.Value().Length > 0))
                    {
                        OutputPath = pathNameOption.Value();
                    }
                    if ((!sourceSchemaFileNameOption.HasValue()) && (AppSettings.Instance.ConnectionString.Length == 0))
                    {
                        Errors.AppendLine("ConnectionString and schemaFileName are both missing or empty. ");
                    }
                    if ((sourceSchemaFileNameOption.HasValue()) && (!File.Exists(sourceSchemaFileNameOption.Value())))
                    {
                        Errors.AppendLine(string.Format("Schema file '{0}' was does not exists! ", sourceSchemaFileNameOption.Value()));
                    }
                    if (Errors.Length > 0)
                    {
                        if (sampleFilesOption.HasValue())
                        {
                            Console.WriteLine("Sample files where generated... exiting");
                            Environment.ExitCode = 0;
                            Environment.Exit(Environment.ExitCode);
                            return(Environment.ExitCode);
                        }
                        throw new Exception(Errors.ToString());
                    }

                    var TemplateFileNameOrPath = templateFileNameOrDirectoryOption.Value();
                    if (Path.GetPathRoot(TemplateFileNameOrPath).Length == 0)
                    {
                        TemplateFileNameOrPath = ("{ASSEMBLY_PATH}" + TemplateFileNameOrPath).ResolvePathVars();
                    }
                    if (!(
                            (File.Exists(TemplateFileNameOrPath)) ||
                            (Directory.Exists(TemplateFileNameOrPath)
                            )))
                    {
                        TemplateFileNameOrPath = ("{ASSEMBLY_PATH}" + TemplateFileNameOrPath).ResolvePathVars();
                    }
                    if (!((File.Exists(TemplateFileNameOrPath)) || (Directory.Exists(TemplateFileNameOrPath))))
                    {
                        throw new Exception(string.Format("Template not found in path {0}", TemplateFileNameOrPath));
                    }

                    // get the file attributes for file or directory
                    FileAttributes attr = File.GetAttributes(TemplateFileNameOrPath);

                    if (attr.HasFlag(FileAttributes.Directory))
                    {
                        pfx = "<List of templates>: ";
                        //Since we know this is a directory,  force it to end with a system path seperator
                        TemplateFileNameOrPath = TemplateFileNameOrPath.PathEnds();
                    }
                    else
                    {
                        pfx = Path.GetFileNameWithoutExtension(TemplateFileNameOrPath) + ": ";
                    }

                    Console.WriteLine("Performing Rendering of template " + pfx + "....");
                    if (AppSettings.Instance.VerboseMessages)
                    {
                        Console.WriteLine(pfx + "Template Path: " + TemplateFileNameOrPath);
                        Console.WriteLine(pfx + "Path Name: " + pathNameOption.Value());
                        Console.WriteLine(pfx + "Config File Name: " + AppSettings.Instance.ConfigurationFileName);
                        if (!sourceSchemaFileNameOption.HasValue())
                        {
                            Console.WriteLine(pfx + "Source Connection String: " + AppSettings.Instance.ConnectionString);
                        }
                        if (sourceSchemaFileNameOption.HasValue())
                        {
                            Console.WriteLine(pfx + "Source Schema File Name: " + sourceSchemaFileNameOption.Value());
                        }

                        if (compareToSchemaFileNameOption.HasValue())
                        {
                            Console.WriteLine(pfx + "Compare To Schema File Name: " + compareToSchemaFileNameOption.Value());
                        }
                        if ((!compareToSchemaFileNameOption.HasValue()) && (compareToConnectionStringOption.HasValue()))
                        {
                            Console.WriteLine(pfx + "Compare To Connection String: " + compareToConnectionStringOption.Value());
                        }
                    }
                    var CodeGen = new CodeGenerator
                    {
                        SchemaName             = schemaName,
                        VerboseMessages        = AppSettings.Instance.VerboseMessages,
                        ConfigurationFileName  = AppSettings.Instance.ConfigurationFileName,
                        ProjectPath            = ((projectFileToModifyOption.HasValue()) ? projectFileToModifyOption.Value() : ""),
                        TemplateFileNameFilter = ((templateFilterFileMasks.HasValue()) ? templateFilterFileMasks.Value() : "")
                    };

                    var version = Assembly.GetAssembly(typeof(CodeGenerator)).GetName().Version;
                    Console.WriteLine(pfx + "Using CodeGenerator Version " + version);

                    CodeGen.OnStatusChangeEventArgs += StatusChangeEventHandler;

                    var returnCode        = new ReturnCodes();
                    ITemplateInput Source = null;
                    if (sourceSchemaFileNameOption.HasValue())
                    {
                        Source = new TemplateInputFileSource(sourceSchemaFileNameOption.Value());
                    }
                    else
                    {
                        Source = new TemplateInputDatabaseConnecton(AppSettings.Instance.ConnectionString);
                    }

                    ITemplateInput CompareTo = null;
                    if (compareToSchemaFileNameOption.HasValue())
                    {
                        CompareTo = new TemplateInputFileSource(compareToSchemaFileNameOption.Value());
                    }
                    else if (compareToConnectionStringOption.HasValue())
                    {
                        CompareTo = new TemplateInputDatabaseConnecton(compareToConnectionStringOption.Value());
                    }

                    if (CompareTo == null)
                    {
                        Source.VerboseMessages = AppSettings.Instance.VerboseMessages;
                        returnCode             = CodeGen.ProcessTemplate(TemplateFileNameOrPath, Source, OutputPath);
                    }
                    else
                    {
                        Source.VerboseMessages    = AppSettings.Instance.VerboseMessages;
                        CompareTo.VerboseMessages = AppSettings.Instance.VerboseMessages;
                        returnCode = CodeGen.ProcessTemplate(TemplateFileNameOrPath, Source, CompareTo, OutputPath);
                    }

                    Console.WriteLine("Render of template " + templateFileNameOrDirectoryOption.Value() + " Completed!");
                    Environment.ExitCode = (int)returnCode.Result;
                    Environment.Exit(Environment.ExitCode);
                    return(Environment.ExitCode);
                }
                catch (Exception ex)
                {
                    Console.WriteLine("Could not render template. " + ex.Message);
                    Console.WriteLine("Stack Trace:");
                    Console.WriteLine(ex.StackTrace);
                    Environment.ExitCode = (int)ReturnCode.Error;
                    Environment.Exit(Environment.ExitCode);
                    return(Environment.ExitCode);
                }
            });
        }
Example #25
0
        private void OpenCommandExecuted(object sender, ExecutedRoutedEventArgs e)
        {
            OpenFileDialog ofd = new OpenFileDialog();

            ofd.Title       = "Load sequence files";
            ofd.Multiselect = true;
            bool?success = ofd.ShowDialog();

            if (success.Value)
            {
                //x.Start();
                Alignment   currentAlignment = (Alignment)DataContext;
                ReturnCodes returnCode       = ReturnCodes.OK;
                List <Tuple <string, int, ReturnCodes> > fileErrors;
                bool append = false;
                //x.Stop(); MessageBox.Show("Time to initialize varaibles was " + x.ElapsedMilliseconds + " ms."); Environment.Exit(1);

                if (currentAlignment.NumberMacromolecules > 0)
                {
                    MessageBoxResult appendChoice = MessageBox.Show("Do you want to append these sequences to the current alignment?", "", MessageBoxButton.YesNoCancel, MessageBoxImage.Question);

                    switch (appendChoice)
                    {
                    case MessageBoxResult.Yes:
                        // User wants to append.
                        append = true;
                        break;

                    case MessageBoxResult.No:
                        // User doesn't want to append.
                        append = false;

                        bool cancelAction;
                        CheckToSaveChanges(out cancelAction);
                        if (cancelAction)
                        {
                            // User wants to cancel opening the file
                            return;
                        }
                        break;

                    case MessageBoxResult.Cancel:
                        // User wants to cancel opening the file.
                        return;
                    }
                }

                returnCode = SequenceFileReader.LoadSequencesFromFiles(ref currentAlignment, append, ofd.FileNames, out fileErrors);

                if (returnCode == ReturnCodes.FileErrors)
                {
                    StringBuilder errorMessage = new StringBuilder();

                    errorMessage.AppendLine("The program encountered an error loading your sequence(s):");

                    foreach (Tuple <string, int, ReturnCodes> fileError in fileErrors)
                    {
                        string      fileName  = fileError.Item1;
                        int         numSeq    = fileError.Item2;
                        ReturnCodes errorCode = fileError.Item3;
                        errorMessage.Append(' ', 4);
                        errorMessage.Append(fileName);

                        switch (errorCode)
                        {
                        case ReturnCodes.EmptySequencesRemoved:
                            errorMessage.Append(" had empty sequences removed; ");
                            errorMessage.AppendFormat("{0} loaded.", numSeq);
                            break;

                        case ReturnCodes.FileNotFound:
                            errorMessage.Append(" could not be found or was inaccessible.");
                            break;

                        case ReturnCodes.NoNonEmptySequencesInFile:
                            errorMessage.Append(" contained only empty sequences.");
                            break;

                        case ReturnCodes.NoSequencesInFile:
                            errorMessage.Append(" was a recognized type, but contained no sequences.");
                            break;

                        case ReturnCodes.UnrecognizedFileType:
                            errorMessage.Append(" was not a recognized file type.");
                            break;

                        case ReturnCodes.IOException:
                            errorMessage.Append(" threw an unspecified IO error.");
                            break;

                        case ReturnCodes.MixedToNA:
                            errorMessage.Append("Some sequences were detected as protein, but since most loaded were detected as NA, they were forced to be NA; ");
                            errorMessage.AppendFormat("{0} sequences were affected.", numSeq);
                            break;

                        case ReturnCodes.MixedToProtein:
                            errorMessage.Append("Some sequences were detected as NA, but since most loaded were detected as protein, they were forced to be protein; ");
                            errorMessage.AppendFormat("{0} sequences were affected.", numSeq);
                            break;
                        }
                        errorMessage.AppendLine();
                    }
                    ErrorWindow error = new ErrorWindow();
                    error.DataContext = errorMessage.ToString();
                    error.Owner       = this;
                    error.ShowDialog();
                }
            }
        }
Example #26
0
 public ExceptionHandling(SetupException.ExceptionType exceptionType, string message, ReturnCodes returnCode)
 {
     m_ExceptionType = exceptionType;
     m_Message       = message;
     m_ReturnCode    = (int)returnCode;
 }
Example #27
0
 public RequestResponse(RequestTypes requestType, ReturnCodes returnCode, JToken data = null)
 {
     RequestType = requestType;
     ReturnCode  = returnCode;
     Data        = data;
 }
Example #28
0
 public async Task <XElement> Update([FromBody] XElement req)
 {
     Program.WebApiSyncRequestBuffer.AddRequest(@"api\CallRegistry\Update", req);
     return(ReturnCodes.BuildRcAnswer(0, "OK"));
 }
Example #29
0
 public async Task <XElement> Get(Guid callid, string sessionKey, long requestId)
 {
     Program.WebApiSyncRequestBuffer.AddRequest(@"api\CallRegistry\Get?callid=" + callid + "&sessionKey=" + sessionKey + "&requestId=" + requestId);
     return(ReturnCodes.BuildRcAnswer(0, "OK"));
 }
Example #30
0
 public async Task <XElement> GetCalls([FromBody] XElement requestParameters)
 {
     Program.WebApiSyncRequestBuffer.AddRequest(@"api\CallRegistry\GetCalls", requestParameters, WebApiSync.ContentTypes.xml);
     return(ReturnCodes.BuildRcAnswer(0, "OK"));
 }
Example #31
0
        static void Main(string[] args)
        {
            Console.WriteLine("Hello World!");

            int result1 = 0, result2 = 0;

            int[] input;

            using (StreamReader reader = new StreamReader(File.OpenRead("data.txt")))
            {
                var data = reader.ReadToEnd().Split(',');
                input = new int[data.Length];
                for (int i = 0; i < data.Length; i++)
                {
                    string s = data[i];
                    input[i] = Convert.ToInt32(s);
                }
            }

            //


            {
                var sequences = GetSequences(0, 5);

                int largest_output = 0;

                foreach (int[] sequence in sequences)
                {
                    int last_output = 0;

                    for (int j = 0; j < 5; j++) //run each amplifier once
                    {
                        Queue <int> queue = new Queue <int>();
                        queue.Enqueue(sequence[j]);     // phase setting
                        queue.Enqueue(last_output);     // output from last
                        int[] progMemory = (int[])input.Clone();
                        int   ic         = 0;
                        Compute(ref progMemory, ref ic, input: queue, output: out int output);
                        last_output = output;
                    }

                    if (last_output > largest_output)
                    {
                        largest_output = last_output;
                    }
                }

                result1 = largest_output;
            }

            //

            {
                var sequences = GetSequences(5, 10);

                int largest_output = 0;

                foreach (int[] sequence in sequences)
                {
                    bool first = true;

                    int[][] programdata = new int[5][];
                    int[]   programIC   = new int[5];
                    bool    end         = false;
                    int     last_output = 0;

                    //Console.WriteLine($"Current sequence: [{sequence[0]},{sequence[1]},{sequence[2]},{sequence[3]},{sequence[4]}]");

                    while (!end)
                    {
                        for (int i = 0; i < 5; i++) //run each amplifier once
                        {
                            ReturnCodes returncode = 0;
                            Queue <int> inputQueue = new Queue <int>();
                            int         output;
                            int         ic       = first ? 0 : programIC[i];
                            int[]       progdata = first ? (int[])input.Clone() : programdata[i];

                            if (first)
                            {
                                inputQueue.Enqueue(sequence[i]);     // phase setting
                            }

                            inputQueue.Enqueue(last_output);     // output from last
                            returncode = Compute(ref progdata, ref ic, inputQueue, out output);

                            programIC[i]   = ic;
                            programdata[i] = progdata;

                            last_output = output;

                            //Console.WriteLine($"Amplifier {i}: {last_output} {returncode}");

                            if (i == 4 && returncode != ReturnCodes.NEEDINPUT || last_output < 0)
                            {
                                end = true;
                            }
                        }

                        first = false;
                    }

                    if (last_output > largest_output)
                    {
                        largest_output = last_output;
                    }
                }

                result2 = largest_output;
            }

            //

            Console.WriteLine($"Result: {result1} {result2}");

            // results: 117312 1336480

            Console.ReadKey();
        }