コード例 #1
0
        private JobList <FetchedJobDto> FetchedJobs(
            FbConnection connection,
            IEnumerable <int> jobIds)
        {
            string fetchedJobsSql = string.Format(@"
                SELECT j.id ""Id"", j.invocationdata ""InvocationData"", j.arguments ""Arguments"", j.createdat ""CreatedAt"", 
                    j.expireat ""ExpireAt"", jq.fetchedat ""FetchedAt"", j.statename ""StateName"", s.reason ""StateReason"", s.data ""StateData""
                FROM ""{0}.JOB"" j
                LEFT JOIN ""{0}.STATE"" s ON j.stateid = s.id
                LEFT JOIN ""{0}.JOBQUEUE"" jq ON jq.jobid = j.id
                WHERE j.id = IN ({1}) 
                AND jq.fetchedat IS NOT NULL;", _options.Prefix, string.Join(",", jobIds));

            var jobs = connection.Query <SqlJob>(
                fetchedJobsSql)
                       .ToList();

            var result = new List <KeyValuePair <string, FetchedJobDto> >(jobs.Count);

            foreach (var job in jobs)
            {
                result.Add(new KeyValuePair <string, FetchedJobDto>(
                               job.Id.ToString(),
                               new FetchedJobDto
                {
                    Job       = DeserializeJob(job.InvocationData, job.Arguments),
                    State     = job.StateName,
                    FetchedAt = job.FetchedAt
                }));
            }

            return(new JobList <FetchedJobDto>(result));
        }
コード例 #2
0
        private Dictionary <DateTime, long> GetTimelineStats(FbConnection connection,
                                                             IDictionary <string, DateTime> keyMaps)
        {
            string sqlQuery = string.Format(@"
                SELECT ""KEY"" AS ""Key"", COUNT(""VALUE"") AS ""Count"" 
                FROM ""{0}.COUNTER""
                GROUP BY ""KEY""
                HAVING ""KEY"" IN ('{1}')", _options.Prefix, string.Join("','", keyMaps.Keys));

            var valuesMap = connection.Query(
                sqlQuery,
                new { keys = keyMaps.Keys })
                            .ToDictionary(x => (string)x.Key, x => (long)x.Count);

            foreach (var key in keyMaps.Keys)
            {
                if (!valuesMap.ContainsKey(key))
                {
                    valuesMap.Add(key, 0);
                }
            }

            var result = new Dictionary <DateTime, long>();

            for (var i = 0; i < keyMaps.Count; i++)
            {
                var value = valuesMap[keyMaps.ElementAt(i).Key];
                result.Add(keyMaps.ElementAt(i).Value, value);
            }

            return(result);
        }
コード例 #3
0
ファイル: GetOperations.cs プロジェクト: KamilPuczka/Vertex
 public IEnumerable <T> Get <T>(string conString, string procName)
 {
     using (FbConnection mycon = new FbConnection(_encrypter.DecryptString(conString)))
     {
         return(mycon.Query <T>(_config.GetSqlFrom(procName)));
     }
 }
コード例 #4
0
        private JobList <EnqueuedJobDto> EnqueuedJobs(
            FbConnection connection,
            IEnumerable <int> jobIds)
        {
            string enqueuedJobsSql = string.Format(@"
                SELECT j.id ""Id"", j.invocationdata ""InvocationData"", j.arguments ""Arguments"", j.createdat ""CreatedAt"", j.expireat ""ExpireAt"", s.name ""StateName"", s.reason ""StateReason"", s.data ""StateData""
                FROM ""{0}.JOB"" j
                LEFT JOIN ""{0}.STATE"" s ON j.stateid = s.id
                LEFT JOIN ""{0}.JOBQUEUE"" jq ON jq.jobid = j.id                
                WHERE j.id IN ({1})
                AND jq.fetchedat IS NULL;", _options.Prefix, (jobIds.Count() > 0 ? string.Join(",", jobIds) : "-1"));

            var jobs = connection.Query <SqlJob>(
                enqueuedJobsSql)
                       .ToList();

            return(DeserializeJobs(
                       jobs,
                       (sqlJob, job, stateData) => new EnqueuedJobDto
            {
                Job = job,
                State = sqlJob.StateName,
                EnqueuedAt = sqlJob.StateName == EnqueuedState.StateName
                        ? JobHelper.DeserializeNullableDateTime(stateData["EnqueuedAt"])
                        : null
            }));
        }
コード例 #5
0
 public CLIENTE Selecionar(string id)
 {
     using (var conexao = new FbConnection(_conexao))
     {
         return(conexao.Query <CLIENTE>("SELECT ID, NOME FROM CLIENTE WHERE ID = @Id", new { Id = id }).FirstOrDefault());
     }
 }
コード例 #6
0
 public IEnumerable <CLIENTE> Listar()
 {
     using (var conexao = new FbConnection(_conexao))
     {
         return(conexao.Query <CLIENTE>("SELECT ID, NOME FROM CLIENTE"));
     }
 }
コード例 #7
0
        public void Issue178_Firebird()
        {
            const string cs = @"initial catalog=localhost:database;user id=SYSDBA;password=masterkey";

            using (var connection = new FbConnection(cs))
            {
                connection.Open();
                const string sql = @"select count(*) from Issue178";
                try { connection.Execute("drop table Issue178"); }
                catch { /* don't care */ }
                connection.Execute("create table Issue178(id int not null)");
                connection.Execute("insert into Issue178(id) values(42)");
                // raw ADO.net
                using (var sqlCmd = new FbCommand(sql, connection))
                    using (IDataReader reader1 = sqlCmd.ExecuteReader())
                    {
                        Assert.IsTrue(reader1.Read());
                        reader1.GetInt32(0).IsEqualTo(1);
                        Assert.IsFalse(reader1.Read());
                        Assert.IsFalse(reader1.NextResult());
                    }

                // dapper
                using (var reader2 = connection.ExecuteReader(sql))
                {
                    Assert.IsTrue(reader2.Read());
                    reader2.GetInt32(0).IsEqualTo(1);
                    Assert.IsFalse(reader2.Read());
                    Assert.IsFalse(reader2.NextResult());
                }

                var count = connection.Query <int>(sql).Single();
                count.IsEqualTo(1);
            }
        }
コード例 #8
0
        private static bool IsEntryExpired(FbConnection connection, FirebirdStorageOptions options, int entryId)
        {
            var count = connection.Query <long>(string.Format(@"
                SELECT COUNT(*) FROM ""{0}.COUNTER"" WHERE id = @id;", options.Prefix),
                                                new { id = entryId }).Single();

            return(count == 0);
        }
コード例 #9
0
        private long GetNumberOfJobsByStateName(FbConnection connection, string stateName)
        {
            string sqlQuery = string.Format(@"
                SELECT COUNT(id) 
                FROM ""{0}.JOB""
                WHERE statename = @state;", _options.Prefix);

            var count = connection.Query <int>(
                sqlQuery,
                new { state = stateName })
                        .Single();

            return(count);
        }
コード例 #10
0
        public void TestMethod1()
        {
            var connectionString = @"User=SYSDBA;Password=masterkey;Database=SEU_BANCO.FDB;DataSource=localhost;Port=3050;Dialect=3;Charset=NONE;Role=;Connection lifetime=15;Pooling=true;MinPoolSize=0;MaxPoolSize=50;Packet Size=8192;ServerType=0;";
            var connection       = new FbConnection(connectionString);

            connection.Open();

            var helper = new FireBirdDialect.FireBirdDialect(connection);

            var query = helper.SelectWithWhere("CIDADES");

            var dados = connection.Query(query, new { CIDADE = "Divinópolis", UF = "MG" });

            Assert.IsNotNull(dados);
        }
        public override List <cipprocessdata> GetMovingAveragesByDateTime(DateTime begin, DateTime end)
        {
            List <cipprocessdata> data = null;

            using (FbConnection connection = new FbConnection(connectionString))
            {
                connection.Open();

                data = connection.Query <cipprocessdata>("GetMovingAveragesByDateTime",
                                                         new { a = begin, b = end },
                                                         commandType: System.Data.CommandType.StoredProcedure).ToList();
                connection.Close();
            }

            return(data);
        }
コード例 #12
0
        public IList <Paciente> ListaPacientes()
        {
            FbConnection _conexao = ConexaoFirebird.getInstancia().getConexao();

            try
            {
                _conexao.Open();
                return(_conexao.Query <Paciente>("SELECT id_paciente as IdPaciente, nome, idade, peso, altura FROM tb_paciente").ToList());
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                _conexao.Close();
            }
        }
コード例 #13
0
        public Paciente getPaciente(int idPaciente)
        {
            FbConnection _conexao = ConexaoFirebird.getInstancia().getConexao();

            try
            {
                _conexao.Open();
                return(_conexao.Query <Paciente>($@"SELECT ID_PACIENTE as IdPaciente, nome, idade, peso, altura FROM tb_paciente
                                                  WHERE id_paciente = {idPaciente}").SingleOrDefault());
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                _conexao.Close();
            }
        }
コード例 #14
0
 private void Init()
 {
     using (var conn = new FbConnection(Config.connString)) {
         //populate users grid
         IEnumerable <GridUsers_row> c_useri = conn.Query(@"select aa.id, aa.nume, aa.dela 
                                                         from useri aa 
                                                         where aa.deleted=0 and aa.dela is not null
                                                         order by aa.nume")
                                               .Select(row => new GridUsers_row()
         {
             IdUser   = row.ID,
             NumeUser = row.NUME,
             ldDela   = row.DELA.ToString(),
         });
         Application.Current.Dispatcher.Invoke(() => {
             GridUsersTable.Clear();
             GridUsersTable.AddRange(c_useri);
         });
     }
 }
        //select all records from the database
        public override List <cipprocessdata> GetDataByDateTime(DateTime begin, DateTime end)
        {
            List <cipprocessdata> data = null;

            using (FbConnection connection = new FbConnection(connectionString))
            {
                connection.Open();

                // dapper nicely handles the selectable procedure concept under the hood!
                // this implementation does not build a query string and thus doesn't
                // risk injection attacks
                data = connection.Query <cipprocessdata>("GetDataByDateTime",
                                                         new { a = begin, b = end },
                                                         commandType: System.Data.CommandType.StoredProcedure).ToList();

                connection.Close();
            }

            return(data);
        }
コード例 #16
0
        private JobList <TDto> GetJobs <TDto>(
            FbConnection connection,
            int from,
            int count,
            string stateName,
            Func <SqlJob, Job, Dictionary <string, string>, TDto> selector)
        {
            string jobsSql = string.Format(@"
                SELECT j.id ""Id"", j.invocationdata ""InvocationData"", j.arguments ""Arguments"", j.createdat ""CreatedAt"", 
                    j.expireat ""ExpireAt"", NULL ""FetchedAt"", j.statename ""StateName"", s.reason ""StateReason"", s.data ""StateData""
                FROM ""{0}.JOB"" j
                LEFT JOIN ""{0}.STATE"" s ON j.stateid = s.id
                WHERE j.statename = @stateName 
                ORDER BY j.id desc
                ROWS @start TO @end;", _options.Prefix);

            var jobs = connection.Query <SqlJob>(
                jobsSql,
                new { stateName = stateName, start = @from + 1, end = @from + count })
                       .ToList();

            return(DeserializeJobs(jobs, selector));
        }
コード例 #17
0
        public JobData GetJobData(string id)
        {
            if (id == null)
            {
                throw new ArgumentNullException("id");
            }

            string sql = string.Format(@"SELECT invocationdata, statename, arguments, createdat
                FROM ""{0}.JOB"" 
                WHERE id = @id;", _options.Prefix);

            var jobData = _connection.Query <SqlJob>(sql, new { id = Convert.ToInt32(id, CultureInfo.InvariantCulture) })
                          .SingleOrDefault();

            if (jobData == null)
            {
                return(null);
            }

            // TODO: conversion exception could be thrown.
            var invocationData = JobHelper.FromJson <InvocationData>(jobData.InvocationData);

            invocationData.Arguments = jobData.Arguments;

            Job job = null;
            JobLoadException loadException = null;

            try
            {
                job = invocationData.Deserialize();
            }
            catch (JobLoadException ex)
            {
                loadException = ex;
            }

            return(new JobData
            {
                Job = job,
                State = jobData.StateName,
                CreatedAt = jobData.CreatedAt,
                LoadException = loadException
            });
        }
コード例 #18
0
ファイル: Program.cs プロジェクト: ilopez/Firebird.TestBlobs
        static void Main(string[] args)
        {
            Console.WriteLine("Starting Against Test DB: " + args[0] + " " + args[1] + " " + args[2]);
            Console.WriteLine("Enter to Start");
            Console.ReadLine();

            FbConnectionStringBuilder csb = new FbConnectionStringBuilder();

            csb.DataSource = "localhost";
            csb.Port       = 3050;
            csb.UserID     = args[1];
            csb.Password   = args[2];
            csb.Database   = args[0];
            csb.ServerType = FbServerType.Default;
            Console.WriteLine("Dropping Database");
            FbConnection.DropDatabase(csb.ToString());
            Console.WriteLine("Creating Database");
            FbConnection.CreateDatabase(csb.ToString());

            FileInfo Schema = new FileInfo("schema.sql");
            String   DDL    = Schema.OpenText().ReadToEnd();

            Console.WriteLine("Applying Schema");
            CreateDatabaseSchema(DDL, csb.ToString());

            try
            {
                using (FbConnection db = new FbConnection(csb.ToString()))
                {
                    db.Open();
                    List <int> loops = Enumerable.Range(1, 3).ToList();
                    foreach (int k in loops)
                    {
                        using (FbTransaction t = db.BeginTransaction())
                        {
                            try
                            {
                                List <int> words = Enumerable.Range(1, 1).ToList();
                                foreach (int i in words)
                                {
                                    MemoDB m = new MemoDB();
                                    m.MEMO = "TEST";
                                    db.Insert(m, t);
                                }
                                if (k == 2)
                                {
                                    Console.WriteLine("Simulating a Close");
                                    db.Close();
                                }
                                else
                                {
                                    t.Commit();
                                    var count = db.Query <Int32>("select count(*) from memo").Single();
                                    Console.WriteLine("Records Written: " + count);
                                }
                            }
                            catch (Exception ex)
                            {
                                t.Rollback();
                                WriteExceptionLog(ex);
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                WriteExceptionLog(ex);
            }
            Console.WriteLine("Stopped... Press Enter to Check for Validation.");
            Console.ReadLine();
            try
            {
                using (FbConnection db = new FbConnection(csb.ToString()))
                {
                    db.Open();
                    Console.WriteLine("Counting");
                    var count = db.Query <Int32>("select count(*) from memo").Single();
                    Console.WriteLine("Records Written: " + count);
                    Console.WriteLine("Deleting");
                    db.Execute("delete from memo");
                }
            }
            catch (Exception ex)
            {
                WriteExceptionLog(ex);
            }
            Console.WriteLine("Ending Application.");
            Console.ReadLine();
        }
コード例 #19
0
        static void Main(string[] args)
        {
            // const int FT = 0;

            string path = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);

            Console.WriteLine(path);
            string        subpath  = @"exportdata";
            string        subpath1 = @"importdicom";
            DirectoryInfo dirInfo  = new DirectoryInfo(path);

            if (!dirInfo.Exists)
            {
                dirInfo.Create();
            }
            dirInfo.CreateSubdirectory(subpath);
            dirInfo.CreateSubdirectory(subpath1);


            string libpath = path + "\\";

            Console.WriteLine(libpath);
            NativeMethods.SetDllDirectory(path);



            IntPtr pDll3 = NativeMethods.LoadLibrary("Pimg.dll");

            //error handling here
            if (pDll3 == IntPtr.Zero)
            {
                throw new DllNotFoundException("Dll not found");
            }

            // Step 1. Create configuration object

            LoggingConfiguration config = new LoggingConfiguration();

            // Step 2. Create targets and add them to the configuration

            ColoredConsoleTarget consoleTarget = new ColoredConsoleTarget();

            config.AddTarget("console", consoleTarget);

            FileTarget fileTarget = new FileTarget();

            config.AddTarget("file", fileTarget);

            // Step 3. Set target properties

            consoleTarget.Layout = "${date:format=HH\\:MM\\:ss} ${logger} ${message}";
            fileTarget.FileName  = "${basedir}/file.txt";
            fileTarget.Layout    = "${message}";

            // Step 4. Define rules

            LoggingRule rule1 = new LoggingRule("*", LogLevel.Debug, consoleTarget);

            config.LoggingRules.Add(rule1);

            LoggingRule rule2 = new LoggingRule("*", LogLevel.Debug, fileTarget);

            config.LoggingRules.Add(rule2);

            // Step 5. Activate the configuration

            LogManager.Configuration = config;

            // Example usage

            Logger logger = LogManager.GetLogger("Program");

            /*logger.Trace("trace log message");
             * logger.Debug("debug log message");
             * logger.Info("info log message");
             * logger.Warn("warn log message");
             * logger.Error("error log message");
             * logger.Fatal("fatal log message");
             *
             */


            // strConnectionString s- соединение с базой ARHIMED
            //string strConnectionString = System.Configuration.ConfigurationManager.AppSettings["DB_CONN_STRING"];
            string strConnectionString2 = System.Configuration.ConfigurationManager.AppSettings["DB_CONN_STRING2"];

            //string strConnectionStringM = System.Configuration.ConfigurationManager.AppSettings["MSSQL_CONN_STRING"];


            // SqlConnection myConnection = new SqlConnection(strConnectionStringM);


            Console.WriteLine(strConnectionString2);
            var paths = new List <string>(ConfigurationManager.AppSettings["DB_CONN_STRING2"].Split(new char[] { ';' }));
            //paths.ForEach(Console.WriteLine);
            //Console.WriteLine(paths[3]);
            var Databases = new List <string>(paths[3].Split(new char[] { '=' }));

            Databases.ForEach(Console.WriteLine);
            var    Usernames = new List <string>(paths[1].Split(new char[] { '=' }));
            string User_Name = Usernames[1];
            string Password  = paths[2];
            string Database  = Databases[1];

            Console.WriteLine(User_Name);

            string[] imagepaths = Directory.GetFiles(Database, "Im*.fdb");
            Console.WriteLine("The number image databases  is {0}.", imagepaths.Length);

            foreach (string imagepath in imagepaths)
            {
                string strConnectionStringI = paths[0] + ';' + paths[1] + ';' + paths[2] + "; Database=" + imagepath;
                Console.WriteLine(strConnectionStringI);
            }


            foreach (string imagepath in imagepaths)
            {
                string strConnectionStringI = paths[0] + ';' + paths[1] + ';' + paths[2] + "; Database=" + imagepath;
                Console.WriteLine(strConnectionStringI);
                //Console.ReadLine();
                //FbConnection db = new FbConnection(strConnectionString);
                FbConnection db2 = new FbConnection(strConnectionStringI);

                db2.Open();

                // db.Open();



                //ISOBR
                string SqlString2 = "SELECT   ID, NUMBERKART,   ISOBR FROM ISOBR";

                var ourisobr = (IEnumerable <isobr>)db2.Query <isobr>(SqlString2, buffered: false);
                foreach (var isobr in ourisobr)
                {
                    string filename1 = "id" + isobr.ID.ToString() + "NK" + isobr.NUMBERKART.ToString() + ".dcm";
                    Console.WriteLine(filename1);
                    string filename = path + "\\exportdata\\" + isobr.ID.ToString() + "NK" + isobr.NUMBERKART.ToString() + ".dcm";
                    // Console.WriteLine(filename);
                    int  length  = isobr.ISOBR.Length;
                    long numberk = isobr.NUMBERKART;



                    IntPtr pAddressOfFunctionToCall3 = NativeMethods.GetProcAddress(pDll3, "Improcessing");
                    //oh dear, error handling here
                    if (pAddressOfFunctionToCall3 == IntPtr.Zero)
                    {
                        throw new DllNotFoundException("Dll does not contain required function");
                    }

                    Improcessing imP = (Improcessing)Marshal.GetDelegateForFunctionPointer(pAddressOfFunctionToCall3, typeof(Improcessing));

                    byte[] theResult = isobr.ISOBR;
                    RetrieveStandardImage(filename, theResult);

                    imP(filename, 0, filename1);

                    // Directory.Delete(path + "\\exportdata\\", true);

                    // bool result = NativeMethods.FreeLibrary(pDll3);
                }
                //db2.Close();
                //Directory.Delete(path + "\\exportdata\\", true);
            }
            bool result     = NativeMethods.FreeLibrary(pDll3);
            var  samplesDir = Path.Combine(Path.GetPathRoot(Environment.CurrentDirectory), "exportdata", "dicom");
            var  testDir    = Path.Combine(samplesDir, "Test");

            if (!Directory.Exists(testDir))
            {
                Directory.CreateDirectory(testDir);
            }

            try
            {
                if (!Directory.Exists(testDir))
                {
                    Directory.CreateDirectory(testDir);
                }
                // Only get files that .dcm"
                string[] dirs = Directory.GetFiles(@"c:\exportdicom\", "*.DCM");
                Console.WriteLine("The number of  dicom files  is {0}.", dirs.Length);

                foreach (string dir in dirs)
                {
                    string fname = Path.GetFileNameWithoutExtension(dir);

                    Char charRange = 'N';

                    int    start = fname.IndexOf(charRange);
                    string r     = fname.Substring(start + 2);
                    Console.WriteLine(r);


                    var df = DicomFile.Open(dir);

                    Console.WriteLine(df.ToString());
                    //Console.ReadLine();
                    Save(df, r);
                }
            }
            catch (Exception e)
            {
                Console.WriteLine("The process failed: {0}", e.ToString());
            }
        }
コード例 #20
0
        public static void Save(DicomFile fil, string filn)
        {
            string       strConnectionStringM = System.Configuration.ConfigurationManager.AppSettings["MSSQL_CONN_STRING"];
            string       strConnectionString  = System.Configuration.ConfigurationManager.AppSettings["DB_CONN_STRING"];
            FbConnection db = new FbConnection(strConnectionString);

            Console.WriteLine(strConnectionString);



            DicomFile    _dicomFile    = null;
            DicomDataset _dicomDataset = null;

            var dcf = fil;

            Console.WriteLine(filn);


            using (var memStream = new MemoryStream())
            {
                _dicomFile    = dcf;
                _dicomDataset = dcf.Dataset;
                Console.WriteLine(dcf);
                string _patientID  = _dicomDataset.Get <string>(DicomTag.PatientID);
                string _studyID    = _dicomDataset.Get <string>(DicomTag.StudyID);
                string _patientSex = _dicomDataset.Get <string>(DicomTag.PatientSex);
                Console.WriteLine(_patientID);
                string _studyInstanceUID = _dicomDataset.Get <string>(DicomTag.StudyInstanceUID);
                Console.WriteLine(_dicomDataset.Get <string>(DicomTag.StudyInstanceUID));
                string _seriesInstanceUID = _dicomDataset.Get <string>(DicomTag.SeriesInstanceUID);

                string _modality = _dicomDataset.Get <string>(DicomTag.Modality);
                Console.WriteLine(_modality);
                string _seriesDescription = _dicomDataset.Get <string>(DicomTag.SeriesDescription);
                string _patientName       = _dicomDataset.Get <string>(DicomTag.PatientName).Replace('^', ' ');
                Console.WriteLine(_patientName);
                DateTime _personBirthDate = _dicomDataset.Get <DateTime>(DicomTag.PatientBirthDate);
                Console.WriteLine(_personBirthDate);
                string _comments = _dicomDataset.Get <string>(DicomTag.PatientComments);
                Console.WriteLine(_comments);
                Guid     _id        = Guid.NewGuid();
                Guid     _persid    = Guid.NewGuid();
                Guid     _aeTitleId = Guid.NewGuid();
                DateTime dateTime   = _dicomDataset.Get <DateTime>(DicomTag.StudyDate);
                Console.WriteLine(dateTime);



                _dicomFile.Save(memStream);

                using (SqlConnection myC = new SqlConnection(strConnectionStringM))

                {
                    string vsql4 = string.Format("Insert Into Millennium.dbo.ApplicationEntity" + "(ID, AeTitle, Description) Values (@ID, @AeTitle, @Description)");
                    string vsql1 = string.Format("IF NOT EXISTS(Select * from Millennium.dbo.Studies  where StudyInstanceUID = @StudyInstanceUID)" + " Insert Into Millennium.dbo.Studies" + "(ID, Date, PersonID, Note , Result, MeanDose, Dose, iheClassEHRCode, Prophylaxis,  IsResulted,IsPrinted, X_rayProcedureID, AeTitleId, StudyInstanceUID, Comment) Values (@ID, @Date, @PersonID, @Note, @Result, @MeanDose, @Dose, @iheClassEHRCode, @Prophylaxis, @IsResulted, @IsPrinted, @X_rayProcedureID, @AeTitleId,  @StudyInstanceUID, @Comment)" + "ELSE Update Millennium.dbo.Studies set Date = @Date  where StudyInstanceUID = @StudyInstanceUID");
                    string vsql3 = string.Format("IF NOT EXISTS(Select ID from Millennium.dbo.Studies  where StudyInstanceUID = @StudyInstanceUID)" + "Insert Into Millennium.dbo.Person" + "(ID, Name, Birthday, iheGenderCode) Values (@ID, @Name, @Birthday,@iheGenderCode)" + "ELSE Update Millennium.dbo.Person set Birthday = @Birthday, Name = @Name where ID = (Select PersonID from Millennium.dbo.Studies  where StudyInstanceUID = @StudyInstanceUID)");
                    string vsql2 = "IF NOT EXISTS(Select *  from Millennium.dbo.Studies  INNER JOIN Millennium.dbo.StudiesData ON Millennium.dbo.Studies.ID = Millennium.dbo.StudiesData.StudiesID where Millennium.dbo.Studies.StudyInstanceUID= @StudyInstanceUID)"
                                   + "Insert Into Millennium.dbo.StudiesData"
                                   + "(ID,StudiesID, FileId, Data, TransferSyntaxUID, Invert,  SeriesInstanceUID, StudyInstanceUID, InstanceNumber) Values (@ID,@StudiesID, @FileId, @Data, @TransferSyntaxUID, @Invert, @SeriesInstanceUID, @StudyInstanceUID, @InstanceNumber)"
                                   + "ELSE Insert Into Millennium.dbo.StudiesData"
                                   + "(ID,StudiesID, FileId, Data, TransferSyntaxUID, Invert,  SeriesInstanceUID, StudyInstanceUID, InstanceNumber) Values (@ID, (Select ID from Millennium.dbo.Studies where StudyInstanceUID = @StudyInstanceUID), @FileId, @Data, @TransferSyntaxUID, @Invert, @SeriesInstanceUID, @StudyInstanceUID, @InstanceNumber)";
                    SqlCommand cmd3 = new SqlCommand(vsql4, myC);
                    SqlCommand cmd2 = new SqlCommand(vsql3, myC);
                    SqlCommand cmd1 = new SqlCommand(vsql1, myC);
                    SqlCommand cmd  = new SqlCommand(vsql2, myC);


                    cmd2.Parameters.Add("@StudyInstanceUID", SqlDbType.NVarChar).Value = _studyInstanceUID;
                    cmd3.Parameters.Add("@ID", SqlDbType.UniqueIdentifier).Value       = _aeTitleId;
                    cmd3.Parameters.Add("@AeTitle", SqlDbType.NVarChar).Value          = "ARCHIMED";
                    cmd3.Parameters.Add("@Description", SqlDbType.NVarChar).Value      = "Создан";
                    cmd2.Parameters.Add("@ID", SqlDbType.UniqueIdentifier).Value       = _persid;
                    //Kart_Pac

                    try
                    {
                        db.Open();
                        string SqlString3  = "SELECT  FIO FROM KART_PAC WHERE NUMBERKART = " + filn;
                        var    ourkart_pac = (List <kart_pac>)db.Query <kart_pac>(SqlString3);
                        Console.WriteLine(ourkart_pac.ElementAt(0).FIO);

                        if (ourkart_pac != null)
                        {
                            if (ourkart_pac.ElementAt(0).FIO != null)
                            {
                                string fiio = ourkart_pac.ElementAt(0).FIO;

                                Console.WriteLine(fiio);
                                cmd2.Parameters.Add("@Name", SqlDbType.NVarChar).Value = fiio;
                            }
                            else
                            {
                                cmd2.Parameters.Add("@Name", SqlDbType.NVarChar).Value = _patientName;
                            }
                        }



                        else
                        {
                            Console.WriteLine("***************");
                        }
                        db.Close();
                    }


                    catch (Exception e)
                    {
                        Console.WriteLine("нет соотоветствия в базе CLD, plain Dicom");
                        cmd2.Parameters.Add("@Name", SqlDbType.NVarChar).Value = _patientName;
                        db.Close();
                        // Console.WriteLine("The process failed: {0}", e.ToString());
                        //logger.Warn(e);
                    }


                    try
                    {
                        db.Open();
                        string SqlString4   = "SELECT NUMBERKART, OPISANIE, SAKL FROM PROTOCOL WHERE NUMBERKART = " + filn;
                        var    out_protocol = (IEnumerable <protocol>)db.Query <protocol>(SqlString4);

                        if (out_protocol != null)
                        {
                            if (out_protocol.ElementAt(1).OPISANIE != null)
                            {
                                string protoc = StripRTF(out_protocol.ElementAt(1).OPISANIE);
                                cmd1.Parameters.Add("@Note", SqlDbType.NVarChar).Value = protoc;

                                Console.WriteLine(protoc);
                            }
                            else
                            {
                                cmd1.Parameters.Add("@Note", SqlDbType.NVarChar).Value = "  ";
                            }
                        }


                        else
                        {
                            Console.WriteLine("************");
                        }
                        db.Close();
                    }


                    catch (Exception e)
                    {
                        Console.WriteLine("нет соотоветствующей базы CLD, файлы загружаются без протоколов");
                        cmd1.Parameters.Add("@Note", SqlDbType.NVarChar).Value = "  ";
                        db.Close();
                        // Console.WriteLine("The process failed: {0}", e.ToString());
                        //logger.Warn(e);
                    }



                    // birthday and null excepеtion
                    DateTime etalon  = new DateTime(1753, 1, 1, 12, 0, 0);
                    DateTime nothing = new DateTime();
                    Console.WriteLine(etalon);

                    if (_personBirthDate != nothing && _personBirthDate >= etalon)
                    {
                        cmd2.Parameters.Add("@Birthday", SqlDbType.DateTime).Value = _personBirthDate;
                    }
                    else
                    {
                        cmd2.Parameters.Add("@Birthday", SqlDbType.DateTime).Value = dateTime;
                    }

                    // patient sex
                    if (_patientSex != null)
                    {
                        if (_patientSex.Equals("M"))
                        {
                            cmd2.Parameters.Add("@iheGenderCode", SqlDbType.TinyInt).Value = 1;
                        }
                        else if (_patientSex.Equals("F"))
                        {
                            cmd2.Parameters.Add("@iheGenderCode", SqlDbType.TinyInt).Value = 2;
                        }
                        else
                        {
                            cmd2.Parameters.Add("@iheGenderCode", SqlDbType.TinyInt).Value = 3;
                        }
                    }
                    else
                    {
                        cmd2.Parameters.Add("@iheGenderCode", SqlDbType.TinyInt).Value = 3;
                    }



                    cmd1.Parameters.Add("@ID", SqlDbType.UniqueIdentifier).Value       = _id;
                    cmd1.Parameters.Add("@Date", SqlDbType.DateTime).Value             = dateTime;
                    cmd1.Parameters.Add("@PersonID", SqlDbType.UniqueIdentifier).Value = _persid;
                    // cmd1.Parameters.Add("@Note", SqlDbType.NVarChar).Value = "protoc";

                    /*
                     *
                     *  if (out_protocol.ElementAt(1).OPISANIE != null)
                     *  {
                     *      string protoc = StripRTF(out_protocol.ElementAt(1).OPISANIE);
                     *      cmd1.Parameters.Add("@Note", SqlDbType.NVarChar).Value = protoc;
                     *  Console.WriteLine(protoc);
                     *   }
                     *  else
                     * {
                     *  Console.WriteLine(" нет протокола");
                     * }*/

                    cmd1.Parameters.Add("@Result", SqlDbType.NVarChar).Value = " ";

                    /*
                     * if (out_protocol.ElementAt(0).SAKL != null)
                     * {
                     *     string sakl = StripRTF(out_protocol.ElementAt(0).SAKL);
                     * Console.WriteLine(sakl);
                     * cmd1.Parameters.Add("@Result", SqlDbType.NVarChar).Value = sakl;
                     * }
                     * .else
                     * {
                     *  cmd1.Parameters.Add("@Result", SqlDbType.NVarChar).Value = null;
                     * Console.WriteLine("no sakl");
                     * }*/

                    cmd1.Parameters.Add("@IsResulted", SqlDbType.Bit).Value           = 0;
                    cmd1.Parameters.Add("@Prophylaxis", SqlDbType.Bit).Value          = 0;
                    cmd1.Parameters.Add("@MeanDose", SqlDbType.Decimal).Value         = 0.0;
                    cmd1.Parameters.Add("@Dose", SqlDbType.Decimal).Value             = 0.0;
                    cmd1.Parameters.Add("@iheClassEHRCode", SqlDbType.NVarChar).Value = 2;
                    cmd1.Parameters.Add("@IsPrinted", SqlDbType.Bit).Value            = 0;


                    // modality
                    if (_modality.Equals("CR"))
                    {
                        cmd1.Parameters.Add("@X_rayProcedureID", SqlDbType.TinyInt).Value = 4;
                    }
                    else if (_modality.Equals("CT"))
                    {
                        cmd1.Parameters.Add("@X_rayProcedureID", SqlDbType.TinyInt).Value = 6;
                    }
                    else if (_modality.Equals("MG"))
                    {
                        cmd1.Parameters.Add("@X_rayProcedureID", SqlDbType.TinyInt).Value = 4;
                    }
                    else if (_modality.Equals("MR"))
                    {
                        cmd1.Parameters.Add("@X_rayProcedureID", SqlDbType.TinyInt).Value = 9;
                    }
                    else if (_modality.Equals("US"))
                    {
                        cmd1.Parameters.Add("@X_rayProcedureID", SqlDbType.TinyInt).Value = 10;
                    }
                    else if (_modality.Equals("RF"))
                    {
                        cmd1.Parameters.Add("@X_rayProcedureID", SqlDbType.TinyInt).Value = 1;
                    }
                    else if (_modality.Equals("DF"))
                    {
                        cmd1.Parameters.Add("@X_rayProcedureID", SqlDbType.TinyInt).Value = 2;
                    }
                    else
                    {
                        cmd1.Parameters.Add("@X_rayProcedureID", SqlDbType.TinyInt).Value = 8;
                    }

                    // Studies
                    cmd1.Parameters.Add("@AeTitleId", SqlDbType.UniqueIdentifier).Value = _aeTitleId;
                    cmd1.Parameters.Add("@StudyInstanceUID", SqlDbType.NVarChar).Value  = _dicomDataset.Get <string>(DicomTag.StudyInstanceUID);

                    // Comment
                    if (_comments != null)
                    {
                        cmd1.Parameters.Add("@Comment", SqlDbType.NVarChar).Value = _comments;
                    }
                    else
                    {
                        cmd1.Parameters.Add("@Comment", SqlDbType.NVarChar).Value = "1";
                    }


                    // studies_data
                    cmd.Parameters.Add("@ID", SqlDbType.UniqueIdentifier).Value        = Guid.NewGuid();
                    cmd.Parameters.Add("@data", SqlDbType.VarBinary).Value             = memStream.GetBuffer();
                    cmd.Parameters.Add("@invert", SqlDbType.Bit).Value                 = 0;
                    cmd.Parameters.Add("@transferSyntaxUID", SqlDbType.NVarChar).Value = _dicomDataset.InternalTransferSyntax.ToString();

                    // cmd.Parameters.Add("@windowsWidth", SqlDbType.Decimal).Value = dicomImage.WindowWidth;
                    // cmd.Parameters.Add("@windowsCenter", SqlDbType.Decimal).Value = dicomImage.WindowCenter;
                    cmd.Parameters.Add("@studiesID", SqlDbType.UniqueIdentifier).Value = _id;
                    cmd.Parameters.Add("@fileId", SqlDbType.UniqueIdentifier).Value    = Guid.NewGuid();
                    cmd.Parameters.Add("@SeriesInstanceUID", SqlDbType.NVarChar).Value = _dicomDataset.Get <string>(DicomTag.SeriesInstanceUID);
                    cmd.Parameters.Add("@StudyInstanceUID", SqlDbType.NVarChar).Value  = _dicomDataset.Get <string>(DicomTag.StudyInstanceUID);
                    cmd.Parameters.Add("@InstanceNumber", SqlDbType.SmallInt).Value    = _dicomDataset.Get <string>(DicomTag.InstanceNumber);



                    myC.Open();
                    cmd3.ExecuteNonQuery();
                    cmd3 = null;
                    cmd2.ExecuteNonQuery();
                    cmd2 = null;
                    cmd1.ExecuteNonQuery();
                    cmd1 = null;
                    cmd.ExecuteNonQuery();
                    cmd = null;
                    myC.Close();
                }
            }
        }