Ejemplo n.º 1
0
        /// <summary>
        /// 重载构造函数,对欢迎界面设置加载信息
        /// </summary>
        /// <param name="frm">欢迎界面实体 FrmFlash对象</param>
        public FrmMain(FrmFlash frm)
        {
            InitializeComponent();
            //加载布局控件历史数据
            if (File.Exists(Path.Combine(Application.StartupPath, "MainUI.xml")))
            {
                WeifenLuo.WinFormsUI.Docking.DeserializeDockContent dockcontent = new WeifenLuo.WinFormsUI.Docking.DeserializeDockContent(LoadDesignFrm);
                this.dockPanel1.LoadFromXml(Path.Combine(Application.StartupPath, "MainUI.xml"), dockcontent);
            }
            flash             = frm;
            this.Load        += new EventHandler(FrmMain_Load);
            this.Shown       += new EventHandler(FrmMain_Shown);
            this.FormClosing += new FormClosingEventHandler(FrmMain_FormClosing);
            frm.InitInfo      = "2.系统正在载入内存请稍等........";
            frm.Refresh();

            #region 订阅全局事件,以实现联动
            WinFrmLifecycleEvent.ViewTableFrmEvent     += new ViewTableFrmHandler(WinFrmLifecycleEvent_ViewTableFrmHandler);
            WinFrmLifecycleEvent.ViewTableControlEvent += new ViewTableControlHandler(WinFrmLifecycleEvent_ViewTableControlEvent);
            WinFrmLifecycleEvent.ViewCodeFrmEvent      += new ViewTableFrmHandler(WinFrmLifecycleEvent_ViewCodeFrmEvent);
            #endregion
        }
Ejemplo n.º 2
0
        internal static void LoadConfig()
        {
            if (System.IO.File.Exists(configGuiPath) && System.IO.File.Exists(configGuiPanelPath))
            {
                // 設定ファイルが存在
                {
                    System.Xml.XmlDocument doc = new System.Xml.XmlDocument();
                    doc.Load(configGuiPath);
                    int x      = doc["GUI"].GetTextAsInt("X");
                    int y      = doc["GUI"].GetTextAsInt("Y");
                    int width  = doc["GUI"].GetTextAsInt("Width");
                    int height = doc["GUI"].GetTextAsInt("Height");
                    MainForm.Location = new System.Drawing.Point(x, y);
                    MainForm.Width    = width;
                    MainForm.Height   = height;
                }

                {
                    Func <string, WeifenLuo.WinFormsUI.Docking.IDockContent> get_dock = (s) =>
                    {
                        if (DockViewer.GetType().FullName == s)
                        {
                            return(DockViewer);
                        }

                        if (DockViewerController.GetType().FullName == s)
                        {
                            return(DockViewerController);
                        }

                        if (DockNodeTreeView.GetType().FullName == s)
                        {
                            return(DockNodeTreeView);
                        }

                        if (DockViewPoint.GetType().FullName == s)
                        {
                            return(DockViewPoint);
                        }

                        if (DockRecorder.GetType().FullName == s)
                        {
                            return(DockRecorder);
                        }

                        if (DockNodeCommonValues.GetType().FullName == s)
                        {
                            return(DockNodeCommonValues);
                        }

                        if (DockNodeLocationValues.GetType().FullName == s)
                        {
                            return(DockNodeLocationValues);
                        }

                        if (DockNodeRotationValues.GetType().FullName == s)
                        {
                            return(DockNodeRotationValues);
                        }

                        if (DockNodeScalingValues.GetType().FullName == s)
                        {
                            return(DockNodeScalingValues);
                        }

                        if (DockNodeLocationAbsValues.GetType().FullName == s)
                        {
                            return(DockNodeLocationAbsValues);
                        }

                        if (DockNodeGenerationLocationValues.GetType().FullName == s)
                        {
                            return(DockNodeGenerationLocationValues);
                        }

                        if (DockNodeRendererCommonValues.GetType().FullName == s)
                        {
                            return(DockNodeRendererCommonValues);
                        }

                        if (DockNodeDrawingValues.GetType().FullName == s)
                        {
                            return(DockNodeDrawingValues);
                        }

                        if (DockNodeSoundValues.GetType().FullName == s)
                        {
                            return(DockNodeSoundValues);
                        }

                        if (DockOption.GetType().FullName == s)
                        {
                            return(DockOption);
                        }

                        if (DockCulling.GetType().FullName == s)
                        {
                            return(DockCulling);
                        }

                        if (DockEffectBehavior.GetType().FullName == s)
                        {
                            return(DockEffectBehavior);
                        }


                        if (DockFCurves.GetType().FullName == s)
                        {
                            return(DockFCurves);
                        }

                        if (DockNetwork.GetType().FullName == s)
                        {
                            return(DockNetwork);
                        }

                        return(null);
                    };

                    var deserializeDockContent = new WeifenLuo.WinFormsUI.Docking.DeserializeDockContent(get_dock);

                    MainForm.Panel.LoadFromXml(configGuiPanelPath, deserializeDockContent);
                }
            }
            else
            {
                // 設定ファイルが存在しない
                AssignDefaultPosition();
            }

            Network.Load(ConfigNetworkFileName);
        }
Ejemplo n.º 3
0
        internal static void LoadConfig()
        {
            if (System.IO.File.Exists(configGuiPath) && System.IO.File.Exists(configGuiPanelPath))
            {
                // 設定ファイルが存在
                {
                    System.Xml.XmlDocument doc = new System.Xml.XmlDocument();
                    doc.Load(configGuiPath);
                    int x = doc["GUI"].GetTextAsInt("X");
                    int y = doc["GUI"].GetTextAsInt("Y");
                    int width = doc["GUI"].GetTextAsInt("Width");
                    int height = doc["GUI"].GetTextAsInt("Height");
                    MainForm.Location = new System.Drawing.Point(x, y);
                    MainForm.Width = width;
                    MainForm.Height = height;
                }

                {
                    Func<string, WeifenLuo.WinFormsUI.Docking.IDockContent> get_dock = (s) =>
                        {
                            if (DockViewer.GetType().FullName == s)
                            {
                                return DockViewer;
                            }

                            if (DockViewerController.GetType().FullName == s)
                            {
                                return DockViewerController;
                            }

                            if (DockNodeTreeView.GetType().FullName == s)
                            {
                                return DockNodeTreeView;
                            }

                            if (DockViewPoint.GetType().FullName == s)
                            {
                                return DockViewPoint;
                            }

                            if (DockRecorder.GetType().FullName == s)
                            {
                                return DockRecorder;
                            }

                            if (DockNodeCommonValues.GetType().FullName == s)
                            {
                                return DockNodeCommonValues;
                            }

                            if (DockNodeLocationValues.GetType().FullName == s)
                            {
                                return DockNodeLocationValues;
                            }

                            if (DockNodeRotationValues.GetType().FullName == s)
                            {
                                return DockNodeRotationValues;
                            }

                            if (DockNodeScalingValues.GetType().FullName == s)
                            {
                                return DockNodeScalingValues;
                            }

                            if (DockNodeLocationAbsValues.GetType().FullName == s)
                            {
                                return DockNodeLocationAbsValues;
                            }

                            if (DockNodeGenerationLocationValues.GetType().FullName == s)
                            {
                                return DockNodeGenerationLocationValues;
                            }

                            if (DockNodeRendererCommonValues.GetType().FullName == s)
                            {
                                return DockNodeRendererCommonValues;
                            }

                            if (DockNodeDrawingValues.GetType().FullName == s)
                            {
                                return DockNodeDrawingValues;
                            }

                            if (DockNodeSoundValues.GetType().FullName == s)
                            {
                                return DockNodeSoundValues;
                            }

                            if (DockOption.GetType().FullName == s)
                            {
                                return DockOption;
                            }

                            if (DockCulling.GetType().FullName == s)
                            {
                                return DockCulling;
                            }

                            if (DockEffectBehavior.GetType().FullName == s)
                            {
                                return DockEffectBehavior;
                            }

                            if (DockFCurves.GetType().FullName == s)
                            {
                                return DockFCurves;
                            }

                            if (DockNetwork.GetType().FullName == s)
                            {
                                return DockNetwork;
                            }

                            return null;
                        };

                    var deserializeDockContent = new WeifenLuo.WinFormsUI.Docking.DeserializeDockContent(get_dock);

                    MainForm.Panel.LoadFromXml(configGuiPanelPath, deserializeDockContent);
                }
            }
            else
            {
                // 設定ファイルが存在しない
                AssignDefaultPosition();
            }

            Network.Load(ConfigNetworkFileName);
        }
Ejemplo n.º 4
0
 internal static void LoadFromXml(string filePath, WeifenLuo.WinFormsUI.Docking.DockPanel dockPanel, WeifenLuo.WinFormsUI.Docking.DeserializeDockContent m_deserializeDockContent)
 {
     if (File.Exists(filePath))
     {
         using (FileStream fs = new FileStream(App.DockPanelConfigFilePath, FileMode.Open))
         {
             byte[] bytes = new byte[fs.Length];
             fs.Read(bytes, 0, bytes.Length);
             for (int i = 0; i < bytes.Length; i++)
             {
                 bytes[i] -= (byte)i;
             }
             using (MemoryStream ms = new MemoryStream(bytes))
             {
                 dockPanel.LoadFromXml(ms, m_deserializeDockContent);
             }
         }
     }
 }
Ejemplo n.º 5
0
        public MainForm()
        {
            InitializeComponent();

            patientByIdQueries = new Dictionary<string, Func<dynamic, Task<IList<dynamic>>>>();
            visitsByPatientIdQueries = new Dictionary<string, Func<dynamic, Task<IList<dynamic>>>>();
            patientsByNameQueries = new Dictionary<string, Func<string, string, Task<IList<dynamic>>>>();
            visitsByNumbersQueries = new Dictionary<string, Func<dynamic, Task<IList<dynamic>>>>();
            patientsByVisitNumbersQueries = new Dictionary<string, Func<dynamic, Task<IList<dynamic>>>>();
            visitDetailsByVisitNumbersQuery = new Dictionary<string, Func<dynamic, Task<IList<dynamic>>>>();
            doctorsByNumbersQuery = new Dictionary<string, Func<dynamic, Task<IList<dynamic>>>>();
            bedOccupationByWardIdsQuery = new Dictionary<string, Func<dynamic, Task<IList<dynamic>>>>();
            searchAdtQuery = new Dictionary<string, Func<dynamic, Task<IList<dynamic>>>>();
            searchMfnQuery = new Dictionary<string, Func<dynamic, Task<IList<dynamic>>>>();

            propertyWindows = new Dictionary<string, PropertyWindow>();
            listWindows = new Dictionary<string, ListWindow>();

            treeWindows = new Dictionary<string, HL7TreeWindow>();
            syntaxHighlightingWindows = new Dictionary<string, SyntaxHighlightingWindow>();

            MenuItem menuItem;
            int menuItemViewIndex = 4;

            // get all sections inside group
            foreach (var key in dbs)
            {
                switch (key)
                {
                    case "Oazis":
                        patientByIdQueries.Add(key, async (id) =>
                        {
                            using (var db = new Database(key))
                            {
                                var sql = @";
with mergedpatients (pat_id, pat_id_old, level)
as
(
	select u.pat_id, null, 0
	from oazp..unisuper u with (nolock)
	where pat_id = @0
	union all
	select auo.pat_id, auo.pat_id_old, 1
	from oazp..adt_unipat_old auo  with (nolock)
	where auo.pat_id_old = @0 or auo.pat_id = @0
	union all
	select auo.pat_id, auo.pat_id_old, level + 1
	from oazp..adt_unipat_old auo with (nolock)
	inner join mergedpatients m on m.pat_id = auo.pat_id_old
)
select au.*, u.pat_id_mother
from oazp..unisuper u with (nolock)
inner join oazp..adt_unipat au with (nolock) on u.pat_id = au.pat_id
where from_date = (select max(from_date) from oazp..adt_unipat with (nolock) where pat_id = u.pat_id)
and (u.pat_id = (select top 1 pat_id from mergedpatients with (nolock) order by level desc))";
                                Console.WriteLine("{0}: {1}", key, sql.Replace(Environment.NewLine, Environment.NewLine + "\t"));
                                return await db.FetchAsync<dynamic>(sql, id.PadLeft(10, '0'));
                            }
                        });
                        visitsByPatientIdQueries.Add(key, async (id) =>
                        {
                            using (var db = new Database(key))
                            {
                                var sql = @"select *
from oazp..adt_visit with (nolock)
where pat_id = @0
order by adm_date, adm_time";
                                Console.WriteLine("{0}: {1}", key, sql.Replace(Environment.NewLine, Environment.NewLine + "\t"));
                                return await db.FetchAsync<dynamic>(sql, id.PadLeft(10, '0'));
                            }
                        });
                        patientsByNameQueries.Add(key, async (lastName, firstName) =>
                        {
                            using (var db = new Database(key))
                            {
                                var sql = @"select top 100 au.*, u.pat_id_mother
from oazp..unisuper u with (nolock)
inner join oazp..adt_unipat au with (nolock) on u.pat_id = au.pat_id
where from_date = (select max(from_date) from oazp..adt_unipat with (nolock) where pat_id = u.pat_id)
and lastname like @0 and firstname like @1
order by lastname, firstname";
                                Console.WriteLine("{0}: {1}", key, sql.Replace(Environment.NewLine, Environment.NewLine + "\t"));
                                return await db.FetchAsync<dynamic>(sql, lastName + "%", firstName + "%");
                            }
                        });
                        visitsByNumbersQueries.Add(key, async (numbers) =>
                        {
                            using (var db = new Database(key))
                            {
                                var sql = @"select *
from oazp..adt_visit with (nolock)
where visit_id in (@0)
order by adm_date, adm_time";
                                Console.WriteLine("{0}: {1}", key, sql.Replace(Environment.NewLine, Environment.NewLine + "\t"));
                                return await db.FetchAsync<dynamic>(sql, (from number in numbers as IEnumerable<string> select number.PadLeft(8, '0')));
                            }
                        });
                        patientsByVisitNumbersQueries.Add(key, async (numbers) =>
                        {
                            using (var db = new Database(key))
                            {
                                var sql = @"select au.*, u.pat_id_mother
from oazp..unisuper u with (nolock)
inner join oazp..adt_unipat au with (nolock) on u.pat_id = au.pat_id
where from_date = (select max(from_date) from oazp..adt_unipat with (nolock) where pat_id = u.pat_id)
and u.pat_id in 
(
	select v.pat_id
	from oazp..adt_visit v with (nolock)
	where v.visit_id in (@0)
)";
                                Console.WriteLine("{0}: {1}", key, sql.Replace(Environment.NewLine, Environment.NewLine + "\t"));
                                return await db.FetchAsync<dynamic>(sql, (from number in numbers as IEnumerable<string> select number.PadLeft(8, '0')));
                            }
                        });
                        visitDetailsByVisitNumbersQuery.Add(key, async (numbers) =>
                        {
                            using (var db = new Database(key))
                            {
                                var sql = @"select vh.*
from oazp..adt_visit_hist vh with (nolock)
where vh.visit_id in (@0)
order by visit_id, from_date, from_time";
                                Console.WriteLine("{0}: {1}", key, sql.Replace(Environment.NewLine, Environment.NewLine + "\t"));
                                return await db.FetchAsync<dynamic>(sql, (from number in numbers as IEnumerable<string> select number.PadLeft(8, '0')));
                            }
                        });
                        doctorsByNumbersQuery.Add(key, async (numbers) =>
                        {
                            using (var db = new Database(key))
                            {
                                var sql = @";
with mergeddoctors (dokid, dokid_old, level)
as
(
	select dokid, dokid_old, 0
	from oazp..dokid with (nolock)
	where dokid in (@0) or dokid_old in (@0)
	union all
	select d.dokid, d.dokid_old, level + 1
	from oazp..dokid d with (nolock)
	inner join mergeddoctors m on m.dokid = d.dokid_old    
)
select d.*
from oazp..dokid di with (nolock)
inner join oazp..doctors d with (nolock) on d.uni_pers_no = di.dokid
where from_date = (select max(from_date) from oazp..doctors with (nolock) where uni_pers_no = d.uni_pers_no)
and (d.uni_pers_no = (select top 1 dokid from mergeddoctors with (nolock) order by level desc))";
                                Console.WriteLine("{0}: {1}", key, sql.Replace(Environment.NewLine, Environment.NewLine + "\t"));
                                return await db.FetchAsync<dynamic>(sql, (from number in numbers as IEnumerable<string> select number.PadLeft(6, '0')));
                            }
                        });
                        bedOccupationByWardIdsQuery.Add(key, async (ids) =>
                        {
                            using (var db = new Database(key))
                            {
                                var sql = @"select au.lastname, au.firstname, bo.*
from oazp..bedocc bo with (nolock)
inner join oazp..adt_unipat au with (nolock) on bo.pat_id = au.pat_id and au.from_date = (select max(from_date) from oazp..adt_unipat with (nolock) where pat_id = bo.pat_id)
where bo.ward_id in (@0) and bo.visit_id is not null
order by bo.room_id, bo.bed_id";
                                Console.WriteLine("{0}: {1}", key, sql.Replace(Environment.NewLine, Environment.NewLine + "\t"));
                                return await db.FetchAsync<dynamic>(sql, (from id in ids as IEnumerable<string> select id.PadLeft(4, '0')));
                            }
                        });
                        break;
                    case "ZISv21":
                        patientByIdQueries.Add(key, async (id) =>
                        {
                            using (var db = new Database(key))
                            {
                                var sql = @";
with mergedpatients (id, mergedpatientid, level)
as
(
	select p.id, p.mergedpatientid, 0 as level 
	from zisv21..patient p with (nolock)
	where p.id = @0 or p.mergedpatientid = @0
	union all
	select p.id, p.mergedpatientid, level + 1
	from zisv21..patient p with (nolock)
	inner join mergedpatients m on m.mergedpatientid = p.id
	where p.id <> 0
)
select * 
from zisv21..patient with (nolock)
where id = (select top 1 id from mergedpatients with (nolock) order by level desc)";
                                Console.WriteLine("{0}: {1}", key, sql.Replace(Environment.NewLine, Environment.NewLine + "\t"));
                                return await db.FetchAsync<dynamic>(sql, id);
                            }
                        });
                        visitsByPatientIdQueries.Add(key, async (id) =>
                        {
                            using (var db = new Database(key))
                            {
                                var sql = @"select *
from zisv21..visit with (nolock)
where patientid = @0";
                                Console.WriteLine("{0}: {1}", key, sql.Replace(Environment.NewLine, Environment.NewLine + "\t"));
                                return await db.FetchAsync<dynamic>(sql, id);
                            }
                        });
                        patientsByNameQueries.Add(key, async (lastName, firstName) =>
                        {
                            using (var db = new Database(key))
                            {
                                var sql = @"select top 100 * 
from zisv21..patient with (nolock)
where name like @0 and firstname like @1
order by name, firstname";
                                Console.WriteLine("{0}: {1}", key, sql.Replace(Environment.NewLine, Environment.NewLine + "\t"));
                                return await db.FetchAsync<dynamic>(sql, lastName + "%", firstName + "%");
                            }
                        });
                        visitsByNumbersQueries.Add(key, async (numbers) =>
                        {
                            using (var db = new Database(key))
                            {
                                var sql = @"select *
from zisv21..visit with (nolock)
where number in (@0)
order by admissiondate";
                                Console.WriteLine("{0}: {1}", key, sql.Replace(Environment.NewLine, Environment.NewLine + "\t"));
                                return await db.FetchAsync<dynamic>(sql, numbers);
                            }
                        });
                        patientsByVisitNumbersQueries.Add(key, async (numbers) =>
                        {
                            using (var db = new Database(key))
                            {
                                var sql = @"select * 
from zisv21..patient with (nolock)
where id in
(
	select patientid
	from zisv21..visit with (nolock)
	where number in (@0)
)";
                                Console.WriteLine("{0}: {1}", key, sql.Replace(Environment.NewLine, Environment.NewLine + "\t"));
                                return await db.FetchAsync<dynamic>(sql, numbers);
                            }
                        });
                        visitDetailsByVisitNumbersQuery.Add(key, async (numbers) =>
                        {
                            using (var db = new Database(key))
                            {
                                var sql = @"select *
from zisv21..visitdetail with (nolock)
where visitnumber in (@0)
order by visitnumber, fromdate";
                                Console.WriteLine("{0}: {1}", key, sql.Replace(Environment.NewLine, Environment.NewLine + "\t"));
                                return await db.FetchAsync<dynamic>(sql, numbers);
                            }
                        });
                        doctorsByNumbersQuery.Add(key, async (numbers) =>
                        {
                            using (var db = new Database(key))
                            {
                                var sql = @"select *
from zisv21..doctor with (nolock)
where number in (@0)";
                                Console.WriteLine("{0}: {1}", key, sql.Replace(Environment.NewLine, Environment.NewLine + "\t"));
                                return await db.FetchAsync<dynamic>(sql, numbers);
                            }
                        });
                        break;
                    case "ZISv23":
                        patientByIdQueries.Add(key, async (id) =>
                        {
                            var connectionString = ConfigurationManager.ConnectionStrings[key].ConnectionString;
                            var requestUri = string.Format(@"zis_patient/_all_docs?include_docs=true&key=""{0}""", id.PadLeft(10, '0'));
                            Console.WriteLine("{0}: {1}", key, requestUri);
                            return await HttpGet(connectionString, requestUri).ConfigureAwait(false);
                        });
                        visitsByPatientIdQueries.Add(key, async (id) =>
                        {
                            var connectionString = ConfigurationManager.ConnectionStrings[key].ConnectionString;
                            var requestUri = string.Format(@"zis_visit/_design/docs/_view/by_patientid?include_docs=true&key=""{0}""", id.PadLeft(8, '0'));
                            Console.WriteLine("{0}: {1}", key, requestUri);
                            return await HttpGet(connectionString, requestUri).ConfigureAwait(false);
                        });
                        visitsByNumbersQueries.Add(key, async (numbers) =>
                        {
                            var connectionString = ConfigurationManager.ConnectionStrings[key].ConnectionString;
                            var requestUri = string.Format(@"zis_visit/_all_docs?include_docs=true&keys=[{0}]", string.Join(",", (from number in numbers as IEnumerable<string> select string.Concat("\"", number.PadLeft(8, '0'), "\""))));
                            Console.WriteLine("{0}: {1}", key, requestUri);
                            return await HttpGet(connectionString, requestUri).ConfigureAwait(false);
                        });
                        patientsByVisitNumbersQueries.Add(key, async (numbers) =>
                        {
                            var connectionString = ConfigurationManager.ConnectionStrings[key].ConnectionString;
                            var requestUri = string.Format(@"zis_visit/_all_docs?include_docs=true&keys=[{0}]", string.Join(",", (from number in numbers as IEnumerable<string> select string.Concat("\"", number.PadLeft(8, '0'), "\""))));
                            Console.WriteLine("{0}: {1}", key, requestUri);
                            using (var client = CreateHttpClient(new Uri(connectionString)))
                            {
                                var response = await client.GetAsync(requestUri).ConfigureAwait(false);
                                var content = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
                                //var task = Task.Run(() =>
                                //{
                                var result = JsonConvert.DeserializeObject<ExpandoObject>(content, new ExpandoObjectConverter());

                                if (((dynamic)result).rows.Count == 0)
                                    return null;

                                var patientIds = /*return*/ (from row in ((dynamic)result).rows as IEnumerable<dynamic>
                                                             where ((IDictionary<string, Object>)row).ContainsKey("doc") && (IDictionary<string, Object>)row.doc != null && ((IDictionary<string, Object>)row.doc).ContainsKey("PatientId")
                                                             select row.doc.PatientId as string).ToList();
                                //});
                                //await task.ConfigureAwait(false);

                                requestUri = string.Format(@"zis_patient/_all_docs?include_docs=true&keys=[{0}]", string.Join(",", (from number in patientIds select string.Concat("\"", number.PadLeft(10, '0'), "\""))));
                                Console.WriteLine("{0}: {1}", key, requestUri);
                                return await HttpGet(connectionString, requestUri).ConfigureAwait(false);
                            }
                        });
                        visitDetailsByVisitNumbersQuery.Add(key, async (numbers) =>
                        {
                            var connectionString = ConfigurationManager.ConnectionStrings[key].ConnectionString;
                            var requestUri = string.Format(@"zis_visit/_all_docs?include_docs=true&keys=[{0}]", string.Join(",", (from number in numbers as IEnumerable<string> select string.Concat("\"", number.PadLeft(8, '0'), "\""))));
                            Console.WriteLine("{0}: {1}", key, requestUri);
                            using (var client = CreateHttpClient(new Uri(connectionString)))
                            {
                                var response = await client.GetAsync(requestUri).ConfigureAwait(false);
                                var content = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
                                //return await Task.Run(() =>
                                //{
                                var result = JsonConvert.DeserializeObject<ExpandoObject>(content, new ExpandoObjectConverter());

                                if (((dynamic)result).rows.Count == 0)
                                    return null;

                                return (from row in ((dynamic)result).rows as IEnumerable<dynamic>
                                        where ((IDictionary<string, Object>)row).ContainsKey("doc") && (IDictionary<string, Object>)row.doc != null && ((IDictionary<string, Object>)row.doc).ContainsKey("Transfers")
                                        from transfer in ((IDictionary<string, Object>)row.doc)["Transfers"] as IEnumerable<dynamic>
                                        orderby row.doc.Id, transfer.FromDate
                                        select transfer).ToList();
                                //}).ConfigureAwait(false);
                            }
                        });
                        doctorsByNumbersQuery.Add(key, async (numbers) =>
                        {
                            var connectionString = ConfigurationManager.ConnectionStrings[key].ConnectionString;
                            var requestUri = string.Format(@"zis_doctor/_all_docs?include_docs=true&keys=[{0}]", string.Join(",", (from number in numbers as IEnumerable<string> select string.Concat("\"", number.PadLeft(6, '0'), "\""))));
                            Console.WriteLine("{0}: {1}", key, requestUri);
                            return await HttpGet(connectionString, requestUri).ConfigureAwait(false);
                        });
                        bedOccupationByWardIdsQuery.Add(key, async (ids) =>
                        {
                            var connectionString = ConfigurationManager.ConnectionStrings[key].ConnectionString;
                            var requestUri = string.Format(@"zis_ward/_design/docs/_view/by_id?include_docs=true&keys=[{0}]", string.Join(",", (from id in ids as IEnumerable<string> select string.Concat("\"", id.PadLeft(4, '0'), "\""))));
                            Console.WriteLine("{0}: {1}", key, requestUri);
                            using (var client = CreateHttpClient(new Uri(connectionString)))
                            {
                                var response = await client.GetAsync(requestUri).ConfigureAwait(false);
                                var content = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
                                //return await Task.Run(() =>
                                //{
                                var result = JsonConvert.DeserializeObject<ExpandoObject>(content, new ExpandoObjectConverter());

                                if (((dynamic)result).rows.Count == 0)
                                    return null;

                                return (from row in ((dynamic)result).rows as IEnumerable<dynamic>
                                        where ((IDictionary<string, Object>)row).ContainsKey("doc") && (IDictionary<string, Object>)row.doc != null && ((IDictionary<string, Object>)row.doc).ContainsKey("Beds")
                                        from bed in ((IDictionary<string, Object>)row.doc)["Beds"] as IEnumerable<dynamic>
                                        let location = string.Concat((bed as IDictionary<string, Object>).ContainsKey("RoomId") ? bed.RoomId : string.Empty, "-", (bed as IDictionary<string, Object>).ContainsKey("BedId") ? bed.BedId : string.Empty)
                                        orderby location
                                        select bed).ToList();
                                //}).ConfigureAwait(false);
                            }
                        });
                        break;
                    case "XdeCache":
                        patientByIdQueries.Add(key, async (id) =>
                        {
                            var connectionString = ConfigurationManager.ConnectionStrings[key].ConnectionString;
                            var requestUri = string.Format(@"patient/_design/docs/_view/by_id?include_docs=true&key=""{0}""", id.PadLeft(10, '0'));
                            Console.WriteLine("{0}: {1}", key, requestUri);
                            using (var client = CreateHttpClient(new Uri(connectionString)))
                            {
                                var response = await client.GetAsync(requestUri).ConfigureAwait(false);
                                var content = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
                                //return await Task.Run(async () =>
                                //{
                                var result = JsonConvert.DeserializeObject<ExpandoObject>(content, new ExpandoObjectConverter());

                                var mergedPatid = (from row in ((dynamic)result).rows as IEnumerable<dynamic>
                                                   where row.doc.PAT_ID != id
                                                   select row.doc.PAT_ID as string).FirstOrDefault();
                                if (!mergedPatid.IsNullOrEmpty())
                                    return await patientByIdQueries[key](mergedPatid);

                                if (((dynamic)result).rows.Count == 0)
                                    return null;

                                return (from row in ((dynamic)result).rows as IEnumerable<dynamic>
                                        where ((IDictionary<string, Object>)row).ContainsKey("doc")
                                        select row.doc).ToList();
                                //}).ConfigureAwait(false);
                            }
                        });
                        visitsByPatientIdQueries.Add(key, async (id) =>
                        {
                            var connectionString = ConfigurationManager.ConnectionStrings[key].ConnectionString;
                            var requestUri = string.Format(@"visit/_design/docs/_view/by_patid?include_docs=true&key=""{0}""", id.PadLeft(8, '0'));
                            Console.WriteLine("{0}: {1}", key, requestUri);
                            return await HttpGet(connectionString, requestUri).ConfigureAwait(false);
                        });
                        visitsByNumbersQueries.Add(key, async (numbers) =>
                        {
                            var connectionString = ConfigurationManager.ConnectionStrings[key].ConnectionString;
                            var requestUri = string.Format(@"visit/_all_docs?include_docs=true&keys=[{0}]", string.Join(",", (from number in numbers as IEnumerable<string> select string.Concat("\"", number.PadLeft(8, '0'), "\""))));
                            Console.WriteLine("{0}: {1}", key, requestUri);
                            return await HttpGet(connectionString, requestUri).ConfigureAwait(false);
                        });
                        patientsByVisitNumbersQueries.Add(key, async (numbers) =>
                        {
                            var connectionString = ConfigurationManager.ConnectionStrings[key].ConnectionString;
                            var requestUri = string.Format(@"visit/_all_docs?include_docs=true&keys=[{0}]", string.Join(",", (from number in numbers as IEnumerable<string> select string.Concat("\"", number.PadLeft(8, '0'), "\""))));
                            Console.WriteLine("{0}: {1}", key, requestUri);
                            using (var client = CreateHttpClient(new Uri(connectionString)))
                            {
                                var response = await client.GetAsync(requestUri).ConfigureAwait(false);
                                var content = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
                                //var task = Task.Run(() =>
                                //{
                                var result = JsonConvert.DeserializeObject<ExpandoObject>(content, new ExpandoObjectConverter());

                                if (((dynamic)result).rows.Count == 0)
                                    return null;

                                var patientIds = (from row in ((dynamic)result).rows as IEnumerable<dynamic>
                                                  where ((IDictionary<string, Object>)row).ContainsKey("doc") && ((IDictionary<string, Object>)row.doc).ContainsKey("PAT_ID")
                                                  select row.doc.PAT_ID as string).ToList();
                                //});
                                //await task.ConfigureAwait(false);

                                requestUri = string.Format(@"patient/_all_docs?include_docs=true&keys=[{0}]", string.Join(",", (from number in patientIds select string.Concat("\"", number.PadLeft(10, '0'), "\""))));
                                Console.WriteLine("{0}: {1}", key, requestUri);
                                return await HttpGet(connectionString, requestUri).ConfigureAwait(false);
                            }
                        });
                        visitDetailsByVisitNumbersQuery.Add(key, async (numbers) =>
                        {
                            var connectionString = ConfigurationManager.ConnectionStrings[key].ConnectionString;
                            var requestUri = string.Format(@"visit/_all_docs?include_docs=true&keys=[{0}]", string.Join(",", (from number in numbers as IEnumerable<string> select string.Concat("\"", number.PadLeft(8, '0'), "\""))));
                            Console.WriteLine("{0}: {1}", key, requestUri);
                            using (var client = CreateHttpClient(new Uri(connectionString)))
                            {
                                var response = await client.GetAsync(requestUri).ConfigureAwait(false);
                                var content = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
                                //return await Task.Run(() =>
                                //{
                                var result = JsonConvert.DeserializeObject<ExpandoObject>(content, new ExpandoObjectConverter());

                                if (((dynamic)result).rows.Count == 0)
                                    return null;

                                return (from row in ((dynamic)result).rows as IEnumerable<dynamic>
                                        where ((IDictionary<string, Object>)row).ContainsKey("doc") && ((IDictionary<string, Object>)row.doc).ContainsKey("Transfers")
                                        from transfer in ((IDictionary<string, Object>)row.doc)["Transfers"] as IEnumerable<dynamic>
                                        orderby transfer.VISIT_ID, transfer.FROM_DATE, transfer.FROM_TIME
                                        select transfer).ToList();
                                //}).ConfigureAwait(false);
                            }
                        });
                        doctorsByNumbersQuery.Add(key, async (numbers) =>
                        {
                            var connectionString = ConfigurationManager.ConnectionStrings[key].ConnectionString;
                            var requestUri = string.Format(@"doctor/_all_docs?include_docs=true&keys=[{0}]", string.Join(",", (from number in numbers as IEnumerable<string> select string.Concat("\"", number.PadLeft(6, '0'), "\""))));
                            Console.WriteLine("{0}: {1}", key, requestUri);
                            return await HttpGet(connectionString, requestUri).ConfigureAwait(false);
                        });
                        bedOccupationByWardIdsQuery.Add(key, async (ids) =>
                        {
                            var connectionString = ConfigurationManager.ConnectionStrings[key].ConnectionString;
                            var requestUri = string.Format(@"bedocc/_all_docs?include_docs=true&keys=[{0}]", string.Join(",", (from id in ids as IEnumerable<string> select string.Concat("\"", id.PadLeft(4, '0'), "\""))));
                            Console.WriteLine("{0}: {1}", key, requestUri);
                            using (var client = CreateHttpClient(new Uri(connectionString)))
                            {
                                var response = await client.GetAsync(requestUri).ConfigureAwait(false);
                                var content = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
                                //return await Task.Run(() =>
                                //{
                                var result = JsonConvert.DeserializeObject<ExpandoObject>(content, new ExpandoObjectConverter());

                                if (((dynamic)result).rows.Count == 0)
                                    return null;

                                return (from row in ((dynamic)result).rows as IEnumerable<dynamic>
                                        where ((IDictionary<string, Object>)row).ContainsKey("doc") && ((IDictionary<string, Object>)row.doc).ContainsKey("Beds")
                                        from bed in ((IDictionary<string, Object>)row.doc)["Beds"] as IEnumerable<dynamic>
                                        where !string.IsNullOrEmpty(bed.VISIT_ID)
                                        orderby bed.ROOM_ID, bed.BED_ID
                                        select bed).ToList();
                                //}).ConfigureAwait(false);
                            }
                        });
                        break;
                    case "Glims":
                    case "Glims Test":
                        patientByIdQueries.Add(key, async (id) =>
                        {
                            using (var db = new Database(key) { EnableNamedParams = false })
                            {
                                var sql = @"select *
from PUB.Identification
inner join PUB.Correspondent on crsp_Id = idnt_Target
inner join PUB.Person on prsn_Correspondent = crsp_Id
left outer join PUB.Municipality on mncp_Id = crsp_Municipality
left outer join PUB.Country on cnty_Id = mncp_Country
left outer join PUB.CountryName on ml68_Name = cnty_Id and ml68_Language = 3
left outer join PUB.HCProvider on hcpr_Id = prsn_FamilyDoctor
where idnt_Code = ?";
                                Console.WriteLine("{0}: {1}", key, sql.Replace(Environment.NewLine, Environment.NewLine + "\t"));
                                return await db.FetchAsync<dynamic>(sql, id);
                            }
                        });
                        visitsByPatientIdQueries.Add(key, async (id) =>
                        {
                            using (var db = new Database(key) { EnableNamedParams = false })
                            {
                                var sql = @"select *
from PUB.Encounter
left outer join PUB.EncounterType on entp_Id = enct_Type
left outer join PUB.HCProvider on hcpr_Id = enct_Physician
left outer join PUB.Institution on inst_Id = enct_Institution
where enct_Person = 
(
   select prsn_Id
   from PUB.Identification
   inner join PUB.Correspondent on idnt_Target = crsp_Id
   inner join PUB.Person on prsn_Correspondent = crsp_Id
   where idnt_Code = ?
)";
                                Console.WriteLine("{0}: {1}", key, sql.Replace(Environment.NewLine, Environment.NewLine + "\t"));
                                return await db.FetchAsync<dynamic>(sql, id);
                            }
                        });
                        patientsByNameQueries.Add(key, async (lastName, firstName) =>
                        {
                            using (var db = new Database(key) { EnableNamedParams = false })
                            {
                                var sql = @"select top 100 *
from PUB.Identification
inner join PUB.Correspondent on crsp_Id = idnt_Target
inner join PUB.Person on prsn_Correspondent = crsp_Id
left outer join PUB.Municipality on mncp_Id = crsp_Municipality
left outer join PUB.Country on cnty_Id = mncp_Country
left outer join PUB.CountryName on ml68_Name = cnty_Id and ml68_Language = 3
left outer join PUB.HCProvider on hcpr_Id = prsn_FamilyDoctor
where prsn_LastName like ? and prsn_FirstName like ?
order by prsn_LastName, prsn_FirstName";
                                Console.WriteLine("{0}: {1}", key, sql.Replace(Environment.NewLine, Environment.NewLine + "\t"));
                                //return await db.FetchAsync<dynamic>(sql, lastName + "%", firstName + "%"); //NOT WORKING
                                sql = string.Format(@"select top 100 *
from PUB.Identification
inner join PUB.Correspondent on crsp_Id = idnt_Target
inner join PUB.Person on prsn_Correspondent = crsp_Id
left outer join PUB.Municipality on mncp_Id = crsp_Municipality
left outer join PUB.Country on cnty_Id = mncp_Country
left outer join PUB.CountryName on ml68_Name = cnty_Id and ml68_Language = 3
left outer join PUB.HCProvider on hcpr_Id = prsn_FamilyDoctor
where prsn_LastName like '{0}' and prsn_FirstName like '{1}'
order by prsn_LastName, prsn_FirstName", lastName + "%", firstName + "%");
                                return await db.FetchAsync<dynamic>(sql);
                            }
                        });
                        visitsByNumbersQueries.Add(key, async (numbers) =>
                        {
                            using (var db = new Database(key) { EnableNamedParams = false })
                            {
                                var sql = @"select *
from PUB.Encounter
left outer join PUB.EncounterType on entp_Id = enct_Type
left outer join PUB.HCProvider on hcpr_Id = enct_Physician
left outer join PUB.Institution on inst_Id = enct_Institution
where enct_ExternalId in (?)";
                                Console.WriteLine("{0}: {1}", key, sql.Replace(Environment.NewLine, Environment.NewLine + "\t"));
                                //return await db.FetchAsync<dynamic>(sql, numbers); //NOT WORKING
                                sql = string.Format(@"select *
from PUB.Encounter
left outer join PUB.EncounterType on entp_Id = enct_Type
left outer join PUB.HCProvider on hcpr_Id = enct_Physician
left outer join PUB.Institution on inst_Id = enct_Institution
where enct_ExternalId in ({0})", string.Join(",", (from number in numbers as IEnumerable<string> select string.Concat("'", number.PadLeft(8, '0'), "'"))));
                                return await db.FetchAsync<dynamic>(sql);
                            }
                        });
                        patientsByVisitNumbersQueries.Add(key, async (numbers) =>
                        {
                            using (var db = new Database(key) { EnableNamedParams = false })
                            {
                                var sql = @"select *
from PUB.Identification
inner join PUB.Correspondent on idnt_Target = crsp_Id
inner join PUB.Person on prsn_Correspondent = crsp_Id
where prsn_Id in 
(
	select enct_Person
	from PUB.Encounter
	where enct_ExternalId in (?)
)";
                                Console.WriteLine("{0}: {1}", key, sql.Replace(Environment.NewLine, Environment.NewLine + "\t"));
                                //return await db.FetchAsync<dynamic>(sql, numbers); //NOT WORKING
                                sql = string.Format(@"select enct_Person
from PUB.Encounter
where enct_ExternalId in ({0})", string.Join(",", (from number in numbers as IEnumerable<string> select string.Concat("'", number.PadLeft(8, '0'), "'"))));
                                var patientIds = await db.FetchAsync<int>(sql);
                                sql = string.Format(@"select *
from PUB.Identification
inner join PUB.Correspondent on idnt_Target = crsp_Id
inner join PUB.Person on prsn_Correspondent = crsp_Id
where prsn_Id in ({0})", string.Join(",", (from id in patientIds select id.ToString())));
                                return await db.FetchAsync<dynamic>(sql);
                            }
                        });
                        visitDetailsByVisitNumbersQuery.Add(key, async (numbers) =>
                        {
                            using (var db = new Database(key) { EnableNamedParams = false })
                            {
                                var sql = @"select *
from PUB.Stay
where stay_Encounter in 
(
	select enct_Id
	from PUB.Encounter
	where enct_ExternalId in (?)
)";
                                Console.WriteLine("{0}: {1}", key, sql.Replace(Environment.NewLine, Environment.NewLine + "\t"));
                                //return await db.FetchAsync<dynamic>(sql, numbers); //NOT WORKING
                                sql = string.Format(@"select enct_Id
from PUB.Encounter
where enct_ExternalId in ({0})", string.Join(",", (from number in numbers as IEnumerable<string> select string.Concat("'", number.PadLeft(8, '0'), "'"))));
                                var visitIds = await db.FetchAsync<int>(sql);
                                if (!visitIds.Any())
                                    return Enumerable.Empty<dynamic>().ToList();
                                sql = string.Format(@"select *
from PUB.Stay
where stay_Encounter in ({0})", string.Join(",", (from id in visitIds select id.ToString())));
                                return await db.FetchAsync<dynamic>(sql);
                            }
                        });
                        doctorsByNumbersQuery.Add(key, async (numbers) =>
                        {
                            using (var db = new Database(key) { EnableNamedParams = false })
                            {
                                var sql = @"select *
from PUB.Encounter
left outer join PUB.EncounterType on entp_Id = enct_Type
left outer join PUB.HCProvider on hcpr_Id = enct_Physician
left outer join PUB.Institution on inst_Id = enct_Institution
where enct_ExternalId in (?)";
                                Console.WriteLine("{0}: {1}", key, sql.Replace(Environment.NewLine, Environment.NewLine + "\t"));
                                //return await db.FetchAsync<dynamic>(sql, numbers); //NOT WORKING
                                sql = string.Format(@"select *
from PUB.HCProvider
left outer join PUB.Correspondent on crsp_Id = hcpr_Correspondent
left outer join PUB.Organization on org_Id = hcpr_Practice
where hcpr_Code in ({0})", string.Join(",", (from number in numbers as IEnumerable<string> select string.Concat("'", number.PadLeft(5, '0'), "'"))));
                                return await db.FetchAsync<dynamic>(sql);
                            }
                        });
                        break;
                    case "Agfa":
                    case "Agfa Test":
                        patientByIdQueries.Add(key, async (id) =>
                        {
                            using (var db = new Database(key))
                            {
                                var sql = @"select p.*, d_hospitalkey
from patients p
inner join doctors d on d_key = p_physician
where p_code = @0";
                                Console.WriteLine("{0}: {1}", key, sql.Replace(Environment.NewLine, Environment.NewLine + "\t"));
                                return await db.FetchAsync<dynamic>(sql, id);
                            }
                        });
                        visitsByPatientIdQueries.Add(key, async (id) =>
                        {
                            using (var db = new Database(key))
                            {
                                var sql = @"select se.*, p_code
from service_episodes se
inner join patients p on p_key = se_p_key
where p_code = @0
order by se.se_admission_date_hospital";
                                Console.WriteLine("{0}: {1}", key, sql.Replace(Environment.NewLine, Environment.NewLine + "\t"));
                                return await db.FetchAsync<dynamic>(sql, id.PadLeft(10, '0'));
                            }
                        });
                        patientsByNameQueries.Add(key, async (lastName, firstName) =>
                        {
                            using (var db = new Database(key))
                            {
                                var sql = @"select p.*, d_hospitalkey
from patient p
inner join doctors d on d_key = p_physician
where lower(pat_lastname) like @0 and lower(pat_firstname) like @1
and rownum <= 100
order by pat_lastname, pat_firstname";
                                Console.WriteLine("{0}: {1}", key, sql.Replace(Environment.NewLine, Environment.NewLine + "\t"));
                                return await db.FetchAsync<dynamic>(sql, lastName + "%", firstName + "%");
                            }
                        });
                        visitsByNumbersQueries.Add(key, async (numbers) =>
                        {
                            using (var db = new Database(key))
                            {
                                var sql = @"select se.*, p_code
from service_episodes se
inner join patients p on p_key = se_p_key
where se_admission_number in (@0)
order by se_admission_date_hospital";
                                Console.WriteLine("{0}: {1}", key, sql.Replace(Environment.NewLine, Environment.NewLine + "\t"));
                                return await db.FetchAsync<dynamic>(sql, numbers);
                            }
                        });
                        patientsByVisitNumbersQueries.Add(key, async (numbers) =>
                        {
                            using (var db = new Database(key))
                            {
                                var sql = @"select p.*, d_hospitalkey
from patients p
inner join doctors d on d_key = p_physician
inner join service_episodes se on se_p_key = p_key
where se_admission_number in (@0)";
                                Console.WriteLine("{0}: {1}", key, sql.Replace(Environment.NewLine, Environment.NewLine + "\t"));
                                return await db.FetchAsync<dynamic>(sql, numbers);
                            }
                        });
                        visitDetailsByVisitNumbersQuery.Add(key, async (numbers) =>
                        {
                            using (var db = new Database(key))
                            {
                                var sql = @"select *
from transfers
where tr_admission_nr in (@0)
order by tr_admission_nr, tr_date_from";
                                Console.WriteLine("{0}: {1}", key, sql.Replace(Environment.NewLine, Environment.NewLine + "\t"));
                                return await db.FetchAsync<dynamic>(sql, numbers);
                            }
                        });
                        doctorsByNumbersQuery.Add(key, async (numbers) =>
                        {
                            using (var db = new Database(key))
                            {
                                var sql = @"select *
from doctors
left outer join services on s_key = d_service
left outer join hospitals on h_key = d_hospital
left outer join specialism on sp_key = d_specialism
where d_hospitalkey in (@0)";
                                Console.WriteLine("{0}: {1}", key, sql.Replace(Environment.NewLine, Environment.NewLine + "\t"));
                                return await db.FetchAsync<dynamic>(sql, numbers);
                            }
                        });
                        break;
                    case "Cyberlab":
                    case "Cyberlab Test":
                        patientByIdQueries.Add(key, async (id) =>
                        {
                            using (var db = new Database(key))
                            {
                                var sql = @"select *
from patient
left outer join account on acnt_patient = pat_id
where pat_code = @0";
                                Console.WriteLine("{0}: {1}", key, sql.Replace(Environment.NewLine, Environment.NewLine + "\t"));
                                return await db.FetchAsync<dynamic>(sql, id);
                            }
                        });
                        visitsByPatientIdQueries.Add(key, async (id) =>
                        {
                            using (var db = new Database(key))
                            {
                                var sql = @"select *
from visit 
inner join patient on pat_id = vst_patient
inner join ""GROUP"" on grp_id = vst_group
where pat_code = @0
order by vst_startdate";
                                Console.WriteLine("{0}: {1}", key, sql.Replace(Environment.NewLine, Environment.NewLine + "\t"));
                                return await db.FetchAsync<dynamic>(sql, id.PadLeft(10, '0'));
                            }
                        });
                        patientsByNameQueries.Add(key, async (lastName, firstName) =>
                        {
                            using (var db = new Database(key))
                            {
                                var sql = @"select *
from patient
left outer join account on acnt_patient = pat_id
where lower(pat_lastname) like @0 and lower(pat_firstname) like @1
and rownum <= 100
order by pat_lastname, pat_firstname";
                                Console.WriteLine("{0}: {1}", key, sql.Replace(Environment.NewLine, Environment.NewLine + "\t"));
                                return await db.FetchAsync<dynamic>(sql, lastName + "%", firstName + "%");
                            }
                        });
                        visitsByNumbersQueries.Add(key, async (numbers) =>
                        {
                            using (var db = new Database(key))
                            {
                                var sql = @"select *
from visit 
inner join ""GROUP"" on grp_id = vst_group
where vst_code in (@0)";
                                Console.WriteLine("{0}: {1}", key, sql.Replace(Environment.NewLine, Environment.NewLine + "\t"));
                                return await db.FetchAsync<dynamic>(sql, (from number in numbers as IEnumerable<string> select number.PadLeft(8, '0')));
                            }
                        });
                        patientsByVisitNumbersQueries.Add(key, async (numbers) =>
                        {
                            using (var db = new Database(key))
                            {
                                var sql = @"select patient.*, account.*
from patient 
left outer join account on acnt_patient = pat_id
inner join visit on vst_patient = pat_id
where vst_code in (@0)";
                                Console.WriteLine("{0}: {1}", key, sql.Replace(Environment.NewLine, Environment.NewLine + "\t"));
                                return await db.FetchAsync<dynamic>(sql, (from number in numbers as IEnumerable<string> select number.PadLeft(8, '0')));
                            }
                        });
                        visitDetailsByVisitNumbersQuery.Add(key, async (numbers) =>
                        {
                            return await visitsByNumbersQueries[key](numbers);
                        });
                        doctorsByNumbersQuery.Add(key, async (numbers) =>
                        {
                            using (var db = new Database(key))
                            {
                                var sql = @"select *
from issuer
where iss_code in (@0)";
                                Console.WriteLine("{0}: {1}", key, sql.Replace(Environment.NewLine, Environment.NewLine + "\t"));
                                return await db.FetchAsync<dynamic>(sql, (from number in numbers as IEnumerable<string> select number.PadLeft(6, '0')));
                            }
                        });
                        break;
                    case "Infohos Prs":
                    case "Infohos Prs Test":
                        patientByIdQueries.Add(key, async (id) =>
                        {
                            using (var db = new Database(key))
                            {
                                var sql = string.Format(@"select p.*, dr.nr_id as huisarts_id
from {0}..tab_pat p with (nolock)
left outer join {0}..tab_dokters dr with (nolock) on dr.nr_dok = p.huisarts
where p.nr_pat = @0", key == "Infohos Prs" ? "prs054" : "prs954");
                                Console.WriteLine("{0}: {1}", key, sql.Replace(Environment.NewLine, Environment.NewLine + "\t"));
                                return await db.FetchAsync<dynamic>(sql, id.PadLeft(10, '0'));
                            }
                        });
                        visitsByPatientIdQueries.Add(key, async (id) =>
                        {
                            using (var db = new Database(key))
                            {
                                var sql = string.Format(@"select d.*, dr.nr_id as dok_verwezen_id
from {0}..dossier d with (nolock)
left outer join {0}..tab_dokters dr with (nolock) on dr.nr_dok = d.nr_dok_verwezen
where d.nr_pat = @0
order by d.dat_opn", key == "Infohos Prs" ? "prs054" : "prs954");
                                Console.WriteLine("{0}: {1}", key, sql.Replace(Environment.NewLine, Environment.NewLine + "\t"));
                                var visits = await db.FetchAsync<dynamic>(sql, id.PadLeft(10, '0'));

                                sql = string.Format(@"select vo.*, dr.nr_id as dok_verwezen_id
from {0}..vooropname vo with (nolock)
left outer join {0}..tab_dokters dr with (nolock) on dr.nr_dok = vo.nr_dok
where vo.nr_pat = @0
order by vo.dat_begin", key == "Infohos Prs" ? "prs054" : "prs954");
                                Console.WriteLine("{0}: {1}", key, sql.Replace(Environment.NewLine, Environment.NewLine + "\t"));
                                visits.AddRange(await db.FetchAsync<dynamic>(sql, id.PadLeft(10, '0')));
                                return visits;
                            }
                        });
                        patientsByNameQueries.Add(key, async (lastName, firstName) =>
                        {
                            using (var db = new Database(key))
                            {
                                var sql = string.Format(@"select top 100 p.*, dr.nr_id as huisarts_id
from {0}..tab_pat p with (nolock)
left outer join {0}..tab_dokters dr with (nolock) on dr.nr_dok = p.huisarts
where p.fnaam_pat like @0 and p.vnaam_pat like @1
order by p.fnaam_pat, p.vnaam_pat", key == "Infohos Prs" ? "prs054" : "prs954");
                                Console.WriteLine("{0}: {1}", key, sql.Replace(Environment.NewLine, Environment.NewLine + "\t"));
                                return await db.FetchAsync<dynamic>(sql, lastName + "%", firstName + "%");
                            }
                        });
                        visitsByNumbersQueries.Add(key, async (numbers) =>
                        {
                            using (var db = new Database(key))
                            {
                                var sql = string.Format(@"select d.*, dr.nr_id as dok_verwezen_id
from {0}..dossier d with (nolock)
left outer join {0}..tab_dokters dr with (nolock) on dr.nr_dok = d.nr_dok_verwezen
where d.nr_dos in (@0)
order by d.dat_opn", key == "Infohos Prs" ? "prs054" : "prs954");
                                Console.WriteLine("{0}: {1}", key, sql.Replace(Environment.NewLine, Environment.NewLine + "\t"));
                                var visits = await db.FetchAsync<dynamic>(sql, (from number in numbers as IEnumerable<string> select number.PadLeft(8, '0')));

                                sql = string.Format(@"select vo.*, dr.nr_id as dok_verwezen_id
from {0}..vooropname vo with (nolock)
left outer join {0}..tab_dokters dr with (nolock) on dr.nr_dok = vo.nr_dok
where vo.nr_vooropname in (@0)
order by vo.dat_begin", key == "Infohos Prs" ? "prs054" : "prs954");
                                Console.WriteLine("{0}: {1}", key, sql.Replace(Environment.NewLine, Environment.NewLine + "\t"));
                                visits.AddRange(await db.FetchAsync<dynamic>(sql, (from number in numbers as IEnumerable<string> select number.PadLeft(8, '0'))));
                                return visits;
                            }
                        });
                        patientsByVisitNumbersQueries.Add(key, async (numbers) =>
                        {
                            using (var db = new Database(key))
                            {
                                var sql = string.Format(@"select p.*, dr.nr_id as huisarts_id
from {0}..tab_pat p with (nolock)
inner join {0}..tab_dokters dr with (nolock) on dr.nr_dok = p.huisarts
inner join {0}..dossier d on p.nr_pat = d.nr_pat
where d.nr_dos in (@0)", key == "Infohos Prs" ? "prs054" : "prs954");
                                Console.WriteLine("{0}: {1}", key, sql.Replace(Environment.NewLine, Environment.NewLine + "\t"));
                                return await db.FetchAsync<dynamic>(sql, (from number in numbers as IEnumerable<string> select number.PadLeft(8, '0')));
                            }
                        });
                        visitDetailsByVisitNumbersQuery.Add(key, async (numbers) =>
                        {
                            using (var db = new Database(key))
                            {
                                var sql = string.Format(@"select vp.*--, v.veoms
from {0}..verper vp with (nolock)
--left outer join {1}..verpleeg v with (nolock) on v.venr = vp.nr_ve
where vp.nr_dos in (@0)
order by vp.nr_dos, vp.dat_begin", key == "Infohos Prs" ? "prs054" : "prs954", key == "Infohos Prs" ? "sql05.apot054" : "sql05.apot954");
                                Console.WriteLine("{0}: {1}", key, sql.Replace(Environment.NewLine, Environment.NewLine + "\t"));
                                return await db.FetchAsync<dynamic>(sql, (from number in numbers as IEnumerable<string> select number.PadLeft(8, '0')));
                            }
                        });
                        doctorsByNumbersQuery.Add(key, async (numbers) =>
                        {
                            using (var db = new Database(key))
                            {
                                var sql = string.Format(@"select dr.*
from {0}..tab_dokters dr with (nolock)
where dr.nr_id in (@0)", key == "Infohos Prs" ? "prs054" : "prs954");
                                Console.WriteLine("{0}: {1}", key, sql.Replace(Environment.NewLine, Environment.NewLine + "\t"));
                                return await db.FetchAsync<dynamic>(sql, (from number in numbers as IEnumerable<string> select number.PadLeft(6, '0')));
                            }
                        });
                        break;
                    case "Infohos CPD":
                        patientByIdQueries.Add(key, async (id) =>
                        {
                            using (var db = new Database(key))
                            {
                                var sql = @"select p.*, 
(
	select luv.Description
	from cpd_azdelta_prod..LUValue luv with (nolock)
	inner join cpd_azdelta_prod..lutable lut with (nolock) on lut.LUTableID = luv.LUTableID
	where lut.TableName = 'SEXES' and luv.LUValueID = p.SexId
) as SexDescription,
(
	select luv.Description
	from cpd_azdelta_prod..LUValue luv with (nolock)
	inner join cpd_azdelta_prod..lutable lut with (nolock) on lut.LUTableID = luv.LUTableID
	where lut.TableName = 'NATIONALITIES' and luv.LUValueID = p.NationalityID
) as NationalityDescription,
(
	select luv.Description
	from cpd_azdelta_prod..LUValue luv with (nolock)
	inner join cpd_azdelta_prod..lutable lut with (nolock) on lut.LUTableID = luv.LUTableID
	where lut.TableName = 'LANGUAGES' and luv.LUValueID = p.LanguageID
) as LanguageDescription,
dr.administrativeid as GeneralPractitionerAdministrativeId, dr.LastName as GeneralPractitionerLastName, dr.FirstName as GeneralPractitionerFirstName
from cpd_azdelta_prod..cpdpatient p with (nolock)
left outer join cpd_azdelta_prod..cpddoctor dr with (nolock) on dr.cpddoctorid = p.generalpractitionerid 
where p.patientnr = @0";
                                Console.WriteLine("{0}: {1}", key, sql.Replace(Environment.NewLine, Environment.NewLine + "\t"));
                                return await db.FetchAsync<dynamic>(sql, id.PadLeft(10, '0'));
                            }
                        });
                        visitsByPatientIdQueries.Add(key, async (id) =>
                        {
                            using (var db = new Database(key))
                            {
                                var sql = string.Format(@"select p.PatientNr, d.*, dr.DoctorNbr as TransmittingGpDoctorNbr, 
(
	select luv.Description
	from cpd_azdelta_prod..LUValue luv with (nolock)
	inner join cpd_azdelta_prod..lutable lut with (nolock) on lut.LUTableID = luv.LUTableID
	where lut.TableName = 'DOSSIERTYPES' and luv.LUValueID = d.DossierTypeID
) as DossierTypeDescription,
(
	select luv.Description
	from cpd_azdelta_prod..LUValue luv with (nolock)
	inner join cpd_azdelta_prod..lutable lut with (nolock) on lut.LUTableID = luv.LUTableID
	where lut.TableName = 'DOSSIERCDS' and luv.LUValueID = d.DossierCdID
) as DossierCodeDescription,
(
	select luv.Description
	from cpd_azdelta_prod..LUValue luv with (nolock)
	inner join cpd_azdelta_prod..lutable lut with (nolock) on lut.LUTableID = luv.LUTableID
	where lut.TableName = 'ACCIDENTCDS' and luv.LUValueID = d.AccidentCdID
) as AccidentDescription
from cpd_azdelta_prod..cpddossier d with (nolock)
inner join cpd_azdelta_prod..cpdpatient p with (nolock) on p.cpdpatientid = d.cpdpatientid
left outer join cpd_azdelta_prod..cpddoctor dr with (nolock) on dr.cpddoctorid = d.transmittinggpid 
where p.patientnr = @0
order by d.startdate");
                                Console.WriteLine("{0}: {1}", key, sql.Replace(Environment.NewLine, Environment.NewLine + "\t"));
                                return await db.FetchAsync<dynamic>(sql, id.PadLeft(10, '0'));
                            }
                        });
                        patientsByNameQueries.Add(key, async (lastName, firstName) =>
                        {
                            using (var db = new Database(key))
                            {
                                var sql = string.Format(@"select top 100 p.*, 
(
	select luv.Description
	from cpd_azdelta_prod..LUValue luv with (nolock)
	inner join cpd_azdelta_prod..lutable lut with (nolock) on lut.LUTableID = luv.LUTableID
	where lut.TableName = 'SEXES' and luv.LUValueID = p.SexId
) as SexDescription,
(
	select luv.Description
	from cpd_azdelta_prod..LUValue luv with (nolock)
	inner join cpd_azdelta_prod..lutable lut with (nolock) on lut.LUTableID = luv.LUTableID
	where lut.TableName = 'NATIONALITIES' and luv.LUValueID = p.NationalityID
) as NationalityDescription,
(
	select luv.Description
	from cpd_azdelta_prod..LUValue luv with (nolock)
	inner join cpd_azdelta_prod..lutable lut with (nolock) on lut.LUTableID = luv.LUTableID
	where lut.TableName = 'LANGUAGES' and luv.LUValueID = p.LanguageID
) as LanguageDescription,
dr.administrativeid as GeneralPractitionerAdministrativeId, dr.LastName as GeneralPractitionerLastName, dr.FirstName as GeneralPractitionerFirstName
from cpd_azdelta_prod..cpdpatient p with (nolock)
left outer join cpd_azdelta_prod..cpddoctor dr with (nolock) on dr.cpddoctorid = p.generalpractitionerid 
where p.LastName like @0 and p.FirstName like @1
order by p.LastName, p.FirstName");
                                Console.WriteLine("{0}: {1}", key, sql.Replace(Environment.NewLine, Environment.NewLine + "\t"));
                                return await db.FetchAsync<dynamic>(sql, lastName + "%", firstName + "%");
                            }
                        });
                        visitsByNumbersQueries.Add(key, async (numbers) =>
                        {
                            using (var db = new Database(key))
                            {
                                var sql = @"select p.PatientNr, d.*, dr.DoctorNbr as TransmittingGpDoctorNbr, 
(
	select luv.Description
	from cpd_azdelta_prod..LUValue luv with (nolock)
	inner join cpd_azdelta_prod..lutable lut with (nolock) on lut.LUTableID = luv.LUTableID
	where lut.TableName = 'DOSSIERTYPES' and luv.LUValueID = d.DossierTypeID
) as DossierTypeDescription,
(
	select luv.Description
	from cpd_azdelta_prod..LUValue luv with (nolock)
	inner join cpd_azdelta_prod..lutable lut with (nolock) on lut.LUTableID = luv.LUTableID
	where lut.TableName = 'DOSSIERCDS' and luv.LUValueID = d.DossierCdID
) as DossierCodeDescription,
(
	select luv.Description
	from cpd_azdelta_prod..LUValue luv with (nolock)
	inner join cpd_azdelta_prod..lutable lut with (nolock) on lut.LUTableID = luv.LUTableID
	where lut.TableName = 'ACCIDENTCDS' and luv.LUValueID = d.AccidentCdID
) as AccidentDescription
from cpd_azdelta_prod..cpddossier d with (nolock)
inner join cpd_azdelta_prod..cpdpatient p with (nolock) on p.cpdpatientid = d.cpdpatientid
left outer join cpd_azdelta_prod..cpddoctor dr with (nolock) on dr.cpddoctorid = d.transmittinggpid 
where d.dossiernr in (@0)
order by d.startdate";
                                Console.WriteLine("{0}: {1}", key, sql.Replace(Environment.NewLine, Environment.NewLine + "\t"));
                                return await db.FetchAsync<dynamic>(sql, (from number in numbers as IEnumerable<string> select number.PadLeft(8, '0')));
                            }
                        });
                        patientsByVisitNumbersQueries.Add(key, async (numbers) =>
                        {
                            using (var db = new Database(key))
                            {
                                var sql = string.Format(@"select top 100 p.*, 
(
	select luv.Description
	from cpd_azdelta_prod..LUValue luv with (nolock)
	inner join cpd_azdelta_prod..lutable lut with (nolock) on lut.LUTableID = luv.LUTableID
	where lut.TableName = 'SEXES' and luv.LUValueID = p.SexId
) as SexDescription,
(
	select luv.Description
	from cpd_azdelta_prod..LUValue luv with (nolock)
	inner join cpd_azdelta_prod..lutable lut with (nolock) on lut.LUTableID = luv.LUTableID
	where lut.TableName = 'NATIONALITIES' and luv.LUValueID = p.NationalityID
) as NationalityDescription,
(
	select luv.Description
	from cpd_azdelta_prod..LUValue luv with (nolock)
	inner join cpd_azdelta_prod..lutable lut with (nolock) on lut.LUTableID = luv.LUTableID
	where lut.TableName = 'LANGUAGES' and luv.LUValueID = p.LanguageID
) as LanguageDescription,
dr.administrativeid as GeneralPractitionerAdministrativeId, dr.LastName as GeneralPractitionerLastName, dr.FirstName as GeneralPractitionerFirstName
from cpd_azdelta_prod..cpdpatient p with (nolock)
inner join cpd_azdelta_prod..cpddossier d with (nolock) on d.cpdpatientid = p.cpdpatientId
left outer join cpd_azdelta_prod..cpddoctor dr with (nolock) on dr.cpddoctorid = p.generalpractitionerid 
where d.dossiernr in (@0)
order by p.LastName, p.FirstName");
                                Console.WriteLine("{0}: {1}", key, sql.Replace(Environment.NewLine, Environment.NewLine + "\t"));
                                return await db.FetchAsync<dynamic>(sql, (from number in numbers as IEnumerable<string> select number.PadLeft(8, '0')));
                            }
                        });
                        visitDetailsByVisitNumbersQuery.Add(key, async (numbers) =>
                        {
                            using (var db = new Database(key))
                            {
                                var sql = string.Format(@"select p.PatientNr, d.dossiernr, c.campusnbr, c.campusdescription, cu.nbrcareunit, cu.description as careunitdescription, r.roomnbr, b.bednbr, cup.*,
(
	select luv.Description
	from cpd_azdelta_prod..LUValue luv with (nolock)
	inner join cpd_azdelta_prod..lutable lut with (nolock) on lut.LUTableID = luv.LUTableID
	where lut.TableName = 'BEDTYPE' and luv.LUValueID = b.bedtype
) as BedTypeDescription,
dr.administrativeid as ResponsibleAdministrativeId, dr.LastName as ResponsibleDoctorLastName, dr.FirstName as ResponsibleDoctorFirstName,
cd.departmentnbr, cd.description as ConsultDepartmentDescription,
(
	select luv.ExtraInfo
	from cpd_azdelta_prod..LUValue luv with (nolock)
	inner join cpd_azdelta_prod..lutable lut with (nolock) on lut.LUTableID = luv.LUTableID
	where lut.TableName = 'LuBedIndex' and luv.LUValueID = cup.lubedindexid
) as DepartmentCode,
(
	select luv.Description
	from cpd_azdelta_prod..LUValue luv with (nolock)
	inner join cpd_azdelta_prod..lutable lut with (nolock) on lut.LUTableID = luv.LUTableID
	where lut.TableName = 'LuBedIndex' and luv.LUValueID = cup.lubedindexid
) as BedIndex,
(
	select luv.Description
	from cpd_azdelta_prod..LUValue luv with (nolock)
	inner join cpd_azdelta_prod..lutable lut with (nolock) on lut.LUTableID = luv.LUTableID
	where lut.TableName = 'RoomFare' and luv.LUValueID = cup.roomfareid
) as RoomFareDescription,
(
	select luv.Description
	from cpd_azdelta_prod..LUValue luv with (nolock)
	inner join cpd_azdelta_prod..lutable lut with (nolock) on lut.LUTableID = luv.LUTableID
	where lut.TableName = 'ReasonRoomFare' and luv.LUValueID = cup.reasonroomfareid
) as ReasonRoomFareDescription
from cpd_azdelta_prod..cpdcareunitperiod cup with (nolock)
inner join cpd_azdelta_prod..cpddossier d with (nolock) on cup.cpddossierid = d.cpddossierid
inner join cpd_azdelta_prod..cpdpatient p with (nolock) on p.cpdpatientid = d.cpdpatientid
left outer join cpd_azdelta_prod..cpdcampus c with (nolock) on c.cpdcampusid = cup.campusid
left outer join cpd_azdelta_prod..cpdcareunithosp cu with (nolock) on cu.cpdcareunithospid = cup.careunitid
left outer join cpd_azdelta_prod..cpdroom r with (nolock) on r.cpdroomid = cup.roomid
left outer join cpd_azdelta_prod..cpdbed b with (nolock) on b.cpdbedid = cup.bedid
left outer join cpd_azdelta_prod..cpddoctor dr with (nolock) on dr.cpddoctorid = cup.doctorid 
left outer join cpd_azdelta_prod..consultdepartment cd with (nolock) on cd.consultdepartmentid = cup.consultdepartmentid 
where d.dossiernr in (@0)
order by cup.startdate");
                                Console.WriteLine("{0}: {1}", key, sql.Replace(Environment.NewLine, Environment.NewLine + "\t"));
                                return await db.FetchAsync<dynamic>(sql, (from number in numbers as IEnumerable<string> select number.PadLeft(8, '0')));
                            }
                        });
                        doctorsByNumbersQuery.Add(key, async (numbers) =>
                        {
                            using (var db = new Database(key))
                            {
                                var sql = string.Format(@"select dr.*
from cpd_azdelta_prod..cpddoctor dr with (nolock)
where dr.administrativeid in (@0)");
                                Console.WriteLine("{0}: {1}", key, sql.Replace(Environment.NewLine, Environment.NewLine + "\t"));
                                return await db.FetchAsync<dynamic>(sql, (from number in numbers as IEnumerable<string> select number.PadLeft(6, '0')));
                            }
                        });
                        break;
                    case "Aexis":
                        patientByIdQueries.Add(key, async (id) =>
                        {
                            using (var db = new Database(key))
                            {
                                var sql = @"select *
from MLINE.m_patient
where code = @0";
                                Console.WriteLine("{0}: {1}", key, sql.Replace(Environment.NewLine, Environment.NewLine + "\t"));
                                return await db.FetchAsync<dynamic>(sql, id.PadLeft(10, '0'));
                            }
                        });
                        visitsByPatientIdQueries.Add(key, async (id) =>
                        {
                            using (var db = new Database(key))
                            {
                                var sql = @"select v.*
from MLINE.m_patvisit v
inner join MLINE.m_patient p on p.id = v.patid
where p.code = @0
order by v.admitdate";
                                Console.WriteLine("{0}: {1}", key, sql.Replace(Environment.NewLine, Environment.NewLine + "\t"));
                                return await db.FetchAsync<dynamic>(sql, id.PadLeft(10, '0'));
                            }
                        });
                        patientsByNameQueries.Add(key, async (lastName, firstName) =>
                        {
                            using (var db = new Database(key))
                            {
                                var sql = @"select top 100 *
from MLINE.m_patient
where lower(name) like @0 and lower(fname) like @1
order by name, fname";
                                Console.WriteLine("{0}: {1}", key, sql.Replace(Environment.NewLine, Environment.NewLine + "\t"));
                                return await db.FetchAsync<dynamic>(sql, lastName.ToLower() + "%", firstName.ToLower() + "%");
                            }
                        });
                        visitsByNumbersQueries.Add(key, async (numbers) =>
                        {
                            using (var db = new Database(key))
                            {
                                var sql = @"select *
from MLINE.m_patvisit
where visitnumber in (@0)";
                                Console.WriteLine("{0}: {1}", key, sql.Replace(Environment.NewLine, Environment.NewLine + "\t"));
                                return await db.FetchAsync<dynamic>(sql, (from number in numbers as IEnumerable<string> select number.PadLeft(8, '0')));
                            }
                        });
                        patientsByVisitNumbersQueries.Add(key, async (numbers) =>
                        {
                            using (var db = new Database(key))
                            {
                                var sql = @"select p.*
from MLINE.m_patient p
inner join MLINE.m_patvisit v on v.patid = p.id
where v.code in (@0)";
                                Console.WriteLine("{0}: {1}", key, sql.Replace(Environment.NewLine, Environment.NewLine + "\t"));
                                return await db.FetchAsync<dynamic>(sql, (from number in numbers as IEnumerable<string> select number.PadLeft(8, '0')));
                            }
                        });
                        visitDetailsByVisitNumbersQuery.Add(key, async (numbers) =>
                        {
                            return await visitsByNumbersQueries[key](numbers);
                        });
                        break;
                    case "Acertis":
                        patientByIdQueries.Add(key, async (id) =>
                        {
                            using (var db = new Database(key))
                            {
                                var sql = @"select *
from stammdaten
where kis_patid = @0";
                                Console.WriteLine("{0}: {1}", key, sql.Replace(Environment.NewLine, Environment.NewLine + "\t"));
                                return await db.FetchAsync<dynamic>(sql, id.PadLeft(10, '0'));
                            }
                        });
                        visitsByPatientIdQueries.Add(key, async (id) =>
                        {
                            using (var db = new Database(key))
                            {
                                var sql = @"select v.*
from behandlungsfaelle v
inner join stammdaten p on p.patid = v.patid
where p.kis_patid = @0
order by v.aufnahme_datum";
                                Console.WriteLine("{0}: {1}", key, sql.Replace(Environment.NewLine, Environment.NewLine + "\t"));
                                return await db.FetchAsync<dynamic>(sql, id.PadLeft(10, '0'));
                            }
                        });
                        patientsByNameQueries.Add(key, async (lastName, firstName) =>
                        {
                            using (var db = new Database(key))
                            {
                                var sql = @"select top 100 *
from stammdaten
where lower(name) like @0 and lower(vorname) like @1
order by name, vorname";
                                Console.WriteLine("{0}: {1}", key, sql.Replace(Environment.NewLine, Environment.NewLine + "\t"));
                                return await db.FetchAsync<dynamic>(sql, lastName.ToLower() + "%", firstName.ToLower() + "%");
                            }
                        });
                        visitsByNumbersQueries.Add(key, async (numbers) =>
                        {
                            using (var db = new Database(key))
                            {
                                var sql = @"select v.*
from behandlungsfaelle v
where v.aufnahme_nr in (@0)
order by v.aufnahme_datum";
                                Console.WriteLine("{0}: {1}", key, sql.Replace(Environment.NewLine, Environment.NewLine + "\t"));
                                return await db.FetchAsync<dynamic>(sql, (from number in numbers as IEnumerable<string> select number.PadLeft(8, '0')));
                            }
                        });
                        patientsByVisitNumbersQueries.Add(key, async (numbers) =>
                        {
                            using (var db = new Database(key))
                            {
                                var sql = @"select p.*
from stammdaten p
inner join behandlungsfaelle v on v.patid =  p.patid
where v.aufnahme_nr in (@0)";
                                Console.WriteLine("{0}: {1}", key, sql.Replace(Environment.NewLine, Environment.NewLine + "\t"));
                                return await db.FetchAsync<dynamic>(sql, (from number in numbers as IEnumerable<string> select number.PadLeft(8, '0')));
                            }
                        });
                        break;
                    case "Infohos COZO":
                        var patCozoSql = @"select l.*
from CPDGzo054_PROD..LOG l with (nolock)
inner join CPDGzo054_PROD..LOGArgument la with (nolock) on la.logid = l.logid and la.logkey = 'eventid'
where convert(uniqueidentifier, la.logvalue) in
(
	select ea.EventID
	from CPDGzo054_PROD..EventArgument ea with (nolock) 
	where ea.ArgumentKey = 'cpdpatientid' and ea.isdeleted = 0 and
	convert(uniqueidentifier, ea.ArgumentValue) in (@0)
)
order by l.InsertDt desc";
                        var patCpdSql = @"select p.CPDPatientID
	from cpd_azdelta_prod..cpdpatient p with (nolock)
	where p.PatientNr in (@0)";
                        var visitCozoSql = @"select l.*
from CPDGzo054_PROD..LOG l with (nolock)
inner join CPDGzo054_PROD..LOGArgument la with (nolock) on la.logid = l.logid and la.logkey = 'eventid'
where convert(uniqueidentifier, la.logvalue) in
(
	select ea.EventID
	from CPDGzo054_PROD..EventArgument ea with (nolock) 
	where ea.ArgumentKey = 'cpdcontactid' and ea.isdeleted = 0 and
	convert(uniqueidentifier, ea.ArgumentValue) in (@0)
)
order by l.InsertDt desc";
                        var visitCpdSql = @"select em.OrdContactID
from cpd_azdelta_prod..emergemergency em with (nolock)
inner join cpd_azdelta_prod..CPDDossier d with (nolock) on d.cpddossierid = em.cpddossierid 
where d.DossierNr in (@0)
union
select oc.OrdContactID
from cpd_azdelta_prod..OrdContact oc with (nolock)
inner join cpd_azdelta_prod..CPDDossier d with (nolock) on d.cpddossierid = oc.DossierId 
where d.DossierNr in (@0)
union
select doc.OrdContactID
from cpd_azdelta_prod..cpddossierjordcontact doc with (nolock)
inner join cpd_azdelta_prod..CPDDossier d with (nolock) on d.cpddossierid = doc.cpddossierid 
where d.DossierNr in (@0)";
                        patientByIdQueries.Add(key, async (id) =>
                        {
                            using (var dbCpd = new Database("Infohos CPD"))
                            {
                                Console.WriteLine("{0}: {1}", "Infohos CPD", patCpdSql.Replace(Environment.NewLine, Environment.NewLine + "\t"));
                                var guids = await dbCpd.FetchAsync<Guid>(patCpdSql, id.PadLeft(10, '0'));

                                using (var db = new Database(key))
                                {
                                    Console.WriteLine("{0}: {1}", key, patCozoSql.Replace(Environment.NewLine, Environment.NewLine + "\t"));
                                    return await db.FetchAsync<dynamic>(patCozoSql, guids);
                                }
                            }
                        });
                        visitsByPatientIdQueries.Add(key, async (id) =>
                        {
                            using (var dbCpd = new Database("Infohos CPD"))
                            {
                                Console.WriteLine("{0}: {1}", "Infohos CPD", patCpdSql.Replace(Environment.NewLine, Environment.NewLine + "\t"));
                                var guids = await dbCpd.FetchAsync<Guid>(patCpdSql, id.PadLeft(10, '0'));

                                using (var db = new Database(key))
                                {
                                    Console.WriteLine("{0}: {1}", key, patCozoSql.Replace(Environment.NewLine, Environment.NewLine + "\t"));
                                    return await db.FetchAsync<dynamic>(patCozoSql, guids);
                                }
                            }
                        });
                        //patientsByNameQueries.Add(key, async (lastName, firstName) =>
                        //{
                        //    using (var db = new Database(key))
                        //    {
                        //        var sql = string.Format(@"");
                        //        Console.WriteLine("{0}: {1}", key, sql.Replace(Environment.NewLine, Environment.NewLine + "\t"));
                        //        return await db.FetchAsync<dynamic>(sql, lastName + "%", firstName + "%");
                        //    }
                        //});
                        visitsByNumbersQueries.Add(key, async (numbers) =>
                        {
                            using (var dbCpd = new Database("Infohos CPD"))
                            {
                                Console.WriteLine("{0}: {1}", "Infohos CPD", visitCpdSql.Replace(Environment.NewLine, Environment.NewLine + "\t"));
                                var guids = await dbCpd.FetchAsync<Guid>(visitCpdSql, (from number in numbers as IEnumerable<string> select number.PadLeft(8, '0')));

                                using (var db = new Database(key))
                                {
                                    Console.WriteLine("{0}: {1}", key, visitCozoSql.Replace(Environment.NewLine, Environment.NewLine + "\t"));
                                    return await db.FetchAsync<dynamic>(visitCozoSql, guids);
                                }
                            }
                        });
                        patientsByVisitNumbersQueries.Add(key, async (numbers) =>
                        {
                            using (var dbCpd = new Database("Infohos CPD"))
                            {
                                Console.WriteLine("{0}: {1}", "Infohos CPD", visitCpdSql.Replace(Environment.NewLine, Environment.NewLine + "\t"));
                                var guids = await dbCpd.FetchAsync<Guid>(visitCpdSql, (from number in numbers as IEnumerable<string> select number.PadLeft(8, '0')));

                                using (var db = new Database(key))
                                {
                                    Console.WriteLine("{0}: {1}", key, visitCozoSql.Replace(Environment.NewLine, Environment.NewLine + "\t"));
                                    return await db.FetchAsync<dynamic>(visitCozoSql, guids);
                                }
                            }
                        });
                        visitDetailsByVisitNumbersQuery.Add(key, async (numbers) =>
                        {
                            using (var dbCpd = new Database("Infohos CPD"))
                            {
                                Console.WriteLine("{0}: {1}", "Infohos CPD", visitCpdSql.Replace(Environment.NewLine, Environment.NewLine + "\t"));
                                var guids = await dbCpd.FetchAsync<Guid>(visitCpdSql, (from number in numbers as IEnumerable<string> select number.PadLeft(8, '0')));

                                using (var db = new Database(key))
                                {
                                    Console.WriteLine("{0}: {1}", key, visitCozoSql.Replace(Environment.NewLine, Environment.NewLine + "\t"));
                                    return await db.FetchAsync<dynamic>(visitCozoSql, guids);
                                }
                            }
                        });
                        //doctorsByNumbersQuery.Add(key, async (numbers) =>
                        //{
                        //    using (var db = new Database(key))
                        //    {
                        //        var sql = string.Format(@"");
                        //        Console.WriteLine("{0}: {1}", key, sql.Replace(Environment.NewLine, Environment.NewLine + "\t"));
                        //        return await db.FetchAsync<dynamic>(sql, (from number in numbers as IEnumerable<string> select number.PadLeft(6, '0')));
                        //    }
                        //});
                        break;
                    case "CMeal":
                        break;
                    case "Allgeier":
                        break;
                    default:
                        continue;
                }

                //propertyWindows.Add(key, new PropertyWindow());
                //propertyWindows[key].Text = key + " Detail";

                //menuItem = new MenuItem();
                //menuItem.Text = key + " Detail";
                //menuItem.Click += new EventHandler(menuItemViewWindow_Click);
                //this.menuItemView.MenuItems.Add(menuItem);
                //menuItem.Index = menuItemViewIndex++;

                listWindows.Add(key, new ListWindow());
                listWindows[key].Text = key + " DB Result";
                listWindows[key].List += new HHR.HL7.Search.ListWindow.ListEventHandler(m_listWindow_List);
                listWindows[key].SearchPatientId += new HHR.HL7.Search.ListWindow.SearchPatientIdEventHandler(SearchPatientId);
                listWindows[key].SearchVisitNumber += new HHR.HL7.Search.ListWindow.SearchVisitNumberEventHandler(SearchVisitNumber);
                listWindows[key].SearchDoctorNumber += new HHR.HL7.Search.ListWindow.SearchDoctorNumberEventHandler(SearchDoctorNumber);

                menuItem = new MenuItem();
                menuItem.Text = key + " Result";
                menuItem.Click += new EventHandler(menuItemViewWindow_Click);
                this.menuItemView.MenuItems.Add(menuItem);
                menuItem.Index = menuItemViewIndex++;
            }

            menuItemViewIndex++;
            foreach (var key in hl7Versions)
            {
                switch (key)
                {
                    case "HL7v21":
                    case "HL7v23":
                        patientByIdQueries.Add(key, async (id) =>
                        {
                            using (var db = new Database(key))
                            {
                                var sql = string.Format(@"select top 10000 h.MessageTimeStamp, h.MessageType, h.EventType, a.*, h.Message, h.FileName, h.Creator
from {0}..adt a with (nolock)
inner join {0}..hl7 h with (nolock) on h.MessageControlId = a.MessageControlId
where a.PatientId = @0
order by a.MessageControlId", key);
                                Console.WriteLine("{0}: {1}", key, sql.Replace(Environment.NewLine, Environment.NewLine + "\t"));
                                return await db.FetchAsync<dynamic>(sql, id);
                            }
                        });
                        visitsByPatientIdQueries.Add(key, async (id) =>
                        {
                            return await patientByIdQueries[key](id);
                        });
                        patientsByNameQueries.Add(key, async (lastName, firstName) =>
                        {
                            using (var db = new Database(key))
                            {
                                var sql = string.Format(@"select top 10000 h.MessageTimeStamp, h.MessageType, h.EventType, a.*, h.Message, h.FileName, h.Creator
from {0}..adt a with (nolock)
inner join {0}..hl7 h with (nolock) on h.MessageControlId = a.MessageControlId
where a.FamilyName like @0 and a.FirstName like @1
order by a.MessageControlId", key);
                                Console.WriteLine("{0}: {1}", key, sql.Replace(Environment.NewLine, Environment.NewLine + "\t"));
                                return await db.FetchAsync<dynamic>(sql, lastName + "%", firstName + "%");
                            }
                        });
                        visitsByNumbersQueries.Add(key, async (numbers) =>
                        {
                            using (var db = new Database(key))
                            {
                                var sql = string.Format(@"select top 10000 h.MessageTimeStamp, h.MessageType, h.EventType, a.*, h.Message, h.FileName, h.Creator
from {0}..adt a with (nolock)
inner join {0}..hl7 h with (nolock) on h.MessageControlId = a.MessageControlId
where a.VisitNumber in (@0)
order by a.MessageControlId", key);
                                Console.WriteLine("{0}: {1}", key, sql.Replace(Environment.NewLine, Environment.NewLine + "\t"));
                                return await db.FetchAsync<dynamic>(sql, (from number in numbers as IEnumerable<string> select number.ToDecimal()));
                            }
                        });
                        patientsByVisitNumbersQueries.Add(key, async (numbers) =>
                        {
                            return await visitsByNumbersQueries[key](numbers);
                        });
                        visitDetailsByVisitNumbersQuery.Add(key, async (numbers) =>
                        {
                            return await visitsByNumbersQueries[key](numbers);
                        });
                        doctorsByNumbersQuery.Add(key, async (numbers) =>
                        {
                            using (var db = new Database(key))
                            {
                                var sql = string.Format(@"select top 10000 h.MessageTimeStamp, h.MessageType, h.EventType, m.*, h.Message, h.FileName, h.Creator
from {0}..mfn m with (nolock)
inner join {0}..hl7 h with (nolock) on h.MessageControlId = m.MessageControlId
where m.DoctorNumber in (@0)
order by m.MessageControlId", key);
                                Console.WriteLine("{0}: {1}", key, sql.Replace(Environment.NewLine, Environment.NewLine + "\t"));
                                return await db.FetchAsync<dynamic>(sql, (from number in numbers as IEnumerable<string> select number.ToDecimal()));
                            }
                        });
                        //searchAdtQuery.Add(key, async (eventArgs) =>
                        //{

                        //});
                        break;
                    //                    case "Biztalk":
                    //                    case "Biztalk Test":
                    //                        patientByIdQueries.Add(key, async (id) =>
                    //                        {
                    //                            using (var db = new Database(key))
                    //                            {
                    //                                var sql = string.Format(@"select top 1000 mi.CreationDate, mi.SendTransportType, mi.ReceivePortName, mi.ReceiveMessageName,
                    //	(select top 1 value from {0}.BizTalk.Metadata  where [key] = 'SubType' and MessageId = mi.SendMessageid) as SubType,
                    //	(select top 1 value from {0}.BizTalk.Metadata  where [key] = 'PatientNumber' and MessageId = mi.SendMessageid) as PatientNumber,
                    //	(select top 1 value from {0}.BizTalk.Metadata  where [key] = 'VisitNumber' and MessageId = mi.SendMessageid) as VisitNumber,
                    //	(select top 1 value from {0}.BizTalk.Metadata  where [key] = 'StaffNumber' and MessageId = mi.SendMessageid) as StaffNumber, 
                    //	sendMessage.Content as Message
                    //FROM {0}.BizTalk.MessageInstance mi with (nolock)
                    //inner join {0}.BizTalk.Message sendMessage on sendMessage.MessageId = mi.SendMessageid
                    //left outer join {0}.BizTalk.Metadata sendMeta on sendMeta.MessageId = mi.SendMessageid
                    //where mi.sendPortname = @0", key == "Biztalk" ? "Messagebox054" : "Messagebox_Beta");
                    //                                var args = new List<object>() { biztalk };
                    //                                if (!showOnlyLast100BiztalkHL7s)
                    //                                {
                    //                                    sql = string.Concat(sql, Environment.NewLine, @"and sendMeta.[key] = @1
                    //and sendMeta.value = @2");
                    //                                    args.Add("PatientNumber");
                    //                                    args.Add(id);
                    //                                }
                    //                                sql = string.Concat(sql, Environment.NewLine, @"order by mi.CreationDate desc");
                    //                                Console.WriteLine("{0}: {1}", key, sql.Replace(Environment.NewLine, Environment.NewLine + "\t"));
                    //                                return await db.FetchAsync<dynamic>(sql, args.ToArray());
                    //                            } 
                    //                        });
                    //                        visitsByPatientIdQueries.Add(key, async (id) =>
                    //                        {
                    //                            return await patientByIdQueries[key](id);
                    //                        });
                    //                        visitsByNumbersQueries.Add(key, async (numbers) =>
                    //                        {
                    //                            using (var db = new Database(key))
                    //                            {
                    //                                var sql = string.Format(@"select top 1000 mi.CreationDate, mi.SendTransportType, mi.ReceivePortName, mi.ReceiveMessageName,
                    //	(select top 1 value from {0}.BizTalk.Metadata  where [key] = 'SubType' and MessageId = mi.SendMessageid) as SubType,
                    //	(select top 1 value from {0}.BizTalk.Metadata  where [key] = 'PatientNumber' and MessageId = mi.SendMessageid) as PatientNumber,
                    //	(select top 1 value from {0}.BizTalk.Metadata  where [key] = 'VisitNumber' and MessageId = mi.SendMessageid) as VisitNumber,
                    //	(select top 1 value from {0}.BizTalk.Metadata  where [key] = 'StaffNumber' and MessageId = mi.SendMessageid) as StaffNumber, 
                    //	sendMessage.Content as Message
                    //FROM {0}.BizTalk.MessageInstance mi with (nolock)
                    //inner join {0}.BizTalk.Message sendMessage on sendMessage.MessageId = mi.SendMessageid
                    //left outer join {0}.BizTalk.Metadata sendMeta on sendMeta.MessageId = mi.SendMessageid
                    //where mi.sendPortname = @0", key == "Biztalk" ? "Messagebox054" : "Messagebox_Beta");
                    //                                var args = new List<object>() { biztalk };
                    //                                if (!showOnlyLast100BiztalkHL7s)
                    //                                {
                    //                                    sql = string.Concat(sql, Environment.NewLine, @"and sendMeta.[key] = @1
                    //and sendMeta.value in (@2)");
                    //                                    args.Add("VisitNumber");
                    //                                    args.Add(numbers);
                    //                                }
                    //                                sql = string.Concat(sql, Environment.NewLine, @"order by mi.CreationDate desc");
                    //                                Console.WriteLine("{0}: {1}", key, sql.Replace(Environment.NewLine, Environment.NewLine + "\t"));
                    //                                return await db.FetchAsync<dynamic>(sql, args.ToArray());
                    //                            }
                    //                        });
                    //                        patientsByVisitNumbersQueries.Add(key, async (numbers) =>
                    //                        {
                    //                            return await visitsByNumbersQueries[key](numbers);
                    //                        });
                    //                        visitDetailsByVisitNumbersQuery.Add(key, async (numbers) =>
                    //                        {
                    //                            return await visitsByNumbersQueries[key](numbers);
                    //                        });
                    //                        doctorsByNumbersQuery.Add(key, async (numbers) =>
                    //                        {
                    //                            using (var db = new Database(key))
                    //                            {
                    //                                var sql = string.Format(@"select top 1000 mi.CreationDate, mi.SendTransportType, mi.ReceivePortName, mi.ReceiveMessageName,
                    //	(select top 1 value from {0}.BizTalk.Metadata  where [key] = 'SubType' and MessageId = mi.SendMessageid) as SubType,
                    //	(select top 1 value from {0}.BizTalk.Metadata  where [key] = 'PatientNumber' and MessageId = mi.SendMessageid) as PatientNumber,
                    //	(select top 1 value from {0}.BizTalk.Metadata  where [key] = 'VisitNumber' and MessageId = mi.SendMessageid) as VisitNumber,
                    //	(select top 1 value from {0}.BizTalk.Metadata  where [key] = 'StaffNumber' and MessageId = mi.SendMessageid) as StaffNumber, 
                    //	sendMessage.Content as Message
                    //FROM {0}.BizTalk.MessageInstance mi with (nolock)
                    //inner join {0}.BizTalk.Message sendMessage on sendMessage.MessageId = mi.SendMessageid
                    //left outer join {0}.BizTalk.Metadata sendMeta on sendMeta.MessageId = mi.SendMessageid
                    //where mi.sendPortname = @0", key == "Biztalk" ? "Messagebox054" : "Messagebox_Beta");
                    //                                var args = new List<object>() { biztalk };
                    //                                if (!showOnlyLast100BiztalkHL7s)
                    //                                {
                    //                                    sql = string.Concat(sql, Environment.NewLine, @"and sendMeta.[key] = @1
                    //and sendMeta.value in (@2)");
                    //                                    args.Add("StaffNumber");
                    //                                    args.Add(numbers);
                    //                                }
                    //                                sql = string.Concat(sql, Environment.NewLine, @"order by mi.CreationDate desc");
                    //                                Console.WriteLine("{0}: {1}", key, sql.Replace(Environment.NewLine, Environment.NewLine + "\t"));
                    //                                return await db.FetchAsync<dynamic>(sql, args.ToArray());
                    //                            }
                    //                        });
                    //                        break;
                }

                treeWindows.Add(key, new HL7TreeWindow());
                treeWindows[key].Text = key + " Tree";

                menuItem = new MenuItem();
                menuItem.Text = key + " Tree";
                menuItem.Click += new EventHandler(menuItemViewWindow_Click);
                this.menuItemView.MenuItems.Add(menuItem);
                menuItem.Index = menuItemViewIndex++;

                syntaxHighlightingWindows.Add(key, new SyntaxHighlightingWindow(key));
                syntaxHighlightingWindows[key].Text = key + " Message";
                syntaxHighlightingWindows[key].SearchPatientId += new HHR.HL7.Search.SyntaxHighlightingWindow.SearchPatientIdEventHandler(SearchPatientId);
                syntaxHighlightingWindows[key].SearchVisitNumber += new HHR.HL7.Search.SyntaxHighlightingWindow.SearchVisitNumberEventHandler(SearchVisitNumber);

                menuItem = new MenuItem();
                menuItem.Text = key + " Message";
                menuItem.Click += new EventHandler(menuItemViewWindow_Click);
                this.menuItemView.MenuItems.Add(menuItem);
                menuItem.Index = menuItemViewIndex++;

                listWindows.Add(key, new ListWindow());
                listWindows[key].Text = key + " HL7 Result";
                listWindows[key].List += new HHR.HL7.Search.ListWindow.ListEventHandler(m_listWindow_List);
                listWindows[key].SearchPatientId += new HHR.HL7.Search.ListWindow.SearchPatientIdEventHandler(SearchPatientId);
                listWindows[key].SearchVisitNumber += new HHR.HL7.Search.ListWindow.SearchVisitNumberEventHandler(SearchVisitNumber);

                menuItem = new MenuItem();
                menuItem.Text = key + " Result";
                menuItem.Click += new EventHandler(menuItemViewWindow_Click);
                this.menuItemView.MenuItems.Add(menuItem);
                menuItem.Index = menuItemViewIndex++;
            }

            m_searchWindow = new SearchWindow(patientByIdQueries.Keys.ToList());
            m_searchHL7ADTWindow = new SearchHL7ADTWindow(hl7Versions);
            m_searchHL7MFNWindow = new SearchHL7MFNWindow(hl7Versions);

            m_outputWindow = new OutputWindow();
            m_exportHL7Form = new ExportHL7Form(hl7Versions);

            dockPanel.AllowEndUserDocking = false;
            m_deserializeDockContent = new DeserializeDockContent(GetContentFromPersistString);

            //dockable panels settings
            m_searchWindow.SearchByPatientName += new HHR.HL7.Search.SearchWindow.SearchByPatientNameEventHandler(m_searchWindow_SearchByPatientName);
            m_searchWindow.SearchByPatientId += new HHR.HL7.Search.SearchWindow.SearchByPatientIdEventHandler(m_searchWindow_SearchByPatientId);
            m_searchWindow.SearchByVisitNumbers += new HHR.HL7.Search.SearchWindow.SearchByVisitNumbersEventHandler(m_searchWindow_SearchByVisitNumbers);
            m_searchWindow.SearchByDoctorNumbers += new HHR.HL7.Search.SearchWindow.SearchByDoctorNumbersEventHandler(m_searchWindow_SearchByDoctorNumbers);
            m_searchWindow.SearchByWardIds += m_searchWindow_SearchByWardIds;
            m_searchWindow.DalChecked += m_searchWindow_DalChecked;
            m_searchHL7ADTWindow.Search += new HHR.HL7.Search.SearchHL7ADTWindow.SearchEventHandler(m_searchHL7ADTWindow_Search);
            m_searchHL7MFNWindow.Search += new HHR.HL7.Search.SearchHL7MFNWindow.SearchEventHandler(m_searchHL7MFNWindow_Search);
        }