public SqlArchiveMethod(ArchiveControl ctl) : base(ctl) { string[] split = ctl.ArchiveInfo.Split(new Char[] { ';' }); dbServer = split[0]; dbDatabase = split[1]; dbTable = split[2]; mArchiveControl = ctl; insertSql = "Insert into " + dbTable + " (RecID,ControlID,data) Values(@ID,@controlID,@data)"; deleteSql = "Delete " + dbTable + " where RecID = @ID AND controlID = @controlID"; selectSql = "Select data from " + dbTable + " where RecID = @ID AND controlID = @controlID"; squtil = new SqlUtil(dbServer, dbDatabase, "sql database archiver"); }
/// <summary> /// 出院病人查询方法 /// </summary> /// <param name="valueStr"></param> private void GoSerachOutHosPatInfo(string valueStr) { try { string sql = MedicalRecordManage.Object.DaoCommand._SELECT_MEDICAL_RECORD_INPATIENT_LONG; if (valueStr.ToLower().Contains("iem_mainpage_diagnosis_sx")) { sql = DaoCommand._SELECT_MEDICAL_RECORD_INPATIENT_LONG_ZY; } List <DbParameter> sqlParams = new List <DbParameter>(); if (this.txtName.Text.Trim() != null && this.txtName.Text.Trim() != "") { sql = sql + " and i.name like '%'||@name||'%' "; SqlParameter param1 = new SqlParameter("@name", SqlDbType.VarChar); param1.Value = this.txtName.Text.Trim(); sqlParams.Add(param1); } if (this.txtNumber.Text.Trim() != null && this.txtNumber.Text.Trim() != "") { sql = sql + " and i.patid like '%'||@patId||'%'"; SqlParameter param2 = new SqlParameter("@patId", SqlDbType.VarChar); param2.Value = this.txtNumber.Text.Trim(); sqlParams.Add(param2); } if (this.lookUpEditorDepartment.Text != null && this.lookUpEditorDepartment.Text.Trim() != "") { if (lookUpEditorDepartment.CodeValue != "0000") { sql = sql + " and i.outhosdept = @code "; SqlParameter param5 = new SqlParameter("@code", SqlDbType.VarChar); param5.Value = lookUpEditorDepartment.CodeValue; sqlParams.Add(param5); } } //add by ck 2013-8-26 if (this.lookUpEditorDoctor.Text != null && this.lookUpEditorDoctor.Text.Trim() != "") { sql = sql + " and i.resident = @code"; SqlParameter param4 = new SqlParameter("@code", SqlDbType.VarChar); param4.Value = lookUpEditorDoctor.CodeValue; sqlParams.Add(param4); }//主治医生 if (this.dateAdmitStart.Text.Trim() != null && this.dateAdmitStart.Text.Trim() != "") { string ds = this.dateAdmitStart.DateTime.ToString("yyyy-MM-dd 00:00:00");//开始时间默认当天的0点 sql = sql + " and i.admitdate >= @ds "; SqlParameter param6 = new SqlParameter("@ds", SqlDbType.VarChar); param6.Value = ds; sqlParams.Add(param6); } if (this.dateAdmitEnd.Text.Trim() != null && this.dateAdmitEnd.Text.Trim() != "") { string de = this.dateAdmitEnd.DateTime.ToString("yyyy-MM-dd 23:59:59");//结束时间默认当天23:59:59 sql = sql + " and i.admitdate <= @de "; SqlParameter param7 = new SqlParameter("@de", SqlDbType.VarChar); param7.Value = de; sqlParams.Add(param7); } if (this.dateLeaveStart.Text.Trim() != null && this.dateLeaveStart.Text.Trim() != "") { string ds = this.dateLeaveStart.DateTime.ToString("yyyy-MM-dd 00:00:00"); sql = sql + " and i.outhosdate >= @dss"; SqlParameter param8 = new SqlParameter("@dss", SqlDbType.VarChar); param8.Value = ds; sqlParams.Add(param8); } if (this.dateLeaveEnd.Text.Trim() != null && this.dateLeaveEnd.Text.Trim() != "") { string de = this.dateLeaveEnd.DateTime.ToString("yyyy-MM-dd 23:59:59"); sql = sql + " and i.outhosdate <= @dee"; SqlParameter param9 = new SqlParameter("@dee", SqlDbType.VarChar); param9.Value = de; sqlParams.Add(param9); } if (this.cbxLockStatus.Text.Trim() != null && this.cbxLockStatus.Text.Trim() != "") { int lockstatus = ComponentCommand.GetLockStatusValue(this.cbxLockStatus.Text); if (lockstatus == 4700) { sql = sql + " and (i.islock = @lockstatus OR i.islock is null)"; } else { sql = sql + " and i.islock = @lockstatus"; } SqlParameter param10 = new SqlParameter("@lockstatus", SqlDbType.VarChar); param10.Value = lockstatus; sqlParams.Add(param10); } DataTable dataTable = DrectSoft.DSSqlHelper.DS_SqlHelper.ExecuteDataTable(sql, sqlParams, CommandType.Text); //压缩数据源生成新的数据源 //压缩DateSet中的记录,将住院诊断信息合并 ComponentCommand.ImpressDataSet(ref dataTable, "noofinpat", "cyzd", "operation_name"); //add by zjy 2013-6-17 string wheresql = "1=1 "; if (this.lookUpEditorDiagnosis.Text.Trim() != null && this.lookUpEditorDiagnosis.Text.Trim() != "") { wheresql = wheresql + " and cyzd like '%" + this.lookUpEditorDiagnosis.Text.Trim() + "%'"; } if (this.lookUpEditorOperation.Text.Trim() != null && this.lookUpEditorOperation.Text.Trim() != "") { wheresql = wheresql + " and operation_name like '%" + this.lookUpEditorOperation.Text.Trim().Trim() + "%'"; } DataRow[] dr = dataTable.Select(wheresql); if (dr != null && dr.Length > 0) { DataTable tableRecord = ToDataTable(dr); string ResultName = string.Empty;//声明最终要在列表显示的姓名的内容 for (int i = 0; i < tableRecord.Rows.Count; i++) { ResultName = SqlUtil.GetPatsBabyContent(SqlUtil.App, tableRecord.Rows[i]["noofinpat"].ToString()); tableRecord.Rows[i]["Name"] = ResultName; if (tableRecord.Rows[i]["isbaby"].ToString() == "1") { tableRecord.Rows[i]["PATID"] = SqlUtil.GetPatsBabyMother(dataTable.Rows[i]["mother"].ToString()); } } //绑定控件 this.dbGrid.DataSource = tableRecord; lblTip.Text = "共" + tableRecord.Rows.Count.ToString() + "条"; } else { this.dbGrid.DataSource = null; lblTip.Text = "共0条"; } } catch (Exception ex) { MyMessageBox.Show(1, ex); } }
/// <summary> /// Final configuration method, configures the /// message bus according to all previously specified /// config options. /// </summary> /// <returns></returns> public MessageBusConfigurator FinishConfiguration() { if (!IsServiceRegistered <IMessageDispatcher>()) { var c = _wc.Kernel.ConfigurationStore.GetComponentConfiguration("ExternalServiceResolver"); var reg = Component.For <IMessageDispatcher, MessageDispatcher>() .ImplementedBy <MessageDispatcher>() .LifeStyle.Singleton; if (c != null) { reg = reg.Parameters(Parameter.ForKey("resolver").Eq("${ExternalServiceResolver}")); } _wc.Register(reg); } if (!IsServiceRegistered <IServiceMessageDispatcher>()) { _wc.Register(Component.For <IServiceMessageDispatcher>() .ImplementedBy <ServiceMessageDispatcher>().LifeStyle.Singleton); } _wc.Register(Component.For <JsonServiceCallHandler>().ImplementedBy <JsonServiceCallHandler>()); if (!IsServiceRegistered <IMessageConsumer <Ping> >()) { RegisterHandlerType(typeof(PingService), _wc); } if (!IsServiceRegistered <IMessageConsumer <SubscribeRequest> >()) { _wc.Register(Component.For <IMessageConsumer <SubscribeRequest>, IMessageConsumer <UnsubscribeRequest>, IMessageConsumer <SubscriptionExpiring>, IMessageConsumer <SubscriptionTimeout> >() .ImplementedBy <SubscriptionMsgHandler>() .DependsOn(new { DefaultSubscriptionLifetime = SubscriptionLifetime })); } if (!IsServiceRegistered <ISerializeMessages>()) { _wc.Register(Component.For <ISerializeMessages>().ImplementedBy <JsonMessageSerializer>().LifeStyle.Singleton); } if (!IsServiceRegistered <ISubscriptionService>()) { UseSqlSubscriptions(); } var dcs = GetDefaultConnectionString(); if (EnableSagas) { if (!IsServiceRegistered <SagaStateHelper>()) { _wc.Register(Component.For <SagaStateHelper>().ImplementedBy <SagaStateHelper>().LifeStyle.Singleton); } if (!IsServiceRegistered <ISagaRepository>()) { string calias, tmp; ConnectionStringSettings cs = null; if (SqlUtil.ParseSqlEndpoint(Endpoint, out calias, out tmp)) { cs = _connStrings.FirstOrDefault(x => x.Name == calias); if (cs == null) { cs = SqlHelper.GetConnectionString(calias); } } else { throw new Exception("Endpoint"); } _wc.Register(Component.For <ISagaRepository>().ImplementedBy <SqlSagaStateRepository>().LifeStyle.Singleton .DependsOn(new { ConnectionString = cs == null ? calias : cs.ConnectionString, ProviderName = cs == null ? DefaultDbProviderName : cs.ProviderName, TableName = "NG_Sagas", AutoCreateDatabase = AutoCreateQueues })); } } if (!IsServiceRegistered <IMessageBus>()) { ConfigureSqlMessageBus(); } var dmb = _wc.Resolve <IMessageBus>(); foreach (var ac in _additionalBuses) { log.Info("Configuring additional message bus {0} | {1}", ac.Endpoint, ac.BusName); ConfigureAdditionalSqlMessageBus(ac); } foreach (IPlugin pl in _wc.ResolveAll <IPlugin>()) { pl.OnFinishConfiguration(_wc); } if (dcs != null) { using (var con = SqlHelper.OpenConnection(dcs)) { IMessageDispatcher md = _wc.Resolve <IMessageDispatcher>(); md.DispatchMessage(new Impl.InternalEvents.DatabaseInit { Connection = con }, dmb); } } if (AutoStart) { foreach (IMessageBus mb in _wc.ResolveAll <IMessageBus>()) { log.Info("Message bus configured: {0}", mb.Endpoint); } StartMessageBus(); } if (IsServiceRegistered <HttpMessageGateway>()) { _wc.Resolve <HttpMessageGateway>(); } return(this); }
public void PrintSqlByConsole(DbAccessorContext context) { Console.WriteLine("--<<<------------------------------------------------------------------------------------------------------"); Console.WriteLine(SqlUtil.GetSqlFromDbCommand(context.DbCommand)); Console.WriteLine("------------------------------------------------------------------------------------------------------>>>--"); }
public void Insert(KeyValueListBase list) { ExecuteComand(SqlUtil.BuildInsert(list)); }
//Überträgt die Namen von Properties vom Repository in die mobile Datenbank. Um doppelte Einträge zu vermeiden werden zunächst Einträge in der Mobilen Datenbank //gelöscht. Kann mit Reflexion verallgemeinert und mit updateTaxonNames kombiniert werden. public void updateProperties(string sourceTable, string targetTable) { if (MappingDictionary.Mapping.ContainsKey(typeof(PropertyNames))) { MappingDictionary.Mapping[typeof(PropertyNames)] = sourceTable; } else { MappingDictionary.Mapping.Add(typeof(PropertyNames), sourceTable); } //Neue Properties holen IList <PropertyNames> properties = new List <PropertyNames>(); String praefix = ConnectionsAccess.RepositoryDefinitions.Praefix; //IRestriction r = RestrictionFactory.TypeRestriction(typeof(PropertyNames)); //properties = taxonrepSerializer.Connector.LoadList<PropertyNames>(r);//geht nicht , weil auf der Sicht keine GUID definiert ist DbConnection connRepository = ConnectionsAccess.RepositoryDefinitions.CreateConnection(); DbCommand select = connRepository.CreateCommand(); DbCommand count = connRepository.CreateCommand(); select.CommandText = String.Format("SELECT * FROM {0}", praefix + sourceTable); count.CommandText = String.Format("SELECT COUNT(*) FROM {0}", praefix + sourceTable); DbDataReader reader = null; IAdvanceProgress localProgress = progress.startExternal(progressPerProperty / 2); int propertyCount = 0; try { connRepository.Open(); propertyCount = (int)count.ExecuteScalar(); localProgress.InternalTotal = propertyCount; reader = select.ExecuteReader(); while (reader.Read()) { PropertyNames prop = new PropertyNames(); prop.PropertyID = reader.GetInt32(0); if (!reader.IsDBNull(1)) { prop.PropertyURI = reader.GetString(1); } if (!reader.IsDBNull(2)) { prop.DisplayText = reader.GetString(2); } if (!reader.IsDBNull(3)) { prop.HierarchyCache = reader.GetString(3); } //primary key prop.TermID = reader.GetInt32(4); if (!reader.IsDBNull(5)) { prop.BroaderTermID = reader.GetInt32(5); } properties.Add(prop); localProgress.advance(); } } catch (Exception e) { _Log.ErrorFormat("Exception reading Properties: [{0}]", e); return; } finally { connRepository.Close(); } DbConnection connMobile = ConnectionsAccess.MobileTaxa.CreateConnection(); connMobile.Open(); SqlCeTransaction trans = null; try { trans = (SqlCeTransaction)connMobile.BeginTransaction(); localProgress = progress.startInternal(progressPerProperty / 2, propertyCount); //Alte Taxa löschen DbCommand commandMobile = connMobile.CreateCommand(); commandMobile.CommandText = String.Format("DELETE FROM {0}", targetTable); commandMobile.ExecuteNonQuery(); //Taxa eintragen foreach (PropertyNames prop in properties) { var sb = new StringBuilder(); //Alternativ mobileDBSerializer.Connector.Save(taxon) sb.Append("Insert INTO ").Append(targetTable).Append(" (PropertyID,PropertyURI,DisplayText,HierarchyCache,TermID,BroaderTermID) VALUES ("); sb.Append(SqlUtil.SqlConvert(prop.PropertyID)).Append(","); sb.Append(SqlUtil.SqlConvert(prop.PropertyURI)).Append(",").Append(SqlUtil.SqlConvert(prop.DisplayText)).Append(",").Append(SqlUtil.SqlConvert(prop.HierarchyCache)).Append(",").Append(prop.TermID).Append(",").Append(prop.BroaderTermID).Append(")"); DbCommand insert = connMobile.CreateCommand(); insert.CommandText = @sb.ToString(); insert.ExecuteNonQuery(); localProgress.advance(); } trans.Commit(); } catch (Exception) { if (trans != null) { trans.Rollback(); } return; } finally { connMobile.Close(); } }
private void LoadData() { try { //add by zjy 2013-6-14 string valueStr = DrectSoft.Service.DS_SqlService.GetConfigValueByKey("AutoScoreMainpage"); string sql = MedicalRecordManage.Object.DaoCommand._SELECT_MEDICAL_RECORD_WriteUp_SQL + " and i.status = 1"; if (valueStr.ToLower().Contains("iem_mainpage_diagnosis_sx")) { sql = MedicalRecordManage.Object.DaoCommand._SELECT_MEDICAL_RECORD_WriteUp_SQL_ZY + " and i.status = 1"; } List <DbParameter> sqlParams = new List <DbParameter>(); if (this.txtDoctor.Text.Trim() != null && this.txtDoctor.Text.Trim() != "") { sql = sql + " and i.applyname like @doc "; SqlParameter param1 = new SqlParameter("@doc", SqlDbType.VarChar); param1.Value = "%" + this.txtDoctor.Text.Trim() + "%"; sqlParams.Add(param1); } if (this.txtName.Text.Trim() != null && this.txtName.Text.Trim() != "") { sql = sql + " and i.name like @name "; SqlParameter param2 = new SqlParameter("@name", SqlDbType.VarChar); param2.Value = "%" + this.txtName.Text.Trim() + "%"; sqlParams.Add(param2); } if (this.txtNumber.Text.Trim() != null && this.txtNumber.Text.Trim() != "") { sql = sql + " and i.patid like '%'||@patid||'%' "; SqlParameter param3 = new SqlParameter("@patid", SqlDbType.VarChar); param3.Value = this.txtNumber.Text.Trim(); sqlParams.Add(param3); } if (this.lookUpEditorDepartment.Text != null && this.lookUpEditorDepartment.Text.Trim() != "") { if (lookUpEditorDepartment.CodeValue != "0000") { sql = sql + " and i.outhosdept = @dept"; SqlParameter param4 = new SqlParameter("@dept", SqlDbType.VarChar); param4.Value = lookUpEditorDepartment.CodeValue; sqlParams.Add(param4); } } if (this.dateStart.Text.Trim() != null && this.dateStart.Text.Trim() != "") { string ds = this.dateStart.DateTime.ToString("yyyy-MM-dd 00:00:00"); sql = sql + " and to_char(i.applydate,'yyyy-mm-dd hh24:mi:ss') >= @ds"; SqlParameter param5 = new SqlParameter("@ds", SqlDbType.VarChar); param5.Value = ds; sqlParams.Add(param5); } if (this.dateEnd.Text.Trim() != null && this.dateEnd.Text.Trim() != "") { string de = this.dateEnd.DateTime.ToString("yyyy-MM-dd 23:59:59"); sql = sql + " and to_char(i.applydate,'yyyy-mm-dd hh24:mi:ss') <= @de"; SqlParameter param6 = new SqlParameter("@de", SqlDbType.VarChar); param6.Value = de; sqlParams.Add(param6); } DataTable dataTable = DrectSoft.DSSqlHelper.DS_SqlHelper.ExecuteDataTable(sql, sqlParams, CommandType.Text); //压缩数据源生成新的数据源 //压缩DateSet中的记录,将住院诊断信息合并 ComponentCommand.ImpressDataSet(ref dataTable, "id", "cyzd"); string ResultName = string.Empty;//声明最终要在列表显示的姓名的内容 for (int i = 0; i < dataTable.Rows.Count; i++) { ResultName = SqlUtil.GetPatsBabyContent(SqlUtil.App, dataTable.Rows[i]["noofinpat"].ToString()); dataTable.Rows[i]["Name"] = ResultName; if (dataTable.Rows[i]["isbaby"].ToString() == "1") { dataTable.Rows[i]["PATID"] = SqlUtil.GetPatsBabyMother(dataTable.Rows[i]["mother"].ToString()); } } this.dbGrid.DataSource = dataTable; } catch (Exception ex) { DrectSoft.Common.Ctrs.DLG.MyMessageBox.Show(1, ex); } }
public void Delete(KeyValueListBase list) { ExecuteComand(SqlUtil.BuildDelete(list.TableName, SqlUtil.BuildWhere(list.Pairs))); }
// 示例:Member.Id=6 and Cat.Id>7 // art.Find("Author=:author and Title=:title and Id>:id order by Id desc") public String processCondition(String conditionString, Dictionary <String, Object> paramMap, ref String joinTable) { //logger.Info( "conditionString=>" + conditionString ); // 根据不同方言,替换参数,比如“Author=:author and Title=:title”需要替换成“Author=? and Title=?” foreach (String key in paramMap.Keys) { conditionString = conditionString.Replace(":" + key, _entityInfo.Dialect.GetParameter(key)); } //如果是实体属性在设置条件,还要负责把 Member.Id=:mid 转换成 TMemberId=?:不联表查询 // 1、当前实体具有的column : _entityInfo.ColumnList // 2、找到参数查询所对应的column if (isConditionHasEntity(conditionString)) { //是否联表查询 Boolean isJoinedQuery = false; String _join_condition = ""; int _joined_Property_Count = 0; // and (Member.Id=? and Cat.Name=?) order by Id desc List <String[]> items = SqlUtil.getEntityProperties(conditionString); foreach (String[] pair in items) { String strItem = pair[0] + "." + pair[1]; if (!pair[1].ToLower().Equals("id")) { isJoinedQuery = true; } if (!isJoinedQuery) { conditionString = conditionString.Replace(strItem, _entityInfo.GetColumnName(pair[0])); } else { _joined_Property_Count += 1; EntityPropertyInfo _e_p = _entityInfo.GetProperty(pair[0]); EntityPropertyInfo _sub_p = _e_p.EntityInfo.GetProperty(pair[1]); String subColumn = (_sub_p == null ? pair[1] : _sub_p.ColumnName); String _sub_column_name = "t" + _joined_Property_Count + "." + subColumn; // joinTable joinTable += _e_p.EntityInfo.TableName + " t" + _joined_Property_Count + ","; // replace entity property conditionString = conditionString.Replace(strItem, _sub_column_name); _join_condition += "and t0." + _e_p.ColumnName + "=t" + _joined_Property_Count + ".Id "; } } // add prefix "0" to all current entity property's column, especially in "order by id desc" etc.(=>order by t0.id desc) if (isJoinedQuery) { conditionString = addJoinTablePrefix(conditionString, ' '); } //conditionString = _join_condition + conditionString; conditionString = conditionString.Trim(); _join_condition = _join_condition.Trim(); if (conditionString.StartsWith("and ") == false && _join_condition.EndsWith(" and") == false) { conditionString = _join_condition + " and " + conditionString; } else { conditionString = _join_condition + " " + conditionString; } } return(conditionString); }
public string updatePeopleDetail(string userId, string name, string age, string sex, string phone) { Dictionary <string, object> allMap = new Dictionary <string, object>(); if (userId.Length == 0) { allMap.Add("result", "1"); allMap.Add("message", "用户id不能为空!"); return(JsonHelper.ToJson(allMap)); } DataSet ds0 = dbMysql.seleDB("select * from t_people where id = '" + userId + "'"); if (ds0.Tables[0].Rows.Count == 0) { allMap.Add("result", "1"); allMap.Add("message", "该用户不存在!"); return(JsonHelper.ToJson(allMap)); } Dictionary <string, object> inertMap = new Dictionary <string, object>(); if (name.Length > 0) { inertMap.Add("name", name); } if (age.Length > 0) { inertMap.Add("age", age); } if (sex.Length > 0) { inertMap.Add("sex", sex); } if (phone.Length > 0) { inertMap.Add("phone", phone); } string updateSql = SqlUtil.getUpdateSql("t_people", inertMap); // return updateSql; try { // 更新用户信息 dbMysql.ExecuteSql(updateSql + " where id = " + userId); // 查出新用户 DataSet ds = dbMysql.seleDB("SELECT * FROM t_people where id = " + userId); Dictionary <string, object> voMap = JsonHelper.DataRowToDictionary(ds.Tables[0].Rows[0]); allMap.Add("result", "0"); allMap.Add("people", voMap); return(JsonHelper.ToJson(allMap)); } catch (Exception ex) { allMap.Add("result", "1"); allMap.Add("message", "更新异常"); return(JsonHelper.ToJson(allMap)); } }
public string register(string loginName, string passWord, string name, string age, string sex, string phone, string headUrl) { Dictionary <string, object> allMap = new Dictionary <string, object>(); if (loginName.Length == 0 || passWord.Length == 0) { allMap.Add("result", "1"); allMap.Add("message", "用户名、密码不能为空!"); return(JsonHelper.ToJson(allMap)); } DataSet ds0 = dbMysql.seleDB("select * from t_people where loginName = '" + loginName + "'"); if (ds0.Tables[0].Rows.Count > 0) { allMap.Add("result", "1"); allMap.Add("message", "该用户已经存在!"); return(JsonHelper.ToJson(allMap)); } string fileName = FileUploadImage(headUrl); if (fileName != null) { string imageUrl = "/image/" + fileName; } else { headUrl = "/image/user_head.png"; } Dictionary <string, object> inertMap = new Dictionary <string, object>(); inertMap.Add("loginName", loginName); inertMap.Add("passWord", passWord); inertMap.Add("name", name); inertMap.Add("age", age); inertMap.Add("sex", sex); inertMap.Add("phone", phone); inertMap.Add("headUrl", headUrl); string inertSql = SqlUtil.getInsertSql("t_people", inertMap); // return inertSql; try { // 插入新用户 dbMysql.ExecuteSql(inertSql); // 查出新用户 DataSet ds = dbMysql.seleDB("SELECT * FROM t_people ORDER BY id DESC LIMIT 0, 1"); Dictionary <string, object> voMap = JsonHelper.DataRowToDictionary(ds.Tables[0].Rows[0]); allMap.Add("result", "0"); allMap.Add("people", voMap); return(JsonHelper.ToJson(allMap)); } catch (Exception ex) { allMap.Add("result", "1"); allMap.Add("message", "插入报错"); return(JsonHelper.ToJson(allMap)); } }
protected void build_poll_radios() { List <SqlParameter> p = new List <SqlParameter>(); List <double> votes = new List <double>(); int i = 0; foreach (Guid op in id_list) { if (option_list[i] != "") { p.Clear(); p.Add(new SqlParameter("@option_id", op)); SqlDataReader reader = SqlUtil.ExecuteReader("select * from Votes where Option_ID=@option_id", p); DataTable dt = new DataTable(); dt.Load(reader); reader.Close(); votes.Add(dt.Rows.Count); } i++; } if (!has_voted()) { if (option_list[0] != "") { option1.Text = option_list[0]; option1.Visible = true; } if (option_list[1] != "") { option2.Text = option_list[1]; option2.Visible = true; } if (option_list[2] != "") { option3.Text = option_list[2]; option3.Visible = true; } if (option_list[3] != "") { option4.Text = option_list[3]; option4.Visible = true; } if (option_list[4] != "") { option5.Text = option_list[4]; option5.Visible = true; } if (option_list[5] != "") { option6.Text = option_list[5]; option6.Visible = true; } if (option_list[6] != "") { option7.Text = option_list[6]; option7.Visible = true; } if (option_list[7] != "") { option8.Text = option_list[7]; option8.Visible = true; } if (option_list[8] != "") { option9.Text = option_list[8]; option9.Visible = true; } if (option_list[9] != "") { option10.Text = option_list[9]; option10.Visible = true; } submit_vote.Visible = true; } else { double total = 0; foreach (double vo in votes) { total += vo; } int j = 0; if (option_list[j] != "") { poll_option_desc1.Visible = true; poll_option_desc1.Text = " " + option_list[j]; poll_option_percent1.Visible = true; if (total > 0) { poll_option_percent1.Text = " " + Math.Round(((votes[j] / total)) * 100).ToString() + "%"; } else { poll_option_percent1.Text = "0%"; } poll_option_votes1.Visible = true; poll_option_votes1.Text = votes[j].ToString() + " Votes"; poll_option_bar1.Visible = true; if (total > 0) { poll_option_bar1.Style.Add("width", (((votes[j] / total) * 100).ToString() + "%")); } else { poll_option_bar1.Style.Add("width", "0%"); } j++; } if (option_list[j] != "") { poll_option_desc2.Visible = true; poll_option_desc2.Text = " " + option_list[j]; poll_option_percent2.Visible = true; if (total > 0) { poll_option_percent2.Text = " " + Math.Round(((votes[j] / total)) * 100).ToString() + "%"; } else { poll_option_percent2.Text = "0%"; } poll_option_votes2.Visible = true; poll_option_votes2.Text = votes[j].ToString() + " Votes"; poll_option_bar2.Visible = true; if (total > 0) { poll_option_bar2.Style.Add("width", (((votes[j] / total) * 100).ToString() + "%")); } else { poll_option_bar2.Style.Add("width", "0%"); } j++; } if (option_list[j] != "") { poll_option_desc3.Visible = true; poll_option_desc3.Text = " " + option_list[j]; poll_option_percent3.Visible = true; if (total > 0) { poll_option_percent3.Text = " " + Math.Round(((votes[j] / total)) * 100).ToString() + "%"; } else { poll_option_percent3.Text = "0%"; } poll_option_votes3.Visible = true; poll_option_votes3.Text = votes[j].ToString() + " Votes"; poll_option_bar3.Visible = true; if (total > 0) { poll_option_bar3.Style.Add("width", (((votes[j] / total) * 100).ToString() + "%")); } else { poll_option_bar3.Style.Add("width", "0%"); } j++; } if (option_list[j] != "") { poll_option_desc4.Visible = true; poll_option_desc4.Text = " " + option_list[j]; poll_option_percent4.Visible = true; if (total > 0) { poll_option_percent4.Text = " " + Math.Round(((votes[j] / total)) * 100).ToString() + "%"; } else { poll_option_percent4.Text = "0%"; } poll_option_votes4.Visible = true; poll_option_votes4.Text = votes[j].ToString() + " Votes"; poll_option_bar4.Visible = true; if (total > 0) { poll_option_bar4.Style.Add("width", (((votes[j] / total) * 100).ToString() + "%")); } else { poll_option_bar4.Style.Add("width", "0%"); } j++; } if (option_list[j] != "") { poll_option_desc5.Visible = true; poll_option_desc5.Text = " " + option_list[j]; poll_option_percent5.Visible = true; if (total > 0) { poll_option_percent5.Text = " " + Math.Round(((votes[j] / total)) * 100).ToString() + "%"; } else { poll_option_percent5.Text = "0%"; } poll_option_votes5.Visible = true; poll_option_votes5.Text = votes[j].ToString() + " Votes"; poll_option_bar5.Visible = true; if (total > 0) { poll_option_bar5.Style.Add("width", (((votes[j] / total) * 100).ToString() + "%")); } else { poll_option_bar5.Style.Add("width", "0%"); } j++; } if (option_list[j] != "") { poll_option_desc6.Visible = true; poll_option_desc6.Text = " " + option_list[j]; poll_option_percent6.Visible = true; if (total > 0) { poll_option_percent6.Text = " " + Math.Round(((votes[j] / total)) * 100).ToString() + "%"; } else { poll_option_percent6.Text = "0%"; } poll_option_votes6.Visible = true; poll_option_votes6.Text = votes[j].ToString() + " Votes"; poll_option_bar6.Visible = true; if (total > 0) { poll_option_bar6.Style.Add("width", (((votes[j] / total) * 100).ToString() + "%")); } else { poll_option_bar6.Style.Add("width", "0%"); } j++; } if (option_list[j] != "") { poll_option_desc7.Visible = true; poll_option_desc7.Text = " " + option_list[j]; poll_option_percent7.Visible = true; if (total > 0) { poll_option_percent7.Text = " " + Math.Round(((votes[j] / total)) * 100).ToString() + "%"; } else { poll_option_percent7.Text = "0%"; } poll_option_votes7.Visible = true; poll_option_votes7.Text = votes[j].ToString() + " Votes"; poll_option_bar7.Visible = true; if (total > 0) { poll_option_bar7.Style.Add("width", (((votes[j] / total) * 100).ToString() + "%")); } else { poll_option_bar7.Style.Add("width", "0%"); } j++; } if (option_list[j] != "") { poll_option_desc8.Visible = true; poll_option_desc8.Text = " " + option_list[j]; poll_option_percent8.Visible = true; if (total > 0) { poll_option_percent8.Text = " " + Math.Round(((votes[j] / total)) * 100).ToString() + "%"; } else { poll_option_percent8.Text = "0%"; } poll_option_votes8.Visible = true; poll_option_votes8.Text = votes[j].ToString() + " Votes"; poll_option_bar8.Visible = true; if (total > 0) { poll_option_bar8.Style.Add("width", (((votes[j] / total) * 100).ToString() + "%")); } else { poll_option_bar8.Style.Add("width", "0%"); } j++; } if (option_list[j] != "") { poll_option_desc9.Visible = true; poll_option_desc9.Text = " " + option_list[j]; poll_option_percent9.Visible = true; if (total > 0) { poll_option_percent9.Text = " " + Math.Round(((votes[j] / total)) * 100).ToString() + "%"; } else { poll_option_percent9.Text = "0%"; } poll_option_votes9.Visible = true; poll_option_votes9.Text = votes[j].ToString() + " Votes"; poll_option_bar9.Visible = true; if (total > 0) { poll_option_bar9.Style.Add("width", (((votes[j] / total) * 100).ToString() + "%")); } else { poll_option_bar9.Style.Add("width", "0%"); } j++; } if (option_list[j] != "") { poll_option_desc10.Visible = true; poll_option_desc10.Text = " " + option_list[j]; poll_option_percent10.Visible = true; if (total > 0) { poll_option_percent10.Text = " " + Math.Round(((votes[j] / total)) * 100).ToString() + "%"; } else { poll_option_percent10.Text = "0%"; } poll_option_votes10.Visible = true; poll_option_votes10.Text = votes[j].ToString() + " Votes"; poll_option_bar10.Visible = true; if (total > 0) { poll_option_bar10.Style.Add("width", (((votes[j] / total) * 100).ToString() + "%")); } else { poll_option_bar10.Style.Add("width", "0%"); } j++; } } }
protected void Page_Load(object sender, EventArgs e) { require_login(); IList <string> seg = Request.GetFriendlyUrlSegments(); if (!Guid.TryParse(seg[0], out post_id)) { Response.Redirect("/Board/404.aspx"); } List <SqlParameter> p = new List <SqlParameter>(); p.Add(new SqlParameter("@post_id", post_id)); SqlDataReader reader = SqlUtil.ExecuteReader("select * from board_post where BpostID=@post_id", p); if (!reader.Read()) { reader.Close(); Response.Redirect("404.aspx"); return; } Byte[] bytes = (Byte[])reader["Attachments"]; view_title.Text = (string)reader["Title"]; board = (byte)reader["Board"]; view_description.Text = (string)reader["Description"]; if (bytes.Length > 0) { string str = Convert.ToBase64String(bytes, 0, bytes.Length); view_image.ImageUrl = "data:image/png;base64," + str; view_image.Visible = true; view_image_label.Visible = true; } reader.Close(); if (board == 2) { p.Clear(); p.Add(new SqlParameter("@post_id", post_id)); SqlDataReader reader2 = SqlUtil.ExecuteReader("select * from poll_options where BpostID=@post_id", p); option_list = new List <string>(); id_list = new List <Guid>(); int i = 0; while (reader2.Read()) { option_list.Add(reader2.GetString(2)); id_list.Add(reader2.GetGuid(0)); i++; } while (i < 10) { option_list.Add(""); i++;//good fix for bad code } reader2.Close(); build_poll_radios(); } }
/// <summary> /// Data handling method to add/update WatchListEntity based on Id. /// </summary> /// <param name="watchListEntity">WatchListEntity to be saved or updated.</param> /// <returns>Id of WatchListEntity inserted/updated.</returns> public int SaveWatchListItem(WatchListEntity watchListEntity) { int watchListIdSaved; try { using (DbCommand cmd = Database.GetStoredProcCommand(DataAccess.StoredProcedure.Dbo.WATCH_LIST_ITEM_SAVE)) { cmd.Connection = Database.CreateConnection(); cmd.Connection.Open(); Database.AddInParameter(cmd, DataAccess.Params.BSE_SYMBOL, DbType.String, SqlUtil.ParameterValue(watchListEntity.BseSymbol)); Database.AddInParameter(cmd, DataAccess.Params.NSE_SYMBOL, DbType.String, SqlUtil.ParameterValue(watchListEntity.NseSymbol)); Database.AddInParameter(cmd, DataAccess.Params.NAME, DbType.String, SqlUtil.ParameterValue(watchListEntity.Name)); Database.AddInParameter(cmd, DataAccess.Params.ALT_NAME_ONE, DbType.String, SqlUtil.ParameterValue(watchListEntity.AltNameOne)); Database.AddInParameter(cmd, DataAccess.Params.ALT_NAME_TWO, DbType.String, SqlUtil.ParameterValue(watchListEntity.AltNameTwo)); Database.AddInParameter(cmd, DataAccess.Params.ALT_NAME_THREE, DbType.String, SqlUtil.ParameterValue(watchListEntity.AltNameThree)); Database.AddInParameter(cmd, DataAccess.Params.TEMP_NAME, DbType.String, SqlUtil.ParameterValue(watchListEntity.TempName)); Database.AddInParameter(cmd, DataAccess.Params.IS_ACTIVE, DbType.Boolean, SqlUtil.ParameterValue(watchListEntity.IsActive)); Database.AddInParameter(cmd, DataAccess.Params.ALERT_REQUIRED, DbType.Boolean, SqlUtil.ParameterValue(watchListEntity.AlertRequired)); Database.AddInParameter(cmd, DataAccess.Params.MODIFIED_ON, DbType.DateTime, SqlUtil.ParameterValue(watchListEntity.ModifiedOn)); Database.AddInParameter(cmd, DataAccess.Params.CREATED_ON, DbType.DateTime, SqlUtil.ParameterValue(watchListEntity.CreatedOn)); Database.AddParameter(cmd, DataAccess.Params.WATCH_LIST_ID, DbType.Int32, ParameterDirection.InputOutput, null, DataRowVersion.Default, watchListEntity.WatchListID); var dbRes = cmd.ExecuteNonQuery(); watchListIdSaved = SqlUtil.SetValue(cmd.Parameters["@" + DataAccess.Params.WATCH_LIST_ID], 0); // Set the value to 0 if DB operation failed. watchListIdSaved = (dbRes > 0) ? watchListIdSaved : 0; } } catch (Exception exception) { watchListIdSaved = 0; } return(watchListIdSaved); }
/// <summary> /// Data handling method to search for WatchList entities based on search criteria. /// </summary> /// <param name="searchCriteria">The search criteria object containing all required criteria info.</param> /// <param name="watchListId">Id of particular watchlist entity that has to be fetched. Pass 0 if not applicable.</param> /// <returns>List of WatchListEntity.</returns> public IList <WatchListEntity> SearchWatchList(GridSearchCriteriaEntity searchCriteria, int watchListId) { var watchList = new List <WatchListEntity>(); try { using (DbCommand cmd = Database.GetStoredProcCommand(DataAccess.StoredProcedure.Dbo.WATCH_LIST_SEARCH)) { cmd.Connection = Database.CreateConnection(); cmd.Connection.Open(); Database.AddInParameter(cmd, DataAccess.Params.WATCH_LIST_ID, DbType.Int32, SqlUtil.ParameterValue(watchListId)); Database.AddInParameter(cmd, DataAccess.Params.START_ROW_INDEX, DbType.Int32, SqlUtil.ParameterValue(searchCriteria.StartRowIndex)); Database.AddInParameter(cmd, DataAccess.Params.MAXIMUM_ROWS, DbType.Int32, SqlUtil.ParameterValue(searchCriteria.MaximumRows)); Database.AddInParameter(cmd, DataAccess.Params.SORT_COLUMN, DbType.String, SqlUtil.ParameterValue(searchCriteria.SortColumn)); Database.AddInParameter(cmd, DataAccess.Params.SORT_ASCENDING, DbType.Boolean, SqlUtil.ParameterValue(searchCriteria.SortAscending)); Database.AddInParameter(cmd, DataAccess.Params.SEARCH_CRITERIA, DbType.Xml, SqlUtil.ParameterValue(searchCriteria.SearchCriteria)); Database.AddInParameter(cmd, DataAccess.Params.TEXT_SEARCH_KEY, DbType.String, SqlUtil.ParameterValue(searchCriteria.TextSearchKey)); Database.AddInParameter(cmd, DataAccess.Params.SEARCH_AGAINST, DbType.Boolean, SqlUtil.ParameterValue(searchCriteria.SearchAgainst)); Database.AddInParameter(cmd, DataAccess.Params.SEARCH_WITH_OR, DbType.Boolean, SqlUtil.ParameterValue(searchCriteria.SearchWithOr)); Database.AddParameter(cmd, DataAccess.Params.RECORD_COUNT, DbType.Int32, ParameterDirection.InputOutput, null, DataRowVersion.Default, searchCriteria.RecordCount); using (IDataReader dr = cmd.ExecuteReader()) { while (dr.Read()) { var watchListItem = new WatchListEntity(); watchListItem.Load(SqlUtil.SetValue(dr[DataAccess.Params.WATCH_LIST_ID], 0), SqlUtil.SetValue(dr[DataAccess.Params.BSE_SYMBOL], string.Empty), SqlUtil.SetValue(dr[DataAccess.Params.NSE_SYMBOL], string.Empty), SqlUtil.SetValue(dr[DataAccess.Params.NAME], string.Empty), SqlUtil.SetValue(dr[DataAccess.Params.ALT_NAME_ONE], string.Empty), SqlUtil.SetValue(dr[DataAccess.Params.ALT_NAME_TWO], string.Empty), SqlUtil.SetValue(dr[DataAccess.Params.ALT_NAME_THREE], string.Empty), SqlUtil.SetValue(dr[DataAccess.Params.TEMP_NAME], string.Empty), SqlUtil.SetValue(dr[DataAccess.Params.IS_ACTIVE], true), SqlUtil.SetValue(dr[DataAccess.Params.ALERT_REQUIRED], true), SqlUtil.SetValue(dr[DataAccess.Params.CREATED_ON], DateTime.MinValue), SqlUtil.SetValue(dr[DataAccess.Params.MODIFIED_ON], DateTime.MinValue)); watchList.Add(watchListItem); } } searchCriteria.RecordCount = SqlUtil.SetValue(cmd.Parameters["@" + DataAccess.Params.RECORD_COUNT], 0); } } catch (Exception exception) { watchList = null; } return(watchList); }
public IFetchedJob Dequeue(string[] queues, CancellationToken cancellationToken) { if (queues == null) { throw new ArgumentNullException(nameof(queues)); } if (queues.Length == 0) { throw new ArgumentException("Queue array must be non-empty.", "queues"); } Logger.Debug("Attempting to dequeue"); var timeoutSeconds = _storage.Options.InvisibilityTimeout.Negate().TotalSeconds; try { while (true) { cancellationToken.ThrowIfCancellationRequested(); try { using (new FluentNHibernateDistributedLock(_storage, "JobQueue", _storage.Options.JobQueueDistributedLockTimeout) .Acquire()) { var fluentNHibernateFetchedJob = SqlUtil.WrapForTransaction(() => { var token = Guid.NewGuid().ToString(); if (queues.Any()) { using (var session = _storage.GetSession()) { using (var transaction = session.BeginTransaction(IsolationLevel.Serializable)) { var jobQueueFetchedAt = _storage.UtcNow; var cutoff = jobQueueFetchedAt.AddSeconds(timeoutSeconds); if (Logger.IsDebugEnabled()) { Logger.Debug(string.Format("Getting jobs where {0}=null or {0}<{1}", nameof(_JobQueue.FetchedAt), cutoff)); } var jobQueue = session.Query <_JobQueue>() .FirstOrDefault(i => (i.FetchedAt == null || i.FetchedAt < cutoff) && queues.Contains(i.Queue)); if (jobQueue != null) { jobQueue.FetchToken = token; jobQueue.FetchedAt = jobQueueFetchedAt; session.Update(jobQueue); transaction.Commit(); Logger.DebugFormat("Dequeued job id {0} from queue {1}", jobQueue.Job.Id, jobQueue.Queue); var fetchedJob = new FetchedJob { Id = jobQueue.Id, JobId = jobQueue.Job.Id, Queue = jobQueue.Queue }; return(new FluentNHibernateFetchedJob(_storage, fetchedJob)); } } } } return(null); }); if (fluentNHibernateFetchedJob != null) { return(fluentNHibernateFetchedJob); } } } catch (FluentNHibernateDistributedLockException) { // do nothing } catch (Exception ex) { Logger.ErrorException(ex.Message, ex); throw; } cancellationToken.WaitHandle.WaitOne(_storage.Options.QueuePollInterval); cancellationToken.ThrowIfCancellationRequested(); } } catch (OperationCanceledException) { Logger.Debug("The dequeue operation was cancelled."); return(null); } }
private string GetAlias(string name) { if (_projectionsContext.IsUnqualifiedShorthandProjection()) { return(null); } string rawName = SqlUtil.GetExactlyValue(name); foreach (var projection in _projectionsContext.GetProjections()) { if (SqlUtil.GetExactlyExpression(rawName).EqualsIgnoreCase(SqlUtil.GetExactlyExpression(SqlUtil.GetExactlyValue(projection.GetExpression())))) { return(projection.GetAlias()); } if (rawName.EqualsIgnoreCase(projection.GetAlias())) { return(rawName); } } return(null); }
/// <summary> /// Append to Dest Feature Class. Auto map same field name. /// Filter export only objectID in listFilterObjectIDs of source FeatureClass. /// </summary> /// <param name="fclassSrc"></param> /// <param name="fclassDest"></param> /// <param name="listFilterObjectIDs"></param> public int Append(IFeatureClass fclassSrc, IFeatureClass fclassDest, List <int> listFilterObjectIDs) { if (fclassSrc == null) { return(0); } if (fclassDest == null) { throw new ArgumentNullException("fclassDest", "Destination FeatureClass must not be null."); } if (listFilterObjectIDs == null) { throw new ArgumentNullException("listFilterObjectIDs", "listFilterObjectIDs must not be null."); } if (listFilterObjectIDs.Count == 0) { return(0); } List <List <int> > listParts = CollectionUtil.SplitToParts(listFilterObjectIDs, 2000); int part = 0; string sqlWhereIn; IQueryFilter filter; IFeatureCursor ftCursorSrc = null; IFeature ftSrc; IFeature ftDest; // Make key Upper MakeAllDictConvertFieldValueKeyUpper(); int count = 0; int total = listFilterObjectIDs.Count; int percent = 0; int updateInterval = PercentCallbackInterval; int nextUpdatePercent = updateInterval; try { foreach (var listObjectIDPart in listParts) { part++; sqlWhereIn = SqlUtil.CreateWhereIn(fclassSrc.OIDFieldName, listObjectIDPart); filter = new QueryFilterClass(); filter.WhereClause = sqlWhereIn; ftCursorSrc = fclassSrc.Search(filter, false); // Loop Src Record while ((ftSrc = ftCursorSrc.NextFeature()) != null) { ftDest = fclassDest.CreateFeature(); // Graphic CopyShapeFieldValue(ftSrc, ftDest); // Attribute CopyFieldsValue(ftSrc, ftDest); // Save ftDest.Store(); count++; percent = CalPercent(count, total); if (percent >= nextUpdatePercent) { ProgressCallback?.Invoke(percent); nextUpdatePercent += updateInterval; } } } } finally { if (ftCursorSrc != null) { ComReleaser.ReleaseCOMObject(ftCursorSrc); ftCursorSrc = null; } } return(count); }
public MainPage() { this.InitializeComponent(); MyContent.Navigate(typeof(Sales)); SqlUtil.LoadDatabase(); }
/// <summary> /// Cleans the and reloads the table containing geo data /// </summary> public static void CleanAndReloadDb() { List <GeoPlace> geoList = GetGeoPlacesFromEmbeddedFile(); using (var conn = new NpgsqlConnection(PGConnection)) { conn.Open(); // Re-create table string createTableQuery = "DROP TABLE IF EXISTS cities;CREATE TABLE cities(id varchar(250) NOT NULL,shortname varchar(250) NOT NULL,name varchar(250) NOT NULL,lat numeric(9, 6) NOT NULL,lng numeric(9, 6) NOT NULL,population bigint NOT NULL)WITH(OIDS = FALSE);"; using (NpgsqlCommand command = new NpgsqlCommand(createTableQuery, conn)) { command.ExecuteNonQuery(); } // populate table int batchSize = 50; foreach (IEnumerable <GeoPlace> geoBatch in geoList.Batch(batchSize)) { // Prepare batch command // 1 command length can be about 400-450 StringBuilder sb = new StringBuilder(batchSize * 500); foreach (GeoPlace geo in geoBatch) { sb.AppendFormat("insert into cities(id, shortname, name, lat, lng, population) values('{0}','{1}','{2}',{3},{4},{5});", SqlUtil.EscapeString(geo.ID), SqlUtil.EscapeString(geo.ShortName), SqlUtil.EscapeString(geo.Name), geo.Location.Lat, geo.Location.Lon, geo.Population); } string cmdText = sb.ToString(); using (NpgsqlCommand command = new NpgsqlCommand(cmdText, conn)) { command.ExecuteNonQuery(); } } } }
public AggregationDistinctProjectionSegment(int startIndex, int stopIndex, AggregationTypeEnum type, int innerExpressionStartIndex, string distinctExpression) : base(startIndex, stopIndex, type, innerExpressionStartIndex) { this._distinctExpression = SqlUtil.GetExpressionWithoutOutsideParentheses(distinctExpression); }
protected void Page_Load(object sender, EventArgs e) { IList <string> segments = Request.GetFriendlyUrlSegments(); uid = segments[0]; Guid id; if (!Guid.TryParse(uid, out id)) { Response.Redirect(ResolveUrl("UserNotFound.aspx")); } List <SqlParameter> parameters = new List <SqlParameter>(); parameters.Add(new SqlParameter("uid", uid)); SqlDataReader reader = SqlUtil.ExecuteReader("SELECT Fname, Lname FROM User_Main WHERE ID_Num = @uid", parameters); if (!reader.Read()) { reader.Close(); Response.Redirect(ResolveUrl("UserNotFound.aspx")); } name = reader["Fname"] + " " + reader["Lname"]; reader.Close(); parameters.Clear(); parameters.Add(new SqlParameter("uid", uid)); SqlDataReader r = SqlUtil.ExecuteReader("SELECT * FROM Blog_Post WHERE ID_Num = @uid", parameters); while (r.Read()) { BlogPost post = new BlogPost(); post.blogID = Guid.Parse(r["BlogID"].ToString()); post.title = r["Title"].ToString(); post.body = r["Body"].ToString(); posts.Add(post); } r.Close(); parameters.Clear(); parameters.Add(new SqlParameter("@uid", uid)); r = SqlUtil.ExecuteReader("SELECT *, User_Main.Fname, User_Main.Lname, User_Main.ID_Num FROM BlogFollowers" + " INNER JOIN User_Main ON BlogFollowers.Follower = User_Main.ID_Num" + " WHERE Following = @uid", parameters); while (r.Read()) { UserProfile user = new UserProfile(); user.name = r["Fname"] + " " + r["Lname"]; user.uid = Guid.Parse(r["ID_Num"].ToString()); following.Add(user); } r.Close(); parameters.Clear(); parameters.Add(new SqlParameter("@uid", uid)); r = SqlUtil.ExecuteReader("SELECT *, User_Main.Fname, User_Main.Lname, User_Main.ID_Num FROM BlogFollowers" + " INNER JOIN User_Main ON BlogFollowers.Following = User_Main.ID_Num" + " WHERE Follower = @uid", parameters); while (r.Read()) { UserProfile user = new UserProfile(); user.name = r["Fname"] + " " + r["Lname"]; user.uid = Guid.Parse(r["ID_Num"].ToString()); followers.Add(user); } r.Close(); if (Session["loggedIn"] != null) { parameters.Clear(); parameters.Add(new SqlParameter("profile_uid", uid)); parameters.Add(new SqlParameter("uid", Session["uid"])); r = SqlUtil.ExecuteReader("SELECT * FROM BlogFollowers WHERE Following = @profile_uid AND Follower = @uid", parameters); if (r.Read()) { followingUser = true; } r.Close(); } }
public static bool Prefix(ref RunAggregateDatas __result, ref string database, ref string userId, ref string altUserId, ref int page, ref int numPerPage, ref HadesNetworkCaller.SortFieldName sortFieldName, ref HadesNetworkCaller.SortDirection sortDirection) { // Get the filter manager. I don't think there's a way to pass this as an argument, so we'll have to // set it manually. FilterManager manager = AdvancedRunHistory.filterManager; // This is just vanilla code. altUserId = altUserId ?? string.Empty; int environment = (int)AppManager.EnvironmentConfig.Environment; string commandText = string.Format("SELECT {0} FROM '{1}' WHERE ({2} = '{3}' OR {4} = '{5}') AND {6} = {7} ORDER BY {8} {9}", "runId", "runHistoryTable", "userId", userId, "userId", altUserId, "env", environment, sortFieldName, sortDirection); List <string> runIds = new List <string>(); if (!SqlUtil.ExecuteReader(database, commandText, ErrorFile.RunMinDbEntry, 3, delegate(SqliteDataReader reader) { while (reader.Read()) { runIds.Add(reader.GetString(0)); } return(true); }, exactlyOneRead: false)) { __result = null; return(false); } // The actual patch; start by assuming we don't want to filter. List <string> filteredRunIds = runIds; // Only filter runs if the manager is active- if (manager.Active) { // Make a new list of runIds. filteredRunIds = new List <String>(); // Go through all runIds in the original list. foreach (string runId in runIds) { // Try to read the run from the DB. RunMinDbEntry runMinDbEntry = RunMinDbEntry.ReadFromDb(database, runId); if (runMinDbEntry != null) { // Create a RunAggregateData. Assume it's eglibile. RunAggregateData runAggregateData = runMinDbEntry.minimalRunData.CreateRunAggregateData(); bool isEgligible = true; // Go through all filters and make the run uneglibile if it doesn't pass. foreach (IRunDataFilter filter in manager.Filters) { if (!filter.IsEgligible(runAggregateData)) { isEgligible = false; break; } } // The run has passed all filters, add it to the filtered list. if (isEgligible) { filteredRunIds.Add(runId); } } } } // Back to vanilla code, but changing runIds --> filteredRunIds. List <string> list = new List <string>(); List <RunAggregateData> list2 = new List <RunAggregateData>(); for (int i = (page - 1) * numPerPage; i < filteredRunIds.Count; i++) { if (list2.Count >= numPerPage) { break; } RunMinDbEntry runMinDbEntry = RunMinDbEntry.ReadFromDb(database, filteredRunIds[i]); if (runMinDbEntry != null) { RunAggregateData runAggregateData = runMinDbEntry.minimalRunData.CreateRunAggregateData(); string item = JsonUtility.ToJson(runAggregateData); list.Add(item); list2.Add(runAggregateData); } } int pageCount = filteredRunIds.Count / numPerPage + Math.Min(filteredRunIds.Count % numPerPage, 1); RunAggregateDatas runAggregateDatas = new RunAggregateDatas(list.ToArray(), pageCount, page); runAggregateDatas.SetRuns(list2.ToArray()); __result = runAggregateDatas; return(false); }
public void Update(UpdateKeyValueList list) { ExecuteComand(SqlUtil.BuildUpdate(list)); }
protected void Page_Load(object sender, EventArgs e) { if (Session["loggedIn"] == null) //TODO: tell the user they need to login { Response.Redirect("../Login.aspx"); } else { if (!IsPostBack) { collegedrop.Items.Insert(0, new ListItem("Pick a college", "0")); collegedrop.SelectedIndex = 0; countryDrop.Items.Insert(0, new ListItem("Pick a country", "0")); countryDrop.SelectedIndex = 0; stateDrop.Items.Insert(0, new ListItem("Pick a state", "0")); stateDrop.SelectedIndex = 0; cityDrop.Items.Insert(0, new ListItem("Pick a city", "0")); cityDrop.SelectedIndex = 0; companyDrop.Items.Insert(0, new ListItem("Pick a company", "0")); companyDrop.SelectedIndex = 0; majorDrop.Items.Insert(0, new ListItem("Pick a major", "0")); majorDrop.SelectedIndex = 0; termDrop.Items.Insert(0, new ListItem("Pick a position", "0")); termDrop.SelectedIndex = 0; classificationDrop.Items.Insert(0, new ListItem("Pick a classification", "0")); classificationDrop.SelectedIndex = 0; SqlDataReader reader = SqlUtil.ExecuteReader("SELECT *, User_Main.Fname AS MFname, User_Main.Lname AS MLname FROM Intern_Posting LEFT JOIN User_Main ON " + "Intern_Posting.ID_Num = User_Main.ID_Num"); while (reader.Read()) { intern view = new intern(); view.major = reader["Major"].ToString(); view.name = reader["MFname"] + " " + reader["MLname"]; view.classification = reader["Classification"].ToString(); view.position = reader["Position"].ToString(); view.company = reader["Company"].ToString(); view.location = reader["City"].ToString() + "," + reader["State"].ToString() + "," + reader["Country"].ToString(); view.long_desc = reader["Long_Disc"].ToString(); view.resources = reader["Resources_Used"].ToString(); view.lessons = reader["Lessons_Learned"].ToString(); view.facebook = reader["Facebook"].ToString(); view.twitter = reader["Twitter"].ToString(); view.email = reader["Email"].ToString(); view.linkedIn = reader["LinkedIn"].ToString(); view.instagram = reader["Instagram"].ToString(); view.id = reader["ID_Num"].ToString(); views.Add(view); } reader.Close(); } } }
protected void Application_End(object sender, EventArgs e) { SqlUtil.destroy(); }
// must be run from the SQLite thread public static void Run(Notebook notebook, ScriptEnv env, ScriptRunner runner, Ast.ImportCsvStmt stmt) { var importer = new ImportCsvStmtRunner(notebook, env, runner, stmt); SqlUtil.WithTransaction(notebook, importer.Import); }
public void Process(string connectionString, string tableName) { string primaryKeyFieldName = SplitTableConfigHelper.GetConfigValue(connectionString, tableName, "PrimaryKeyFieldName"); string createTableScript = SplitTableConfigHelper.GetConfigValue(connectionString, tableName, "ArchiveTableScript"); string archiveWhereSql = SplitTableConfigHelper.GetConfigValue(connectionString, tableName, "ArchiveSQL"); //把上个月、已完成的转入Archive表 //把上个月、IsDeleted=1的转入Archive表 DateTime yesterday = DateTime.Now.AddDays(-1); string contentArchiveTableName = string.Format("{0}.Archived.{1}", tableName, yesterday.ToString("yyyyMMdd")); createTableScript = string.Format(createTableScript, contentArchiveTableName); string createContentArchiveTableSql = @" IF NOT EXISTS( SELECT 1 FROM [SplitTableMappings](NOLOCK) WHERE [PhysicalTableName]='" + contentArchiveTableName + @"' AND [LogicalTableName]='" + tableName + @"' ) BEGIN " + createTableScript + @" END IF NOT EXISTS( SELECT 1 FROM [SplitTableMappings](NOLOCK) WHERE [PhysicalTableName]='" + contentArchiveTableName + @"' AND [LogicalTableName]='" + tableName + @"' ) BEGIN INSERT INTO [SplitTableMappings](LogicalTableName, PhysicalTableName) VALUES('" + tableName + @"', '" + contentArchiveTableName + @"') END "; SqlUtil.ExecuteNonQuery(connectionString, createContentArchiveTableSql); string selectHotTableNamesSql = "SELECT [PhysicalTableName] FROM [SplitTableMappings](NOLOCK) WHERE HotTable=1 AND LogicalTableName='" + tableName + "'"; List <string> hotTables = SqlUtil.GetStringList(connectionString, selectHotTableNamesSql); foreach (var hotTable in hotTables) { if (hotTable == contentArchiveTableName) { continue; } string sql = @" BEGIN TRY TRUNCATE TABLE ##MoveRecords END TRY BEGIN CATCH END CATCH BEGIN TRY DROP TABLE ##MoveRecords END TRY BEGIN CATCH END CATCH SELECT * INTO ##MoveRecords FROM ( SELECT TOP 500 * FROM [" + hotTable + @"](READPAST) WHERE " + archiveWhereSql + @" ) TBL BEGIN TRANSACTION DELETE FROM [" + hotTable + @"] WHERE [" + primaryKeyFieldName + @"] IN (SELECT [" + primaryKeyFieldName + @"] FROM ##MoveRecords(NOLOCK)) INSERT INTO [" + contentArchiveTableName + @"] SELECT * FROM ##MoveRecords(NOLOCK) COMMIT TRANSACTION DROP TABLE ##MoveRecords "; SqlUtil.ExecuteNonQuery(connectionString, sql); } }
private void BasePatientInfo_Load(object sender, EventArgs e) { SqlUtil.App = m_app; SetWaitDialogCaption("正在读取患者基本信息"); if (string.IsNullOrEmpty(m_NoOfInpat)) { SqlUtil.App.CustomMessageBox.MessageShow("无法找到病人基本信息!"); btnSave.Enabled = false; //return; } else { //获取病人基本信息 m_Table = SqlUtil.GetRedactPatientInfoFrm("14", "", m_NoOfInpat); if (m_Table.Rows.Count <= 0) { SqlUtil.App.CustomMessageBox.MessageShow("病人没有基本信息!"); btnSave.Enabled = false; //return; } } //加载基本信息 m_UCBaseInfo = new UCBaseInfo(m_Table, m_NoOfInpat); m_UCBaseInfo.Dock = DockStyle.Fill; tabPageBaseInfo.Controls.Add(m_UCBaseInfo); //加载第一联系人 m_UCLinkman = new UCLinkman(m_NoOfInpat); m_UCLinkman.Dock = DockStyle.Fill; tabPageLinkman.Controls.Add(m_UCLinkman); // SetWaitDialogCaption("正在读取患者就诊信息"); //加载就诊信息 m_UCDiacrisis = new UCDiacrisis(m_Table, m_NoOfInpat); m_UCDiacrisis.Dock = DockStyle.Fill; tabPageDiacrisis.Controls.Add(m_UCDiacrisis); //SetWaitDialogCaption("正在读取患者家族史"); ////加载家族史 //m_UCFamilyHistory = new UCFamilyHistory(m_NoOfInpat); //m_UCFamilyHistory.Dock = DockStyle.Fill; //this.tabPageFamilyHistory.Controls.Add(m_UCFamilyHistory); ////加载个人史 //m_UCPersonalHistory = new UCPersonalHistory(m_NoOfInpat); //m_UCPersonalHistory.Dock = DockStyle.Fill; //this.tabPagePersonalHistory.Controls.Add(m_UCPersonalHistory); ////加载过敏史 //m_UCAllergicHistory = new UCAllergicHistory(m_NoOfInpat); //m_UCAllergicHistory.Dock = DockStyle.Fill; //this.tabPageAllergicHistory.Controls.Add(m_UCAllergicHistory); ////加载手术史 //m_UCOperationHistory = new UCOperationHistory(m_NoOfInpat); //m_UCOperationHistory.Dock = DockStyle.Fill; //tabPageOperationHistory.Controls.Add(m_UCOperationHistory); ////加载疾病史 //m_UCDiseaseHistory = new UCDiseaseHistory(m_NoOfInpat); //m_UCDiseaseHistory.Dock = DockStyle.Fill; //tabPageDiseaseHistory.Controls.Add(m_UCDiseaseHistory); //HideWaitDialog(); }
protected void Page_Load(object sender, EventArgs e) { Course SelectedCourse = SqlUtil.GetCourse(Request.QueryString["Q"].ToString()); Label1.Text = "Selected course:" + SelectedCourse.CourseName; }
public string GetExpression() { return(SqlUtil.GetExactlyValue(_type.ToString() + _innerExpression)); }