System.Data.IDataReader.Read()

Here are the examples of the csharp api System.Data.IDataReader.Read() taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

518 Examples 7

19 Source : DataReaderImporter.cs
with GNU General Public License v3.0
from darakeon

private Boolean insertData(IDataReader dr)
        {
            var hasNext = true;

            while (dr.Read() && hasNext)
            {
                hasNext = false;

                for (var i = 0; i < data.Count; i++)
                {
                    var name = dr.GetName(i);
                    var value = dr[i].ToString();

                    if (!String.IsNullOrEmpty(value))
                        hasNext = true;

                    data[name].Add(value);
                }

                RowCount++;
            }

            return hasNext;
        }

19 Source : DicomDsQueryCommand.cs
with Apache License 2.0
from DICOMcloud

public bool Execute()
        {
            Command.Connection.Open();

            try
            {
                
                using (var reader = Command.ExecuteReader())
                {
                    bool maxReached = false ;
                    List<object> queryLevelResultsKey = new List<object> ();

                    while (reader.Read())
                    {
                        foreach (var table in QueryBuilder.ProcessedColumns)
                        {
                            object keyValue = reader.GetValue(reader.GetOrdinal ( table.Key.KeyColumn.Name ) );
                            

                            if (ResponseBuilder.ResultExists ( table.Key.Name, keyValue )) 
                            { 
                                continue ; 
                            }

                            if (ShouldPaginate ( ) && table.Key.Name == ResponseBuilder.QueryLevelTableName)
                            {
                                // if this is true then we alerady have a full page 
                                // and we are skipping adding to ResponseBuilder, 
                                // we should also skip here too
                                if ( queryLevelResultsKey.Contains(keyValue))
                                {
                                    break;
                                }

                                queryLevelResultsKey.Add(keyValue);

                                if (QueryOptions.Offset >= queryLevelResultsKey.Count)
                                { 
                                    break;
                                }

                                // Now we should have enough responses
                                if (queryLevelResultsKey.Count > (QueryOptions.Offset + QueryOptions.Limit))
                                {
                                    System.Diagnostics.Debug.replacedert (QueryOptions.Limit == ResponseBuilder.GetResponse().Count());

                                    break;
                                }
                            }

                            ResponseBuilder.BeginResultSet ( table.Key.Name ) ;
                            ResponseBuilder.BeginRead();

                            foreach ( var column in table.Value )
                            {
                                object value = reader.GetValue(reader.GetOrdinal ( column ) );

                                ResponseBuilder.ReadData(table.Key.Name, column, value);
                            }
                             
                            if ( null != CountColumnName && null != CountColumnTable && 
                                 string.Compare (CountColumnTable, table.Key.Name, true) == 0 )
                            {
                                TotalCount = reader.GetInt32 (reader.GetOrdinal (CountColumnName)) ;
                            }

                            ResponseBuilder.EndRead ( ) ;
                            ResponseBuilder.EndResultSet ( ) ;
                        }

                        if (ShouldPaginate() && maxReached)
                        {
                            break;
                        }
                    }
                    
                    if (ApplyPagination)
                    {
                        TotalCount = queryLevelResultsKey.Count;
                    }
                }

                return true ;
            }
            finally
            {
                if (Command.Connection.State == System.Data.ConnectionState.Open)
                {
                    Command.Connection.Close();
                }
            }
        }

19 Source : ResultSetQueryCommand.cs
with Apache License 2.0
from DICOMcloud

public virtual bool Execute ( ) 
        {
            Command.Connection.Open ( );

            
            using ( var reader = Command.ExecuteReader ( CommandBehavior.CloseConnection | CommandBehavior.KeyInfo ) )
            {
                do
                {
                    //table name is not availabile in GetSchemaTable to compare. depend on the Column name to be unique across tables.
                    if ( null != reader.GetSchemaTable ( ).Select ( "ColumnName ='" + Columns.First() + "'"  ).FirstOrDefault ( ) )
                    {
                        List<T> results = new List<T> ( ) ;

                        while ( reader.Read ( ) )
                        {
                            T model = default(T);


                            foreach (var column in Columns )
                            {    
                                int colIndex = reader.GetOrdinal ( column ) ;
                        
                                if ( colIndex > -1 )
                                {
                                    var value = reader.GetValue ( colIndex ) ;

                                    //TODO: something is wrong here, why is the model being set again and again in the loop before being added to the results?
                                    model = this.SetValueCallback ( column, value ) ;
                                }
                            }

                            results.Add ( model ) ;
                        }

                        Result = results.AsEnumerable<T> ( ) ;

                        return true ;
                    }
                } while ( reader.NextResult ( ) ) ;
            }

            return false ;
        }

19 Source : SingleResultQueryCommand.cs
with Apache License 2.0
from DICOMcloud

public virtual bool Execute ( ) 
        {
            Command.Connection.Open ( );

            using ( var reader = Command.ExecuteReader ( CommandBehavior.CloseConnection | CommandBehavior.KeyInfo ) )
            {
                do
                {
                    while ( reader.Read ( ) )
                    {
                        //table name is not availabile in GetSchemaTable to compare. depend on the Column name to be unique across tables.
                        if ( null != reader.GetSchemaTable ( ).Select ( "ColumnName ='" + Column + "'"  ).FirstOrDefault ( ) )
                        {
                            int colIndex = reader.GetOrdinal ( Column ) ;
                            
                            if ( colIndex > -1 )
                            {
                                var value = reader.GetValue ( colIndex ) ;
                                
                                if ( SetValueCallback != null )
                                {
                                    Result = SetValueCallback (Column, value) ;

                                    return true ;
                                }
                                if ( value is T )
                                {
                                    Result = (T) value ;
                                    
                                    return true ;
                                }
                                else
                                {
                                    throw new InvalidOperationException ( "Generic type T is not supported for this Command value." ) ;
                                }
                            }
                        }
                        else
                        {
                            break ;
                        }
                    }
                } while ( reader.NextResult ( ) ) ;
            }

            return false ;
        }

19 Source : SharedKustoQueries.cs
with MIT License
from dotnet

public static (int buildId, TimeSpan buildTime) ParseBuildTime(IDataReader reader)
        {
            // There was an exception when we queried the database
            if (reader == null)
            {
                return (-1, default(TimeSpan));
            }
            Dictionary<int, TimeSpan> buildTimeResults = new Dictionary<int, TimeSpan>();

            while (reader.Read())
            {
                int definitionId = Int32.Parse(reader.GetString(0));
                TimeSpan duration = (TimeSpan) reader.GetValue(1);
                buildTimeResults[definitionId] = duration;
            }

            // There were no results
            if (buildTimeResults.Count() == 0)
            {
                return (-1, default(TimeSpan));
            }

            KeyValuePair<int, TimeSpan> maxPair = buildTimeResults.Aggregate((l,r) => l.Value > r.Value ? l : r);

            return (maxPair.Key, maxPair.Value);
        }

19 Source : Program.cs
with MIT License
from EFTEC

static void Main(string[] args) {
            string path = System.Reflection.replacedembly.GetExecutingreplacedembly().Location;
            path = path.Substring(0, path.LastIndexOf('\\') + 1);

            // Console.WriteLine("Directory: {0}", path);
            if (args.Length == 0 || args[0].ToLower() == "help") {
                ShowUsage();
                return;
            }
            try {
                Database.Instance.Configure(path);
                IddsConfig.Instance.ApplicationPath = path;
                switch (args[0].ToLower()) {
                    case "islicensed":
                        Console.WriteLine(@"Cyberarms IDDS does not require licensing anymore. Please visit https://cyberarms.net for support options!");
                        break;
                    case "manualreport":
                        if(args.Length<2) {
                            Console.WriteLine("Please enter output filename as parameter.");
                            return;
                        }
                        string report = ReportGenerator.Instance.GetReport(String.Format("Manual report, {0:MM/dd/yyyy}", DateTime.Now), 
                            String.Format("Manually created report for system {0}.{1}", System.Net.Dns.GetHostName(), System.Net.NetworkInformation.IPGlobalProperties.GetIPGlobalProperties().DomainName),""
                            ,DateTime.Now.AddMonths(-1),DateTime.Now);
                        try {
                            StreamWriter sw = System.IO.File.CreateText(args[1]);
                            sw.Write(report);
                            sw.Close();
                        } catch (Exception ex) {
                            Console.WriteLine(ex.Message);
                        }
                        break;
                    case "exportcsv":
                        if (args.Length < 2) {
                            Console.WriteLine("Please enter output filename as parameter.");
                            return;
                        }
                        int lastSquenceNumber = 0;
                        if (args.Length > 2) {
                            if (!int.TryParse(args[2], out lastSquenceNumber)) {
                                Console.WriteLine("Please enter last sequence number as parameter.");
                            }
                        }
                        try {
                            StreamWriter swexport = System.IO.File.CreateText(args[1]);
                            System.Data.IDataReader rdr = IntrusionLog.ReadDifferential(lastSquenceNumber);
                            swexport.WriteLine("Sequence Number;Date and Time;Security Agent;IP Address;Status");
                            while(rdr.Read()) {
                                swexport.WriteLine("{0};{1};{2};{3};{4}", rdr[0].ToString(), rdr[1].ToString(), SecurityAgents.Instance.GetDisplayName(rdr[2].ToString()),
                                    rdr[3].ToString(), IntrusionLog.GetStatusName(int.Parse(rdr[4].ToString())));
                            }
                            swexport.Flush();
                            swexport.Close();
                            rdr.Close();
                        } catch (Exception ex) {
                            Console.WriteLine(ex.Message);
                        }
                        break;
                    default:
                        ShowUsage();
                        break;
                }
            } catch (Exception ex) {
                Console.WriteLine(ex);
            }

        }

19 Source : IddsAdmin.cs
with MIT License
from EFTEC

void logReader_Tick(object sender, EventArgs e) {
            DateTime metering = DateTime.Now;
            if (!IsUpdating && Database.Instance.IsConfigured) {
                IsUpdating = true;
                if (CurrentMenu == labelMenuSecurityLog && IntrusionLog.HasUpdates(LastLogId)) {
                    IDataReader rdr = IntrusionLog.ReadDifferential(LastLogId);
                    int maxLogId = LastLogId;
                    while (rdr.Read()) {
                        int action = int.Parse(rdr["Action"].ToString());
                        string agentId = Shared.Db.DbValueConverter.ToString(rdr["AgentId"]);
                        PanelSecurityLog.AddLogEntry(int.Parse(rdr["id"].ToString()), action, 
                            agentId, 
                            IntrusionLog.GetStatusIcon(action), 
                            IntrusionLog.GetStatusClreplaced(action), DateTime.Parse(rdr["IncidentTime"].ToString()), rdr["ClientIP"].ToString(), 
                            GetLogMessage(agentId,action));
                        if (Convert.ToInt32(rdr["Id"]) > maxLogId) maxLogId = Convert.ToInt32(rdr["Id"]);
                    }
                    rdr.Close();
                    rdr.Dispose();
                    if (maxLogId > LastLogId) LastLogId = maxLogId;
                }
                
                if (CurrentMenu == labelMenuCurrentLocks && Locks.HasUpdates(LastLockUpdate)) {
                    LastLockUpdate = DateTime.Now;
                    PanelCurrentLocks.Clear();
                    IDataReader locksReader = Locks.ReadLocks(); 
                    while (locksReader.Read()) {
                        DateTime lockDate;
                        DateTime unlockDate;
                        DateTime.TryParse(locksReader["LockDate"].ToString(), out lockDate);
                        DateTime.TryParse(locksReader["UnlockDate"].ToString(), out unlockDate);
                        PanelCurrentLocks.Add(int.Parse(locksReader["LockId"].ToString()), global::Cyberarms.IntrusionDetection.Admin.Properties.Resources.logIcon_softLock,
                            LockStatusAdapter.GetLockStatusName(int.Parse(locksReader["Status"].ToString())), locksReader["ClientIp"].ToString(), 
                            locksReader["DisplayName"].ToString(),
                            lockDate, unlockDate, IntrusionDetection.Shared.Db.DbValueConverter.ToInt(locksReader["Status"]));
                    }
                    locksReader.Close();
                    locksReader.Dispose();
                    
                }
                if (CurrentMenu == labelMenuHome) {
                    Dashboard.SetUnsuccessfulLogins(Locks.ReadUnsuccessfulLoginAttempts(DateTime.Now.AddDays(-30)));
                    foreach(SecurityAgent agent in SecurityAgents.Instance) {
                        agent.UpdateStatistics();
                    }
                }
                if (CurrentMenu == labelMenuHome || CurrentMenu == labelMenuCurrentLocks) {
                    int softLocks = Locks.ReadCurrentSoftLocks();
                    int hardLocks = Locks.ReadCurrentHardLocks();
                    PanelCurrentLocks.SetSoftLocks(softLocks);
                    PanelCurrentLocks.SetHardLocks(hardLocks);
                    Dashboard.SetHardLocks(hardLocks);
                    Dashboard.SetSoftLocks(softLocks);
                    
                }
                if (!IsInitialized || (CurrentMenu == labelMenuHome || CurrentMenu == labelMenuSecurityLog)) {
                // ?? 
                }
            }
            IsInitialized = true;
            IsUpdating = false;
            System.Diagnostics.Debug.Print(DateTime.Now.Subtract(metering).TotalMilliseconds.ToString());
        }

19 Source : IddsConfig.cs
with MIT License
from EFTEC

public void Load() {
            if (!Database.Instance.IsConfigured) configureDatabase();
            System.Data.IDataReader reader = null;
            try {
                reader = Database.Instance.ExecuteReader("select * from Configuration order by ConfigVersionNumber desc LIMIT 1");
                if (reader.Read()) {
                    HardLockAttempts = Db.DbValueConverter.ToInt(reader["HardLockAttempts"]);
                    HardLockTimeHours = Db.DbValueConverter.ToInt(reader["HardLockTimeHours"]);
                    LockForever = Db.DbValueConverter.ToBool(reader["LockForever"]);
                    SoftLockAttempts = Db.DbValueConverter.ToInt(reader["SoftLockAttempts"]);
                    SoftLockTimeMinutes = Db.DbValueConverter.ToInt(reader["SoftLockTimeMinutes"]);
                    UseSafeNetworkList = Db.DbValueConverter.ToBool(reader["UseSafeNetworkList"]);
                    PluginDirectory = Db.DbValueConverter.ToString(reader["PluginDirectory"]);
                    SendInfoMail = Db.DbValueConverter.ToBool(reader["SendInfoMail"]);
                    SmtpPort = Db.DbValueConverter.ToInt(reader["SmtpPort"]);
                    SenderEmailAddress = Db.DbValueConverter.ToString(reader["SenderEmailAddress"]);
                    SmtpRequiresAuthentication = Db.DbValueConverter.ToBool(reader["SmtpRequiresAuthentication"]);
                    NotificationEmailAddress = Db.DbValueConverter.ToString(reader["NotificationEmailAddress"]);
                    SmtpServer = Db.DbValueConverter.ToString(reader["SmtpServer"]);
                    SmtpUsername = Db.DbValueConverter.ToString(reader["SmtpUsername"]);
                    SmtpPreplacedword = Db.DbValueConverter.ToString(reader["SmtpPreplacedword"]);
                    CyberSheriffContributor = Db.DbValueConverter.ToBool(reader["CyberSheriffContributor"]);
                    WebBasedMonitoring = Db.DbValueConverter.ToBool(reader["WebBasedMonitoring"]);
                    SmtpSslRequired = Db.DbValueConverter.ToBool(reader["SmtpSslRequired"]);
                    LoadSafeNetworks();
                } else {
                    Database.Instance.ExecuteNonQuery(Db.Version_2_1.CREATE_DEFAULT_CONFIGURATION);
                   
                }

            } catch (Exception ex) {
                throw ex;
            } finally {
                if (reader != null && !reader.IsClosed) reader.Close();
            }
        }

19 Source : SecurityAgent.cs
with MIT License
from EFTEC

public void LoadCustomConfig() {
            IDataReader rdr = Database.Instance.ExecuteReader("select PropertyName,PropertyValueString from SecurityAgentConfig where AgentId like @p0", Id);
            while (rdr.Read()) {
                string propName = Db.DbValueConverter.ToString(rdr["PropertyName"]);
                if (CustomConfiguration.ContainsKey(propName)) {
                    CustomConfiguration[propName] = Db.DbValueConverter.ToString(rdr["PropertyValueString"]);
                }
            }
            rdr.Close();
        }

19 Source : ReportGenerator.cs
with MIT License
from EFTEC

public string GetEventsPerAgent(DateTime start, DateTime end) {
            IDataReader rdr = Database.Instance.ExecuteReader(SELECT_BY_AGENT, start, end);
            string currentAgent = String.Empty;
            string currentLine = String.Empty;
            bool hasValues = false;
            StringBuilder sb = new StringBuilder();
            long intrusionAttempts = 0;
            long softLocks = 0;
            long hardLocks = 0;
            TotalIntrusionAttempts = 0;
            TotalSoftLocks = 0;
            TotalHardLocks = 0;
            string agent = String.Empty;
            while (rdr.Read()) {
                int action = Db.DbValueConverter.ToInt(rdr["Action"]);
                agent = Db.DbValueConverter.ToString(rdr["AgentName"]);
                long incidents = Db.DbValueConverter.ToInt64(rdr["Incidents"]);
                if(!agent.Equals(currentAgent) && hasValues) {
                    sb.AppendLine(SetEventsPerAgent(currentAgent, intrusionAttempts, softLocks, hardLocks));
                    currentAgent = agent;
                    intrusionAttempts = 0;
                    softLocks = 0;
                    hardLocks = 0;
                } else if (!hasValues) {
                    currentAgent = agent;
                }
                switch (action) {
                    case IntrusionLog.STATUS_INTRUSION_ATTEMPT:
                        intrusionAttempts = incidents;
                        break;
                    case IntrusionLog.STATUS_SOFT_LOCKED:
                        softLocks = incidents;
                        break;
                    case IntrusionLog.STATUS_HARD_LOCKED:
                        hardLocks = incidents;
                        break;
                }
                hasValues = true;
            }
            if (hasValues) {
                sb.AppendLine(SetEventsPerAgent(agent, intrusionAttempts, softLocks, hardLocks));
            }
            rdr.Close();
            return sb.ToString();
        }

19 Source : ReportGenerator.cs
with MIT License
from EFTEC

public string GetIncidentsByIP(int action, DateTime start, DateTime end) {
            IDataReader rdr = Database.Instance.ExecuteReader(SELECT_BY_IP, start, end, action);
            StringBuilder sb = new StringBuilder();
            while (rdr.Read()) {
                string result = GetIncidentByIPTemplate();
                string ipAddress = Db.DbValueConverter.ToString(rdr["ClientIP"]);
                long incidents = Db.DbValueConverter.ToInt64(rdr["Incidents"]);
                result = result.Replace("[%IP_ADDRESS%]", ipAddress);
                result = result.Replace("[%INTRUSION_ATTEMPTS%]", incidents.ToString());
                sb.AppendLine(result);
            }
            return sb.ToString();
        }

19 Source : Locks.cs
with MIT License
from EFTEC

public static List<Lock> GetCurrentLocks() {
            if (Database.Instance.IsConfigured) {
                List<Lock> result = new List<Lock>();
                string sqlString = @"select LockId, LockDate, UnlockDate, TriggerIncident, Status, Port, IpAddress from Locks where status in (@p0,@p1)";
                IDataReader rdr = Database.Instance.ExecuteReader(sqlString, Lock.LOCK_STATUS_HARDLOCK, Lock.LOCK_STATUS_SOFTLOCK);
                while (rdr.Read()) {
                    Lock l = new Lock();
                    l.Id = Db.DbValueConverter.ToInt64(rdr["LockId"]);
                    l.LockDate = Db.DbValueConverter.ToDateTime(rdr["LockDate"]);
                    l.UnlockDate = Db.DbValueConverter.ToDateTime(rdr["UnlockDate"]);
                    l.Status = Db.DbValueConverter.ToInt(rdr["Status"]);
                    l.Port = Db.DbValueConverter.ToInt(rdr["Port"]);
                    l.IpAddress = Db.DbValueConverter.ToString(rdr["IpAddress"]);
                    result.Add(l);
                }
                rdr.Close();
                return result;
            } else {
                throw new ApplicationException("Database not initialized");
            }
        }

19 Source : SecurityAgent.cs
with MIT License
from EFTEC

public void Reload() {
            if (!Database.Instance.IsConfigured) {
                throw new ApplicationException("Database is not configured yet. Please configure database and re-try this operation!");
            }
            if (Id == null || Id.Equals(Guid.Empty)) return;
            IDataReader rdr = Database.Instance.ExecuteReader("select * from securityAgents where AgentId=@p0", Id);
            // load all agents
            if (rdr.Read()) {
                Name = Db.DbValueConverter.ToString(rdr["Name"]);
                replacedemblyName = Db.DbValueConverter.ToString(rdr["replacedemblyName"]);
                Id = Db.DbValueConverter.ToGuid(rdr["AgentId"]);
                HardLockAttempts = Db.DbValueConverter.ToInt(rdr["HardLockAttempts"]);
                HardLockTimeHours = Db.DbValueConverter.ToInt(rdr["HardLockTimeHours"]);
                LockForever = Db.DbValueConverter.ToBool(rdr["LockForever"]);
                SoftLockAttempts = Db.DbValueConverter.ToInt(rdr["SoftLockAttempts"]);
                SoftLockTimeMinutes = Db.DbValueConverter.ToInt(rdr["SoftLockTimeMinutes"]);
                OverrideConfig = Db.DbValueConverter.ToBool(rdr["OverwriteConfiguration"]);
                DisplayName = Db.DbValueConverter.ToString(rdr["DisplayName"]);
                Enabled = Db.DbValueConverter.ToBool(rdr["Enabled"]);
                Serial = Db.DbValueConverter.ToInt(rdr["Serial"]);
            }
            rdr.Close();
            LoadCustomConfig();
        }

19 Source : SecurityAgent.cs
with MIT License
from EFTEC

public void UpdateStatistics() {
            string sqlString = "select FailedLogins, HardLocks, SoftLocks from AgentStatistics where AgentId=@p0";
            int hardLocks, failedLogins, softLocks;
            try {
                IDataReader rdr = Database.Instance.ExecuteReader(sqlString, Id);
                if (rdr.Read()) {
                    hardLocks = Db.DbValueConverter.ToInt(rdr["HardLocks"]);
                    failedLogins = Db.DbValueConverter.ToInt(rdr["FailedLogins"]);
                    softLocks = Db.DbValueConverter.ToInt(rdr["SoftLocks"]);
                    if (hardLocks != HardLocks || softLocks != SoftLocks || failedLogins != FailedLogins) {
                        HardLocks = hardLocks;
                        SoftLocks = softLocks;
                        FailedLogins = failedLogins;
                        OnStatisticsUpdated();
                    }
                } else {
                    HardLocks = 0;
                    FailedLogins = 0;
                    SoftLocks = 0;
                }
                rdr.Close();

            } catch { }
        }

19 Source : IntrusionLogTest.cs
with MIT License
from EFTEC

[TestMethod]
        public void ReadIntervalTest() {
            prepareIntrusionLog();
            IDataReader rdr = IntrusionLog.ReadInterval(new TimeSpan(0, 24, 0, 0, 0));
            if (rdr.FieldCount != 6) replacedert.Fail("Field count changed!");
            
            while (rdr.Read()) {
                System.Diagnostics.Debug.Print("Log Id {0} ({1}): {2}", rdr["Id"],rdr["IncidentTime"], rdr["ClientIP"]);
            }

        }

19 Source : IddsConfig.cs
with MIT License
from EFTEC

private Dictionary<string, string> LoadConfig(string configTable) {
            if (!Database.Instance.IsConfigured) configureDatabase();
            Dictionary<string, string> config = new Dictionary<string, string>();
            System.Data.IDataReader rdr = Database.Instance.ExecuteReader(String.Format("select ConfigKey, ConfigValue from {0}", configTable));
            while (rdr.Read()) {
                config.Add(Db.DbValueConverter.ToString(rdr["ConfigKey"]), Db.DbValueConverter.ToString(rdr["ConfigValue"]));
            }
            rdr.Close();
            return config;
        }

19 Source : IddsConfig.cs
with MIT License
from EFTEC

public CSafeNetworks LoadNetworkList(string list) {
            if (!Database.Instance.IsConfigured) configureDatabase();
            CSafeNetworks net = new CSafeNetworks();
            IDataReader rdr = Database.Instance.ExecuteReader(String.Format("Select IpAddress, NetworkMask from {0}", list));
            while (rdr.Read()) {
                net.Add(new CSafeNetwork(Db.DbValueConverter.ToString(rdr["IpAddress"]), Db.DbValueConverter.ToString(rdr["NetworkMask"])));
            }
            rdr.Close();
            return net;
        }

19 Source : Locks.cs
with MIT License
from EFTEC

public static Lock GetLockById(long id) {
            if (Database.Instance.IsConfigured) {
                Lock result = new Lock();
                string sqlString = @"select LockId, LockDate, UnlockDate, TriggerIncident, Status, Port, IpAddress from Locks where LockId = @p0";
                IDataReader rdr = Database.Instance.ExecuteReader(sqlString, id);
                if (rdr.Read()) {
                    result.Id = Db.DbValueConverter.ToInt64(rdr["LockId"]);
                    result.LockDate = Db.DbValueConverter.ToDateTime(rdr["LockDate"]);
                    result.UnlockDate = Db.DbValueConverter.ToDateTime(rdr["UnlockDate"]);
                    result.Status = Db.DbValueConverter.ToInt(rdr["Status"]);
                    result.Port = Db.DbValueConverter.ToInt(rdr["Port"]);
                    result.IpAddress = Db.DbValueConverter.ToString(rdr["IpAddress"]);
                    result.TriggerIncident = Db.DbValueConverter.ToInt64(rdr["TriggerIncident"]);
                }
                rdr.Close();
                return result;
            } else {
                throw new ApplicationException("Database not initialized");
            }
        }

19 Source : Locks.cs
with MIT License
from EFTEC

public static List<Lock> GetUnlockList() {
            List<Lock> result = new List<Lock>();
            if (Database.Instance.IsConfigured) {
                string sqlString = @"select * from Locks where (UnlockDate<@p0 and (status=@p1 or status=@p2)) or status=@p3";
                IDataReader rdr = Database.Instance.ExecuteReader(sqlString, DateTime.Now, Lock.LOCK_STATUS_HARDLOCK, Lock.LOCK_STATUS_SOFTLOCK, Lock.LOCK_STATUS_UNLOCK_REQUESTED);
                while (rdr.Read()) {
                    Lock l = new Lock();
                    l.Id = Db.DbValueConverter.ToInt64(rdr["LockId"]);
                    l.IpAddress = Db.DbValueConverter.ToString(rdr["IpAddress"]);
                    l.LockDate = Db.DbValueConverter.ToDateTime(rdr["LockDate"]);
                    l.Port = Db.DbValueConverter.ToInt(rdr["Port"]);
                    l.Status = Db.DbValueConverter.ToInt(rdr["Status"]);
                    l.TriggerIncident = Db.DbValueConverter.ToInt64(rdr["TriggerIncident"]);
                    l.UnlockDate = Db.DbValueConverter.ToDateTime(rdr["UnlockDate"]);
                    result.Add(l);
                }
                rdr.Close();
                return result;
            } else {
                throw new ApplicationException("Database not initialized");
            }
        }

19 Source : SecurityAgents.cs
with MIT License
from EFTEC

public void InitializeAgents() {
            this.Clear();
            if (!Database.Instance.IsConfigured) {
                throw new ApplicationException("Database is not configured yet. Please configure database and re-try this operation!");
            }

            IDataReader rdr = Database.Instance.ExecuteReader("select * from securityAgents");
            // load all agents
            while (rdr.Read()) {
                SecurityAgent agent = new SecurityAgent();
                agent.Name = Db.DbValueConverter.ToString(rdr["Name"]);
                agent.replacedemblyName = Db.DbValueConverter.ToString(rdr["replacedemblyName"]);
                agent.Id = Db.DbValueConverter.ToGuid(rdr["AgentId"]);
                agent.HardLockAttempts = Db.DbValueConverter.ToInt(rdr["HardLockAttempts"]);
                agent.HardLockTimeHours = Db.DbValueConverter.ToInt(rdr["HardLockTimeHours"]);
                agent.LockForever = Db.DbValueConverter.ToBool(rdr["LockForever"]);
                agent.SoftLockAttempts = Db.DbValueConverter.ToInt(rdr["SoftLockAttempts"]);
                agent.SoftLockTimeMinutes = Db.DbValueConverter.ToInt(rdr["SoftLockTimeMinutes"]);
                agent.OverrideConfig = Db.DbValueConverter.ToBool(rdr["OverwriteConfiguration"]);
                agent.DisplayName = Db.DbValueConverter.ToString(rdr["DisplayName"]);
                agent.Enabled = Db.DbValueConverter.ToBool(rdr["Enabled"]);
                agent.Serial = Db.DbValueConverter.ToInt(rdr["Serial"]);
                //agent.LoadCustomConfig();
                this.Add(agent);
            }
            rdr.Close();
        }

19 Source : EpiDataReader.cs
with Apache License 2.0
from Epi-Info

bool System.Data.IDataReader.Read()
        {
            return this.mReader.Read();
        }

19 Source : EpiWebDataSource.IDataSource.cs
with Apache License 2.0
from Epi-Info

public object GetScalar(string pSQL)
        {
            object result = null;

            try
            {
                System.Data.IDataReader ReaderResult = (System.Data.IDataReader)this.ExecuteReader(this.CreateQuery(pSQL));
                while (ReaderResult.Read())
                {
                    result = ReaderResult[0];
                    break;
                }
            }
            catch (Exception e)
            {
                Logger.Log("Error MongoDBDatabase.IDataSource.GetDataTableReader:\n" + e.ToString());
            }
            return result;
        }

19 Source : Access2007Database.IDataSource.cs
with Apache License 2.0
from Epi-Info

public object GetScalar(string pSQL)
        {
            object result = null;

            try
            {
                System.Data.IDataReader ReaderResult = (System.Data.IDataReader)this.ExecuteReader(this.CreateQuery(pSQL));
                while (ReaderResult.Read())
                {
                    result = ReaderResult[0];
                    break;
                }
            }
            catch (Exception e)
            {
                Logger.Log("Error MySQLDatabase.IDataSource.GetDataTableReader:\n" + e.ToString());
            }
            return result;
        }

19 Source : PostgreSQLDatabase.IDataSource.cs
with Apache License 2.0
from Epi-Info

public object GetScalar(string pSQL)
        {
            object result = null;
            
            try
            {
                System.Data.IDataReader ReaderResult = (System.Data.IDataReader)this.ExecuteReader(this.CreateQuery(pSQL));
                while (ReaderResult.Read())
                {
                    result = ReaderResult[0];
                    break;
                }
            }
            catch (Exception e)
            {
                Logger.Log("Error MySQLDatabase.IDataSource.GetDataTableReader:\n" + e.ToString());
            }
            return result;
        }

19 Source : MongoDBDatabase.IDataSource.cs
with Apache License 2.0
from Epi-Info

public object GetScalar(string pSQL)
        {
            object result = null;
            
            try
            {
                System.Data.IDataReader ReaderResult = (System.Data.IDataReader)this.ExecuteReader(this.CreateQuery(pSQL));
                while (ReaderResult.Read())
                {
                    result = ReaderResult[0];
                    break;
                }
            }
            catch (Exception e)
            {
                Logger.Log("Error MongoDBDatabase.IDataSource.GetDataTableReader:\n" + e.ToString());
            }
            return result;
        }

19 Source : MetadataDbProvider.cs
with Apache License 2.0
from Epi-Info

public DataTable GetViewsAsDataTable()
        {
            try
            {
                DataTable viewTable = GetDataTableTemplateForViewInfo();
                foreach (string viewName in this.GetViewNames())
                {
                    DataRow viewRow = viewTable.NewRow();
                    viewTable.Rows.Add(viewRow);

                    string queryText = string.Empty;
                    Query query;
                    DataTable tempTable;

                    // Name ...
                    viewRow[ColumnNames.NAME] = viewName;

                    List<string> tableNames = new List<string>();
                    Query selectQuery = db.CreateQuery("SELECT DISTINCT Datatable FROM " + viewName + "");                    
                    IDataReader reader = db.ExecuteReader(selectQuery);
                             
                    reader = db.ExecuteReader(selectQuery);

                    while (reader.Read())
                    {
                        string name = reader["DATATABLE"].ToString();

                        if (name.StartsWith("DATA") && !name.Contains(","))
                        {
                            tableNames.Add(name);
                        }
                    }

                    if (tableNames.Count <= 1)
                    {
                        // Data Table
                        queryText = "select [DATATABLE] from " + viewName + " where [Name] = 'DATA1'";
                        query = db.CreateQuery(queryText);
                        tempTable = db.Select(query);
                        if (tempTable.Rows.Count > 0)
                        {
                            viewRow[ColumnNames.DATA_TABLE_NAME] = tempTable.Rows[0]["DATATABLE"].ToString();
                        }
                    }
                    else if (tableNames.Count > 1)
                    {
                        viewRow[ColumnNames.DATA_TABLE_NAME] = string.Empty;
                        foreach (string s in tableNames)
                        {
                            // Data Table
                            queryText = "select [DATATABLE] from " + viewName + " where [Name] = @Name";
                            query = db.CreateQuery(queryText);
                            query.Parameters.Add(new QueryParameter("@Name", DbType.String, s));
                            tempTable = db.Select(query);
                            if (tempTable.Rows.Count > 0)
                            {
                                viewRow[ColumnNames.DATA_TABLE_NAME] = viewRow[ColumnNames.DATA_TABLE_NAME].ToString() + tempTable.Rows[0]["DATATABLE"].ToString() + ";";
                            }
                        }
                        viewRow[ColumnNames.DATA_TABLE_NAME] = viewRow[ColumnNames.DATA_TABLE_NAME].ToString().TrimEnd(';');
                    }

                    // CheckCode variable definitions
                    query = db.CreateQuery("select [Checkcode] from " + viewName + " where [Name] = 'DEFINEDVARIABLES'");
                    tempTable = db.Select(query);
                    if (tempTable.Rows.Count > 0)
                    {
                        viewRow[ColumnNames.CHECK_CODE_VARIABLE_DEFINITIONS] = tempTable.Rows[0][ColumnNames.CHECK_CODE].ToString();
                    }

                    // CheckCode Before and After
                    query = db.CreateQuery("select [Checkcode] from " + viewName + " where [Name] = 'VIEW'");
                    tempTable = db.Select(query);
                    if (tempTable.Rows.Count > 0)
                    {
                        string checkCode = tempTable.Rows[0][ColumnNames.CHECK_CODE].ToString();
                        string checkCodeBefore = string.Empty;
                        string checkCodeAfter = string.Empty;
                        SplitCheckCode(checkCode, ref checkCodeBefore, ref checkCodeAfter);
                        viewRow[ColumnNames.CHECK_CODE_BEFORE] = checkCodeBefore;
                        viewRow[ColumnNames.CHECK_CODE_AFTER] = checkCodeAfter;
                    }

                    // Record Check code Before and Afters
                    query = db.CreateQuery("select [Checkcode] from " + viewName + " where [Name] = 'RECORD'");
                    tempTable = db.Select(query);
                    if (tempTable.Rows.Count > 0)
                    {
                        string recordCheckCode = tempTable.Rows[0][ColumnNames.CHECK_CODE].ToString();
                        string recordCheckCodeBefore = string.Empty;
                        string recordCheckCodeAfter = string.Empty;
                        SplitCheckCode(recordCheckCode, ref recordCheckCodeBefore, ref recordCheckCodeAfter);
                        viewRow[ColumnNames.RECORD_CHECK_CODE_BEFORE] = recordCheckCodeBefore;
                        viewRow[ColumnNames.RECORD_CHECK_CODE_AFTER] = recordCheckCodeAfter;
                    }
                }
                return viewTable;
            }
            finally
            {

            }
        }

19 Source : Project.cs
with Apache License 2.0
from Epi-Info

public void LoadViews()
        {
            this.views = new Collection<View>();
            System.Collections.Hashtable RelatedViews = new System.Collections.Hashtable();

            DataTable viewsTable = GetViewsAsDataTable();
            foreach (DataRow viewRow in viewsTable.Rows)
            {
                View V = new Epi2000.View(viewRow, this);
                
                // set the is related view attribute
                IDataReader R = this.collectedData.GetTableDataReader(V.Name);
                while(R.Read())
                {
                    
                    if (R["Name"].ToString().ToUpperInvariant().StartsWith("RELVIEW"))
                    {
                        if(! RelatedViews.ContainsKey(R["DataTable"].ToString()))
                        {
                            RelatedViews.Add(R["DataTable"].ToString(), R["DataTable"].ToString());
                        }
                    }
                }
                R.Close();

                this.views.Add(V);
            }


            foreach(Epi2000.View V in this.views)
            {
                if (RelatedViews.ContainsKey(V.Name))
                {
                    V.IsRelatedView = true;
                }
            }
        }

19 Source : XmlMultiKeyDataUnpackager.cs
with Apache License 2.0
from Epi-Info

protected override void ImportRecords(View form, XmlNode formNode, List<PackageFieldData> records)
        {
            if (!IsUsingCustomMatchkeys) // Calling clreplaced should instantiate normal data packager if custom keys aren't used
            {
                throw new ApplicationException("This clreplaced should not be used without custom match keys.");
            }

            ImportInfo.RecordsAppended.Add(form, 0);
            ImportInfo.RecordsUpdated.Add(form, 0);

            IDbDriver destinationDb = DestinationProject.CollectedData.GetDatabase();
            
            DataTable destinationKeyTable = new DataTable();
            destinationKeyTable.Columns.Add(new DataColumn("GlobalRecordId", typeof(string)));
            destinationKeyTable.Columns.Add(new DataColumn("Update", typeof(bool)));
            destinationKeyTable.Columns.Add(new DataColumn("KeyDictionary", typeof(Dictionary<Field, object>)));
            
            DataColumn [] primaryKey = new DataColumn[1];
            primaryKey[0] = destinationKeyTable.Columns["GlobalRecordId"];
            destinationKeyTable.PrimaryKey = primaryKey;

            WordBuilder wb = new WordBuilder(",");
            wb.Add("t.GlobalRecordId");
            foreach (Field field in KeyFields)
            {
                wb.Add(field.Name);
            }

            Query selectQuery = destinationDb.CreateQuery("SELECT " + wb.ToString() + " " + form.FromViewSQL);
            using (IDataReader keyTableReader = destinationDb.ExecuteReader(selectQuery))
            {
                while (keyTableReader.Read())
                {
                    string guid = keyTableReader["GlobalRecordId"].ToString();
                    Dictionary<Field, object> keys = new Dictionary<Field, object>();

                    foreach (Field field in KeyFields)
                    {
                        keys.Add(field, keyTableReader[field.Name]);
                    }

                    destinationKeyTable.Rows.Add(guid, true, keys);
                }
            }

            var query = from record in records
                        group record by record.RecordGUID;

            IEnumerable<IEnumerable<PackageFieldData>> fieldDataLists = query as IEnumerable<IEnumerable<PackageFieldData>>;

            foreach (IEnumerable<PackageFieldData> fieldDataList in fieldDataLists)
            {
                PackageFieldData fieldData = fieldDataList.First();
                bool found = false;

                foreach (DataRow row in destinationKeyTable.Rows)
                {
                    Dictionary<Field, object> keyDictionary = row["KeyDictionary"] as Dictionary<Field, object>;

                    if (AreKeyFieldDictionariesEqual(keyDictionary, fieldData.KeyValues))
                    {
                        found = true;
                        if (!Update)
                        {
                            row["Update"] = false;
                        }
                        else
                        {
                            ImportInfo.TotalRecordsUpdated++;
                            ImportInfo.RecordsUpdated[form]++;
                        }
                    }
                }

                if (!found && Append) // no match, this is a new record that must be inserted
                {
                    CreateNewBlankRow(form, fieldData.RecordGUID, fieldData.KeyValues);
                    ImportInfo.TotalRecordsAppended++;
                    ImportInfo.RecordsAppended[form]++;
                }
            }

            System.Threading.Thread.Sleep(2000); // give time for DB to update

            destinationKeyTable.Clear();
            selectQuery = destinationDb.CreateQuery("SELECT " + wb.ToString() + " " + form.FromViewSQL);
            using (IDataReader keyTableReader = destinationDb.ExecuteReader(selectQuery))
            {
                while (keyTableReader.Read())
                {
                    string guid = keyTableReader["GlobalRecordId"].ToString();
                    Dictionary<Field, object> keys = new Dictionary<Field, object>();

                    foreach (Field field in KeyFields)
                    {
                        keys.Add(field, keyTableReader[field.Name]);
                    }

                    destinationKeyTable.Rows.Add(guid, true, keys);
                }
            }

            //Parallel.ForEach(records, rec =>

            // TODO: Make this faster (note that Parallel foreach seems to make it worse)
            foreach(PackageFieldData rec in records)
                {
                    bool found = false;
                    string targetGuid = String.Empty;
                    bool shouldUpdate = true;

                    foreach (DataRow row in destinationKeyTable.Rows)
                    {
                        Dictionary<Field, object> keyDictionary = row["KeyDictionary"] as Dictionary<Field, object>;

                        if (AreKeyFieldDictionariesEqual(keyDictionary, rec.KeyValues))
                        {
                            found = true;
                            targetGuid = row["GlobalRecordId"].ToString();
                            shouldUpdate = (bool)row["Update"];
                            break;
                        }
                    }

                    if (shouldUpdate && found && !String.IsNullOrEmpty(targetGuid) && rec.FieldValue != null && !String.IsNullOrEmpty(rec.FieldValue.ToString()))
                    {
                        Query updateQuery = destinationDb.CreateQuery("UPDATE " + rec.Page.TableName + " SET " +
                        "[" + rec.FieldName + "] = @" + rec.FieldName + " WHERE [GlobalRecordId] = @GlobalRecordId");

                        QueryParameter fieldParam = GetQueryParameterForField(rec, form, rec.Page);

                        if (fieldParam != null)
                        {
                            updateQuery.Parameters.Add(fieldParam);
                            updateQuery.Parameters.Add(new QueryParameter("@GlobalRecordId", DbType.String, targetGuid));
                            int rowsAffected = destinationDb.ExecuteNonQuery(updateQuery);

                            if (rowsAffected == 0)
                            {
                                throw new ApplicationException("No records affected.");
                            }
                            else if (rowsAffected > 1)
                            {
                                throw new ApplicationException("Too many records affected.");
                            }
                        }
                    }
                }
            //);
        }

19 Source : TableToFormMetadataConverter.cs
with Apache License 2.0
from Epi-Info

private void SetFieldProperties(Field field, ColumnConversionInfo cci) 
        {
            if (cci.Prompt == null)
            {
                cci.Prompt = cci.DestinationColumnName;
            }
            switch (field.FieldType)
            {
                case MetaFieldType.Checkbox:
                    CheckBoxField checkboxField = (CheckBoxField)field;
                    checkboxField.TabIndex = cci.TabIndex;
                    checkboxField.IsReadOnly = cci.IsReadOnly;
                    checkboxField.IsRequired = cci.IsRequired;
                    checkboxField.ShouldRepeatLast = cci.IsRepeatLast;
                    break;
                case MetaFieldType.YesNo:
                    YesNoField yesNoField = (YesNoField)field;
                    yesNoField.TabIndex = cci.TabIndex;
                    yesNoField.IsReadOnly = cci.IsReadOnly;
                    yesNoField.IsRequired = cci.IsRequired;
                    yesNoField.ShouldRepeatLast = cci.IsRepeatLast;
                    break;
                case MetaFieldType.Text:
                    SingleLineTextField textField = (SingleLineTextField)field;
                    textField.TabIndex = cci.TabIndex;
                    textField.IsReadOnly = cci.IsReadOnly;
                    textField.IsRequired = cci.IsRequired;
                    textField.ShouldRepeatLast = cci.IsRepeatLast;
                    if (cci.UpperBound is int)
                    {
                        textField.MaxLength = (int)cci.UpperBound;
                    }
                    break;
                case MetaFieldType.Multiline:
                    MultilineTextField multilineTextField = (MultilineTextField)field;
                    multilineTextField.TabIndex = cci.TabIndex;
                    multilineTextField.IsReadOnly = cci.IsReadOnly;
                    multilineTextField.IsRequired = cci.IsRequired;
                    multilineTextField.ShouldRepeatLast = cci.IsRepeatLast;
                    break;
                case MetaFieldType.Date:
                    DateField dateField = (DateField)field;
                    dateField.TabIndex = cci.TabIndex;
                    dateField.IsReadOnly = cci.IsReadOnly;
                    dateField.IsRequired = cci.IsRequired;
                    dateField.ShouldRepeatLast = cci.IsRepeatLast;
                    break;
                case MetaFieldType.DateTime:
                    DateTimeField dateTimeField = (DateTimeField)field;
                    dateTimeField.TabIndex = cci.TabIndex;
                    dateTimeField.IsReadOnly = cci.IsReadOnly;
                    dateTimeField.IsRequired = cci.IsRequired;
                    dateTimeField.ShouldRepeatLast = cci.IsRepeatLast;
                    break;
                case MetaFieldType.Time:
                    TimeField timeField = (TimeField)field;
                    timeField.TabIndex = cci.TabIndex;
                    timeField.IsReadOnly = cci.IsReadOnly;
                    timeField.IsRequired = cci.IsRequired;
                    timeField.ShouldRepeatLast = cci.IsRepeatLast;
                    break;
                case MetaFieldType.Number:
                    NumberField numberField = (NumberField)field;
                    numberField.TabIndex = cci.TabIndex;
                    numberField.IsReadOnly = cci.IsReadOnly;
                    numberField.IsRequired = cci.IsRequired;
                    numberField.ShouldRepeatLast = cci.IsRepeatLast;
                    break;
                case MetaFieldType.LegalValues:
                    DDLFieldOfLegalValues legalValuesField = (DDLFieldOfLegalValues)field;
                    legalValuesField.TabIndex = cci.TabIndex;
                    legalValuesField.IsReadOnly = cci.IsReadOnly;
                    legalValuesField.IsRequired = cci.IsRequired;
                    legalValuesField.ShouldRepeatLast = cci.IsRepeatLast;

                    if (string.IsNullOrEmpty(cci.ListSourceTableName))
                    {
                        DataTable dt = new DataTable(cci.SourceColumnName);
                        dt.Columns.Add(new DataColumn(cci.SourceColumnName, typeof(string)));
                        // table is blank, so replacedume user wants to use a SELECT DISTINCT as the value source
                        Query selectDistinctQuery = sourceDriver.CreateQuery("SELECT DISTINCT [" + cci.SourceColumnName + "] FROM [" + tableName + "]");
                        IDataReader distinctReader = sourceDriver.ExecuteReader(selectDistinctQuery);
                        while (distinctReader.Read())
                        {
                            dt.Rows.Add(distinctReader[0].ToString());
                        }

                        cci.ListSourceTable = dt;
                        cci.ListSourceTableName = cci.SourceColumnName;
                        cci.ListSourceTextColumnName = cci.SourceColumnName;

                        IDbDriver db = project.CollectedData.GetDatabase();
                        if (!db.TableExists(cci.ListSourceTableName))
                        {
                            project.CreateCodeTable(cci.ListSourceTableName, cci.ListSourceTextColumnName);
                            project.SaveCodeTableData(cci.ListSourceTable, cci.ListSourceTableName, cci.ListSourceTextColumnName);
                        }

                        legalValuesField.SourceTableName = cci.ListSourceTableName;
                        legalValuesField.TextColumnName = cci.ListSourceTextColumnName;
                        legalValuesField.CodeColumnName = cci.ListSourceTextColumnName;
                    }
                    else
                    {
                        IDbDriver db = project.CollectedData.GetDatabase();
                        if (!db.TableExists(cci.ListSourceTableName))
                        {
                            project.CreateCodeTable(cci.ListSourceTableName, cci.ListSourceTextColumnName);
                            string[] columns = new string[1];
                            columns[0] = cci.ListSourceTextColumnName;
                            project.InsertCodeTableData(cci.ListSourceTable, cci.ListSourceTableName, columns);
                        }
                        legalValuesField.SourceTableName = cci.ListSourceTableName;
                        legalValuesField.TextColumnName = cci.ListSourceTextColumnName;
                        legalValuesField.CodeColumnName = cci.ListSourceTextColumnName;
                    }
                    break;
                default:
                    throw new ApplicationException("Invalid field type");
                    //break;
            }

            double ControlHeightPercentage = 0.0;
            double ControlWidthPercentage = 0.0;

            if (field is FieldWithSeparatePrompt)
            {
                FieldWithSeparatePrompt fieldWithPrompt;
                fieldWithPrompt = (FieldWithSeparatePrompt)field;
                fieldWithPrompt.PromptText = cci.Prompt;
                fieldWithPrompt.PromptFont = cci.PromptFont;
                fieldWithPrompt.ControlFont = cci.ControlFont;
                fieldWithPrompt.PromptLeftPositionPercentage = cci.ControlLeftPosition / 100;
                fieldWithPrompt.PromptTopPositionPercentage = cci.ControlTopPosition / 100;
                fieldWithPrompt.Name = cci.DestinationColumnName;
                fieldWithPrompt.ControlHeightPercentage = ControlHeightPercentage / 100;
                fieldWithPrompt.ControlWidthPercentage = ControlWidthPercentage / 100;
                fieldWithPrompt.ControlTopPositionPercentage = cci.ControlTopPosition / 100;
                fieldWithPrompt.ControlLeftPositionPercentage = (cci.ControlLeftPosition / 100) + 0.090702947845805;

                fieldWithPrompt.UpdatePromptPosition();
                fieldWithPrompt.UpdateControlPosition();
            }
            else
            {
                FieldWithoutSeparatePrompt fieldWithoutPrompt;
                fieldWithoutPrompt = (FieldWithoutSeparatePrompt)field;
                fieldWithoutPrompt.PromptText = cci.Prompt;
                fieldWithoutPrompt.PromptFont = cci.PromptFont;
                fieldWithoutPrompt.Name = cci.DestinationColumnName;

                fieldWithoutPrompt.ControlHeightPercentage = ControlHeightPercentage / 100;
                fieldWithoutPrompt.ControlWidthPercentage = ControlWidthPercentage / 100;
                fieldWithoutPrompt.ControlTopPositionPercentage = cci.ControlTopPosition / 100;
                fieldWithoutPrompt.ControlLeftPositionPercentage = (cci.ControlLeftPosition / 100) + 0.090702947845805;

                fieldWithoutPrompt.UpdateControlPosition();
            }
        }

19 Source : GuiMediator.Event.Handlers.cs
with Apache License 2.0
from Epi-Info

private void UpdateRecStatus(View view, bool isDelete, string globalRecordId)
        {
            Epi.Data.Services.CollectedDataProvider collectedData = this.EnterCheckCodeEngine.Project.CollectedData;

            Epi.Data.Query updateQuery = collectedData.CreateQuery("update " + view.TableName + " set [RecStatus] = @RecStatus where [GlobalRecordId] = @GlobalRecordId");
            updateQuery.Parameters.Add(new Epi.Data.QueryParameter("@RecStatus", DbType.Int32, isDelete ? 0 : 1));
            updateQuery.Parameters.Add(new Epi.Data.QueryParameter("@GlobalRecordId", DbType.String, globalRecordId));
            collectedData.ExecuteNonQuery(updateQuery);
            
            // < GRID TABLES >

            foreach (GridField gridField in view.Fields.GridFields)
            {
                UpdateRecStatus(gridField, isDelete, globalRecordId);
            }

            // < CHILD VIEW >

            List<Epi.Fields.RelatedViewField> RelatedViewList = FindRelatedFields(view);
            
            foreach (Epi.Fields.RelatedViewField field in RelatedViewList)
            {
                View relatedView = this.EnterCheckCodeEngine.Project.GetViewById(field.RelatedViewID);

                if (collectedData.TableExists(relatedView.Name))
                {
                    Epi.Data.Query childRecordQuery = collectedData.CreateQuery("Select GlobalRecordId From " + relatedView.TableName + " Where [FKEY] = @FKEY");
                    childRecordQuery.Parameters.Add(new Epi.Data.QueryParameter("@FKEY", DbType.String, globalRecordId));
                    IDataReader dataReader = collectedData.ExecuteReader(childRecordQuery);

                    while(dataReader.Read())
                    {
                        string readerGlobalRecordId = dataReader["GlobalRecordId"].ToString();
                        UpdateRecStatus(relatedView, isDelete, readerGlobalRecordId);
                    }
                }
            }
        }

19 Source : GuiMediator.Events.Canvas.cs
with Apache License 2.0
from Epi-Info

private void MarkRelatedRecoredsAsDeleted(Epi.Data.Services.CollectedDataProvider OutputDriver, View pView, List<int> pIDList)
        {

            if(pIDList.Count < 1)
            {
                return;
            }

            Dictionary<string, bool> VisitedViews = new Dictionary<string, bool>(StringComparer.OrdinalIgnoreCase);
            string SQL = null;
            StringBuilder InSQL = new StringBuilder();
            InSQL.Append("  (");
            foreach (int ID in pIDList)
            {
                pView.LoadRecord(ID);
                pView.RecStatusField.CurrentRecordValue = 0;
                pView.SaveRecord(ID);
                InSQL.Append("'");
                InSQL.Append(pView.CurrentGlobalRecordId);
                InSQL.Append("',");
            }
            InSQL.Length = InSQL.Length - 1;
            InSQL.Append(")");

            foreach (Field field in pView.Fields)
            {
                if (field is RelatedViewField)
                {
                    RelatedViewField rvf = field as RelatedViewField;
                    if (!VisitedViews.ContainsKey(rvf.ChildView.Name))
                    {
                        SQL = "Select UniqueKey From [" + rvf.ChildView.TableName + "] Where FKey In " + InSQL.ToString();
                        IDataReader reader = OutputDriver.ExecuteReader(OutputDriver.CreateQuery(SQL)); 
                        List<int> NewIdList = new List<int>();
                        while (reader.Read())
                        {
                            if( reader["UniqueKey"] != DBNull.Value)
                            {
                                NewIdList.Add((int)reader["UniqueKey"]);
                            }
                        }
                        VisitedViews.Add(rvf.ChildView.Name, true);
                        MarkRelatedRecoredsAsDeleted(OutputDriver, rvf.ChildView, NewIdList);
                    }
                }
                else if (field is Epi.Fields.GridField)
                {

                    Epi.Fields.GridField gf = field as Epi.Fields.GridField;

                    SQL = "Update  [" + gf.TableName + "] Set RecStatus = 0 Where FKey In " + InSQL.ToString();
                    OutputDriver.ExecuteNonQuery(OutputDriver.CreateQuery(SQL));

                }
            }
        }

19 Source : GuiMediator.Events.Canvas.cs
with Apache License 2.0
from Epi-Info

private void UnMarkRelatedRecoredsAsDeleted(Epi.Data.Services.CollectedDataProvider OutputDriver, View pView, List<int> pIDList)
        {
            if (pIDList.Count < 1)
            {
                return;
            }

            Dictionary<string, bool> VisitedViews = new Dictionary<string, bool>(StringComparer.OrdinalIgnoreCase);
            string SQL = null;
            StringBuilder InSQL = new StringBuilder();
            InSQL.Append(" Where FKey In (");
            foreach (int ID in pIDList)
            {
                pView.LoadRecord(ID);
                pView.RecStatusField.CurrentRecordValue = 1;
                pView.SaveRecord(ID);
                InSQL.Append("'");
                InSQL.Append(pView.CurrentGlobalRecordId);
                InSQL.Append("',");
            }
            InSQL.Length = InSQL.Length - 1;
            InSQL.Append(")");

            foreach (Field field in pView.Fields)
            {
                if (field is RelatedViewField)
                {
                    RelatedViewField rvf = field as RelatedViewField;
                    if (!VisitedViews.ContainsKey(rvf.ChildView.Name))
                    {
                        SQL = "Select UniqueKey From [" + rvf.ChildView.TableName + "] " + InSQL.ToString();
                        IDataReader reader = OutputDriver.ExecuteReader(OutputDriver.CreateQuery(SQL));
                        List<int> NewIdList = new List<int>();
                        while (reader.Read())
                        {
                            if (reader["UniqueKey"] != DBNull.Value)
                            {
                                NewIdList.Add((int)reader["UniqueKey"]);
                            }
                        }
                        VisitedViews.Add(rvf.ChildView.Name, true);
                        UnMarkRelatedRecoredsAsDeleted(OutputDriver, rvf.ChildView, NewIdList);
                    }
                    else if (field is Epi.Fields.GridField)
                    {

                        Epi.Fields.GridField gf = field as Epi.Fields.GridField;

                        SQL = "Update  [" + gf.TableName + "] Set RecStatus = 1 Where FKey In " + InSQL.ToString();
                        OutputDriver.ExecuteNonQuery(OutputDriver.CreateQuery(SQL));

                    }
                }
            }
        }

19 Source : SqlCeBulkCopyDataReaderAdapter.cs
with MIT License
from ErikEJ

public bool Read()
        {
            return _reader.Read();
        }

19 Source : Database.cs
with GNU General Public License v3.0
from faib920

public virtual IEnumerable<T> ExecuteEnumerable<T>(IQueryCommand queryCommand, IDataSegment segment = null, ParameterCollection parameters = null, IDataRowMapper<T> rowMapper = null)
        {
            Guard.ArgumentNull(queryCommand, "queryCommand");

            rowMapper = rowMapper ?? RowMapperFactory.CreateRowMapper<T>();
            rowMapper.RecordWrapper = Provider.GetService<IRecordWrapper>();
            using (var reader = ExecuteReader(queryCommand, segment, parameters))
            {
                while (reader.Read())
                {
                    yield return rowMapper.Map(reader);
                }
            }
        }

19 Source : Database.cs
with GNU General Public License v3.0
from faib920

public virtual IEnumerable<object> ExecuteEnumerable(IQueryCommand queryCommand, IDataSegment segment = null, ParameterCollection parameters = null)
        {
            Guard.ArgumentNull(queryCommand, "queryCommand");

            using (var reader = ExecuteReader(queryCommand, segment, parameters))
            {
                var wrapper = Provider.GetService<IRecordWrapper>();
#if !N35 && DYNAMIC
                TypeDescriptorUtility.AddDefaultDynamicProvider();

                while (reader.Read())
                {
                    var expando = new ExpandoObject();
                    var dictionary = (IDictionary<string, object>)expando;

                    for (var i = 0; i < reader.FieldCount; i++)
                    {
                        dictionary.Add(wrapper.GetFieldName(reader, i), RecordWrapHelper.GetValue(wrapper, reader, i));
                    }                        
                    yield return expando;
                }
#else
                var builder = new DataReaderTypeBuilder(reader);
                var elementType = builder.CreateType();
                while (reader.Read())
                {
                    yield return elementType.New(reader, wrapper);
                }
#endif
            }
        }

19 Source : Database.cs
with GNU General Public License v3.0
from faib920

public bool MoveNext()
            {
                return reader.Read();
            }

19 Source : TotalRecordEvaluator.cs
with GNU Lesser General Public License v3.0
from faib920

private int GetRecordCount(IDataReader reader, IRecordWrapper wrapper)
        {
            var count = 0;
            if (reader.Read())
            {
                switch (reader.GetFieldType(0).GetDbType())
                {
                    case DbType.Decimal:
                        count = (int)wrapper.GetDecimal(reader, 0);
                        break;
                    case DbType.Int32:
                        count = wrapper.GetInt32(reader, 0);
                        break;
                    case DbType.Int64:
                        count = (int)wrapper.GetInt64(reader, 0);
                        break;
                }
            }
            return count;
        }

19 Source : DbExt.cs
with GNU General Public License v3.0
from Fe7n

public bool Read()
		{
			if (Reader == null)
				return false;
			return Reader.Read();
		}

19 Source : Maper.cs
with GNU General Public License v3.0
from fiado07

public IEnumerable<TMapTo> MapToList<TMapTo>(IDataReader reader, Dictionary<string, string> dbtypes) where TMapTo : new()
        {


            TMapTo newObject;
            List <TMapTo> newObjectList = new List<TMapTo>();

            while (reader.Read())
            {

                newObject = new TMapTo();

                Array.ForEach(typeof(TMapTo).GetProperties(), (propertInfo) =>
                                                                            {

                                                                                SetMapedObject<TMapTo>(newObject, reader, dbtypes, propertInfo);

                                                                            });
               
                yield return newObject;

            }

       
        }

19 Source : DbExecuteQuery.cs
with GNU General Public License v3.0
from fiado07

public bool any(SqlAndParameters sqlParameter)
        {
            bool result = false;
            IDataReader readerResult = null;

            try
            {
                isConnectionStringValid();

                using (var sqlComand = DbConnection.DbConnectionBase.CreateCommand())
                {
                    if (DbConnection?.DbTransaction != null)
                        sqlComand.Transaction = DbConnection.DbTransaction;

                    if (sqlComand.Parameters != null)
                        sqlComand.SetParameters(sqlParameter);

                    // set sql
                    sqlComand.CommandText = sqlParameter.Sql;

                    // set command type
                    sqlComand.CommandType = sqlParameter.isStoredProcedure ? CommandType.StoredProcedure : CommandType.Text;

                    // get and set values
                    readerResult = sqlComand.ExecuteReader();

                    while (readerResult.Read())
                    {
                        if (readerResult[0] != null) result = true;
                    }
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                if (readerResult != null && !readerResult.IsClosed) readerResult.Close();

                if (DbConnection.canClose) DbConnection.DbConnectionBase.Close();
            }

            return result;
        }

19 Source : Maper.cs
with GNU General Public License v3.0
from fiado07

public TMapTo Map<TMapTo>(IDataReader reader, Dictionary<string, string> dbtypes) where TMapTo : new()
        {

            TMapTo newObject = new TMapTo();


            while (reader.Read())
            {


                Array.ForEach(typeof(TMapTo).GetProperties(), (propertInfo) =>
                                                                            {

                                                                                SetMapedObject<TMapTo>(newObject, reader, dbtypes, propertInfo);

                                                                            });
            }

            return newObject;


        }

19 Source : SheetLoadUtil.cs
with MIT License
from focus-creative-games

public static bool TryParseMeta(IExcelDataReader reader, out bool orientRow, out string tableName)
        {
            if (!reader.Read() || reader.FieldCount == 0)
            {
                orientRow = true;
                tableName = "";
                return false;
            }
            string metaStr = reader.GetString(0)?.Trim();
            return TryParseMeta(metaStr, out orientRow, out tableName);
        }

19 Source : SheetLoadUtil.cs
with MIT License
from focus-creative-games

private static List<List<Cell>> ParseRawSheetContent(IExcelDataReader reader, bool orientRow, bool headerOnly)
        {
            // TODO 优化性能
            // 几个思路
            // 1. 没有 replacedle 的列不加载
            // 2. 空行优先跳过
            // 3. 跳过null或者empty的单元格
            var originRows = new List<List<Cell>>();
            int rowIndex = 0;
            do
            {
                var row = new List<Cell>();
                for (int i = 0, n = reader.FieldCount; i < n; i++)
                {
                    row.Add(new Cell(rowIndex, i, reader.GetValue(i)));
                }
                originRows.Add(row);
                if (orientRow && headerOnly && !IsHeaderRow(row))
                {
                    break;
                }
                ++rowIndex;
            } while (reader.Read());

            List<List<Cell>> finalRows;

            if (orientRow)
            {
                finalRows = originRows;
            }
            else
            {
                // 转置这个行列
                int maxColumn = originRows.Select(r => r.Count).Max();
                finalRows = new List<List<Cell>>();
                for (int i = 0; i < maxColumn; i++)
                {
                    var row = new List<Cell>();
                    for (int j = 0; j < originRows.Count; j++)
                    {
                        row.Add(i < originRows[j].Count ? originRows[j][i] : new Cell(j + 1, i, null));
                    }
                    finalRows.Add(row);
                }
            }
            return finalRows;
        }

19 Source : DataHelper.cs
with GNU Lesser General Public License v3.0
from GavinYellow

public static string ReaderToCsv(IDataReader reader)
        {
            StringBuilder sb = new StringBuilder();
            var colcount = reader.FieldCount;
            while (reader.Read())
            {
                for (int i = 0; i < colcount; i++)
                {
                    if (i != 0) sb.Append(",");
                    var txt = reader[i] == null ? "" : reader[i].ToString();
                    if (txt.Contains(","))
                    {
                        sb.Append("\"" + txt.Replace("\"", "\"\"") + "\"");
                    }
                    else sb.Append(txt);
                }
                sb.AppendLine();
            }
            return sb.ToString();
        }

19 Source : DataHelper.cs
with GNU Lesser General Public License v3.0
from GavinYellow

public static string ReaderToCsv(IDataReader reader)
        {  
            StringBuilder sb = new StringBuilder();
            var colcount = reader.FieldCount;
            while (reader.Read())
            {
                for (int i = 0; i < colcount; i++)
                {
                    if (i != 0) sb.Append(",");
                    var txt = reader[i] == null ? "" : reader[i].ToString();
                    if (txt.Contains(","))
                    {
                        sb.Append("\"" + txt.Replace("\"", "\"\"") + "\"");
                    }
                    else sb.Append(txt);
                }
                sb.AppendLine();
            }
            return sb.ToString();
        }

19 Source : DataAdapter.cs
with MIT License
from GrapeCity

internal bool FillTable (DataTable dataTable, IDataReader dataReader, int startRecord, int maxRecords, ref int counter)
		{
			if (dataReader.FieldCount == 0)
				return false;

			int counterStart = counter;

			int[] mapping = BuildSchema (dataReader, dataTable, SchemaType.Mapped);
			
			int [] sortedMapping = new int [mapping.Length];
			int length = sortedMapping.Length;
			for (int i = 0; i < sortedMapping.Length; i++) {
				if (mapping [i] >= 0)
					sortedMapping [mapping [i]] = i;
				else
					sortedMapping [--length] = i;
			}

			for (int i = 0; i < startRecord; i++) {
				dataReader.Read ();
			}

			dataTable.BeginLoadData ();
			while (dataReader.Read () && (maxRecords == 0 || (counter - counterStart) < maxRecords)) {
				try {
					dataTable.LoadDataRow (dataReader, sortedMapping, length, AcceptChangesDuringFill);
					counter++;
				}
				catch (Exception e) {
					object[] readerArray = new object [dataReader.FieldCount];
					object[] tableArray = new object [mapping.Length];
					// we get the values from the datareader
					dataReader.GetValues (readerArray);
					// copy from datareader columns to table columns according to given mapping
					for (int i = 0; i < mapping.Length; i++) {
						if (mapping [i] >= 0) {
							tableArray [i] = readerArray [mapping [i]];
						}
					}
					FillErrorEventArgs args = CreateFillErrorEvent (dataTable, tableArray, e);
					OnFillErrorInternal (args);

					// if args.Continue is not set to true or if a handler is not set, rethrow the error..
					if(!args.Continue)
						throw e;
				}
			}
			dataTable.EndLoadData ();
			return true;
		}

19 Source : DbDataAdapter.cs
with MIT License
from GrapeCity

protected virtual int Update (DataRow[] dataRows, DataTableMapping tableMapping) 
		{
			int updateCount = 0;
			foreach (DataRow row in dataRows) {
				StatementType statementType = StatementType.Update;
				IDbCommand command = null;
				string commandName = String.Empty;

				switch (row.RowState) {
				case DataRowState.Added:
					statementType = StatementType.Insert;
					command = ((IDbDataAdapter) this).InsertCommand;
					commandName = "Insert";
					break;
				case DataRowState.Deleted:
					statementType = StatementType.Delete;
					command = ((IDbDataAdapter) this).DeleteCommand;
					commandName = "Delete";
					break;
				case DataRowState.Modified:
					statementType = StatementType.Update;
					command = ((IDbDataAdapter) this).UpdateCommand;
					commandName = "Update";
					break;
				case DataRowState.Unchanged:
				case DataRowState.Detached:
					continue;
				}

				RowUpdatingEventArgs argsUpdating = CreateRowUpdatingEvent (row, command, statementType, tableMapping);
				row.RowError = null;
				OnRowUpdating (argsUpdating);
				switch (argsUpdating.Status) {
				case UpdateStatus.Continue :
					//continue in update operation
					break;
				case UpdateStatus.ErrorsOccurred :
					if (argsUpdating.Errors == null) {
						argsUpdating.Errors = ExceptionHelper.RowUpdatedError();
					}
					row.RowError += argsUpdating.Errors.Message;
					if (!ContinueUpdateOnError) {
						throw argsUpdating.Errors;
					}
					continue;
				case UpdateStatus.SkipAllRemainingRows :
					return updateCount;
				case UpdateStatus.SkipCurrentRow :
					updateCount++;
					continue;
				default :
					throw ExceptionHelper.InvalidUpdateStatus (argsUpdating.Status);
				}
				command = argsUpdating.Command;
				try {
					if (command != null) {
						DataColumnMappingCollection columnMappings = tableMapping.ColumnMappings;
						IDataParameter nullCheckParam = null;
						foreach (IDataParameter parameter in command.Parameters) {
							if ((parameter.Direction & ParameterDirection.Input) != 0) {
								string dsColumnName = parameter.SourceColumn;
								if (columnMappings.Contains(parameter.SourceColumn))
									dsColumnName = columnMappings [parameter.SourceColumn].DataSetColumn;
								if (dsColumnName == null || dsColumnName.Length <= 0) {
									nullCheckParam = parameter;
									continue;
								}

								DataRowVersion rowVersion = parameter.SourceVersion;
								// Parameter version is ignored for non-update commands
								if (statementType == StatementType.Delete) 
									rowVersion = DataRowVersion.Original;

								parameter.Value = row [dsColumnName, rowVersion];
								if (nullCheckParam != null && (parameter.Value != null
									&& parameter.Value != DBNull.Value)) {
									nullCheckParam.Value = 0;
									nullCheckParam = null;
								}
							}
						}
					}
				}
				catch (Exception e) {
					argsUpdating.Errors = e;
					argsUpdating.Status = UpdateStatus.ErrorsOccurred;
				}

				
				IDataReader reader = null;
				try {								
					if (command == null) {
						throw ExceptionHelper.UpdateRequiresCommand (commandName);
					}				
				
					CommandBehavior commandBehavior = CommandBehavior.Default;
					if (command.Connection.State == ConnectionState.Closed) {
						command.Connection.Open ();
						commandBehavior |= CommandBehavior.CloseConnection;
					}
				
					// use ExecuteReader because we want to use the commandbehavior parameter.
					// so the connection will be closed if needed.
					reader = command.ExecuteReader (commandBehavior);

					// update the current row, if the update command returns any resultset
					// ignore other than the first record.
					DataColumnMappingCollection columnMappings = tableMapping.ColumnMappings;

					if (command.UpdatedRowSource == UpdateRowSource.Both ||
					    command.UpdatedRowSource == UpdateRowSource.FirstReturnedRecord) {
						if (reader.Read ()){
							DataTable retSchema = reader.GetSchemaTable ();
							foreach (DataRow dr in retSchema.Rows) {
								string columnName = dr ["ColumnName"].ToString ();
								string dstColumnName = columnName;
								if (columnMappings != null &&
								    columnMappings.Contains(columnName))
									dstColumnName = columnMappings [dstColumnName].DataSetColumn;
								DataColumn dstColumn = row.Table.Columns [dstColumnName];
								if (dstColumn == null
#if NOT_PFX
								    || (dstColumn.Expression != null
									&& dstColumn.Expression.Length > 0)
#endif
                                    )
									continue;
								// info from : http://www.error-bank.com/microsoft.public.dotnet.framework.windowsforms.databinding/
								// [email protected]_Thread.aspx
								// disable readonly for non-expression columns.
								bool readOnlyState = dstColumn.ReadOnly;
								dstColumn.ReadOnly = false;
								try {
									row [dstColumnName] = reader [columnName];
								} finally {
									dstColumn.ReadOnly = readOnlyState;
								}                                    
							}
						}
					}
					reader.Close ();

					int tmp = reader.RecordsAffected; // records affected is valid only after closing reader
					// if the execute does not effect any rows we throw an exception.
					if (tmp == 0)
						throw new DBConcurrencyException("Concurrency violation: the " + 
                                                                                 commandName +"Command affected 0 records.");
					updateCount += tmp;
                                        
					if (command.UpdatedRowSource == UpdateRowSource.Both ||
					    command.UpdatedRowSource == UpdateRowSource.OutputParameters) {
						// Update output parameters to row values
						foreach (IDataParameter parameter in command.Parameters) {
							if (parameter.Direction != ParameterDirection.InputOutput
							    && parameter.Direction != ParameterDirection.Output
							    && parameter.Direction != ParameterDirection.ReturnValue)
								continue;

							string dsColumnName = parameter.SourceColumn;
							if (columnMappings != null &&
							    columnMappings.Contains(parameter.SourceColumn))
								dsColumnName = columnMappings [parameter.SourceColumn].DataSetColumn;
							DataColumn dstColumn = row.Table.Columns [dsColumnName];
							if (dstColumn == null
#if NOT_PFX
							    || (dstColumn.Expression != null 
								&& dstColumn.Expression.Length > 0)
#endif
                                )
								continue;
							bool readOnlyState = dstColumn.ReadOnly;
							dstColumn.ReadOnly  = false;
							try {
								row [dsColumnName] = parameter.Value;
							} finally {
								dstColumn.ReadOnly = readOnlyState;
							}
                                    
						}
					}
                    
					RowUpdatedEventArgs updatedArgs = CreateRowUpdatedEvent (row, command, statementType, tableMapping);
					OnRowUpdated (updatedArgs);
					switch (updatedArgs.Status) {
					case UpdateStatus.Continue:
						break;
					case UpdateStatus.ErrorsOccurred:
						if (updatedArgs.Errors == null) {
							updatedArgs.Errors = ExceptionHelper.RowUpdatedError();
						}
						row.RowError += updatedArgs.Errors.Message;
						if (!ContinueUpdateOnError) {
							throw updatedArgs.Errors;
						}
						break;
					case UpdateStatus.SkipCurrentRow:
						continue;
					case UpdateStatus.SkipAllRemainingRows:
						return updateCount;
					}
#if NET_2_0
					if (!AcceptChangesDuringUpdate)
						continue;
#endif
					row.AcceptChanges ();
				} catch(Exception e) {
					row.RowError = e.Message;
					if (!ContinueUpdateOnError) {
						throw e;
					}
				} finally {
					if (reader != null && ! reader.IsClosed) {
						reader.Close ();
					}
				}	
			}		
			return updateCount;
		}

19 Source : DbEnumerator.cs
with MIT License
from GrapeCity

public bool MoveNext ()
		{
			if (reader.Read ()) 
				return true;
			if (closeReader)
				reader.Close ();
			return false;
		}

19 Source : NodeSelectionScreen.xaml.cs
with MIT License
from GridProtectionAlliance

private IList<NodeInfo> GetNodes(IDbConnection connection)
        {
            List<NodeInfo> nodes = new List<NodeInfo>();

            if (connection != null)
            {
                try
                {
                    IDbCommand command;
                    IDataReader reader;

                    connection.Open();
                    command = connection.CreateCommand();
                    command.CommandText = "SELECT ID, Name, CompanyName AS Company, Description FROM NodeDetail WHERE Enabled <> 0";

                    using (reader = command.ExecuteReader())
                    {
                        while (reader.Read())
                        {
                            Guid nodeId;

                            if (Guid.TryParse(reader["ID"].ToNonNullString(), out nodeId))
                            {
                                nodes.Add(new NodeInfo()
                                {
                                    Name = reader["Name"].ToNonNullString(),
                                    Company = reader["Company"].ToNonNullString(),
                                    Description = reader["Description"].ToNonNullString(),
                                    Id = nodeId
                                });
                            }
                        }
                    }
                }
                catch
                {
                    // Ignore exceptions since failure to retrieve
                    // the node list should not interrupt the setup.
                }
                finally
                {
                    connection.Dispose();
                }
            }

            return nodes;
        }

19 Source : MysqlStorageImpl.cs
with BSD 3-Clause "New" or "Revised" License
from HalcyonGrid

public List<InventoryFolderBase> getUserRootFolders(UUID user, UUID root)
        {
            try
            {
                using (ISimpleDB conn = _connFactory.GetConnection())
                {

                    string query = "SELECT * FROM inventoryfolders WHERE parentFolderID = ?root AND agentID = ?uuid";
                    Dictionary<string, object> parms = new Dictionary<string, object>();
                    parms.Add("?uuid", user.ToString());
                    parms.Add("?root", root.ToString());

                    using (IDataReader reader = conn.QueryAndUseReader(query, parms))
                    {
                        List<InventoryFolderBase> items = new List<InventoryFolderBase>();
                        while (reader.Read())
                            items.Add(readInventoryFolder(reader));

                        return items;
                    }
                }
            }
            catch (Exception e)
            {
                m_log.Error(e.ToString());
                return null;
            }
        }

See More Examples