Exemple #1
0
        public MainForm(IApplication app)
        {
            InitializeComponent();

            application = app;
            protocol = application.GetProtocol(ProtocolVersion.x100);

            inserter = new Inserter(insert);
            status = new StatusHandle();

            incer = new Incer(IncP);
            initer = new Initer(InitProgressBar);
        }
Exemple #2
0
        public static async Task <Document> RefactorAsync(
            Document document,
            PropertyDeclarationSyntax propertyDeclaration,
            bool prefixIdentifierWithUnderscore = true,
            CancellationToken cancellationToken = default(CancellationToken))
        {
            string fieldName = Identifier.ToCamelCase(
                propertyDeclaration.Identifier.ValueText,
                prefixWithUnderscore: prefixIdentifierWithUnderscore);

            SemanticModel semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false);

            fieldName = Identifier.EnsureUniqueMemberName(fieldName, propertyDeclaration.SpanStart, semanticModel, cancellationToken);

            FieldDeclarationSyntax fieldDeclaration = CreateBackingField(propertyDeclaration, fieldName)
                                                      .WithFormatterAnnotation();

            PropertyDeclarationSyntax newPropertyDeclaration = ExpandPropertyAndAddBackingField(propertyDeclaration, fieldName);

            newPropertyDeclaration = ExpandPropertyRefactoring.ReplaceAbstractWithVirtual(newPropertyDeclaration);

            newPropertyDeclaration = newPropertyDeclaration
                                     .WithTriviaFrom(propertyDeclaration)
                                     .WithFormatterAnnotation();

            var parentMember = (MemberDeclarationSyntax)propertyDeclaration.Parent;
            SyntaxList <MemberDeclarationSyntax> members = parentMember.GetMembers();

            int propertyIndex = members.IndexOf(propertyDeclaration);

            if (IsReadOnlyAutoProperty(propertyDeclaration))
            {
                IPropertySymbol propertySymbol = semanticModel.GetDeclaredSymbol(propertyDeclaration, cancellationToken);

                ImmutableArray <SyntaxNode> oldNodes = await document.FindSymbolNodesAsync(propertySymbol, cancellationToken).ConfigureAwait(false);

                IdentifierNameSyntax newNode = IdentifierName(fieldName);

                MemberDeclarationSyntax newParentMember = parentMember.ReplaceNodes(oldNodes, (f, g) => newNode.WithTriviaFrom(f));

                members = newParentMember.GetMembers();
            }

            SyntaxList <MemberDeclarationSyntax> newMembers = members.ReplaceAt(propertyIndex, newPropertyDeclaration);

            newMembers = Inserter.InsertMember(newMembers, fieldDeclaration);

            return(await document.ReplaceNodeAsync(parentMember, parentMember.SetMembers(newMembers), cancellationToken).ConfigureAwait(false));
        }
Exemple #3
0
        public void Execute()
        {
            //Inserter.StartModelUpdate();

            for (int i = 0; i < Operations.Count; i++)
            {
                Point tileCoords = Operations[i].IndexCoords;
                int   tileId     = Operations[i].TileIdAfter;

                Inserter.SetValue(tileCoords, tileId);
            }

            //Inserter.Model.Update();

            //Inserter.FinishModelUpdate();
        }
Exemple #4
0
        private static void Insert(SQLiteConnection conn, int count, Dictionary <int, string> dict)
        {
            Random r = new Random();

            for (int i = 0; i < count; ++i)
            {
                int      a        = r.Next();
                string   b        = Guid.NewGuid().ToString();
                Inserter inserter = new Inserter("Temp", conn);
                inserter.Set("A", a);
                inserter.Set("B", b, false);
                inserter.Execute();

                dict[a] = b;
            }
        }
Exemple #5
0
        /// <inheritdoc />
        public async Task FillAsync()
        {
            if (Logger.IsEnabled(LogLevel.Information))
            {
                Logger.LogInformation($"Converting DBC file: {typeof(TDBCEntryType).Name} to database table.");
            }

            ParsedDBCFile <TDBCEntryType> dbc = await DbcReader.Parse();

            if (dbc == null)
            {
                throw new InvalidOperationException($"Failed to parse DBC for Type: {typeof(TDBCEntryType).Name}");
            }

            await Inserter.InsertEntriesAsync(dbc.RecordDatabase.Values.ToArray());
        }
Exemple #6
0
        /// <summary>
        /// Used to make sure the *Type tables are updated
        /// </summary>
        /// <param name="conn">The connection to the database</param>
        /// <param name="values">The key/value pair that needs to exist in the DB. If there's a missing entry, or the description
        /// changed, we'll insert or update as appropriate</param>
        /// <param name="table">The table we're going to be updating</param>
        /// <param name="type_column">The name of the type column.</param>
        public static void PopulateTypesTable(this SQLiteConnection conn, Dictionary <int, string> values, string table, string type_column)
        {
            ILog log = LogManager.GetLogger(typeof(Extensions));
            Dictionary <int, string> db_values = new Dictionary <int, string>();

            string select_query = string.Format("SELECT {0}, Description FROM {1};", type_column, table);

            using (SQLiteCommand command = new SQLiteCommand(select_query, conn))
                using (SQLiteDataReader reader = command.ExecuteReader())
                {
                    while (reader.Read())
                    {
                        db_values[reader.GetInt32(0)] = reader.GetString(1);
                    }
                }

            List <int> db_types = new List <int>(db_values.Keys);
            List <int> types    = new List <int>(values.Keys);

            db_types.ForEach(t => types.Remove(t));

            // Whatever's left needs to be added
            foreach (int type in types)
            {
                log.Info($"Inserting {type}=>{values[type]} into {table}");

                Inserter inserter = new Inserter(table, conn);
                inserter.Set(type_column, type);
                inserter.Set("Description", values[type], false);
                inserter.Execute();

                db_values[type] = values[type];
            }

            // Now compare the existing descriptions with the descriptions in values
            foreach (int type in values.Keys)
            {
                if (values[type] != db_values[type])
                {
                    log.Info($"Changing {type}=>{db_values[type]} to {values[type]} in {table}");

                    Updater updater = new Updater(table, $"{type_column} = {type}", conn);
                    updater.Set("Description", values[type], false);
                    updater.Execute();
                }
            }
        }
Exemple #7
0
        public void ProperlyHandleLongs()
        {
            using (FileDeleter fd = new FileDeleter(Extensions.GetTempDBFile()))
            {
                Database db = new Database(new Context(fd.Fi));
                using (SQLiteConnection conn = db.Connection)
                {
                    conn.Open();

                    conn.ExecuteNonQuery("CREATE TABLE Temp(A INTEGER NOT NULL PRIMARY KEY, B INTEGER NOT NULL)");
                    Assert.True(conn.DoesTableExist("Temp"));

                    Dictionary <int, long> dict = new Dictionary <int, long>();
                    Random r     = new Random();
                    int    count = 100;
                    for (int i = 0; i < count; ++i)
                    {
                        int  a = r.Next();
                        long b = r.NextLong();

                        Inserter ins = new Inserter("Temp", conn);
                        ins.Set("A", a);
                        ins.Set("B", b);
                        ins.Execute();

                        dict[a] = b;
                    }

                    foreach (int a in dict.Keys)
                    {
                        string sql = $"SELECT B FROM Temp WHERE A = {a}";
                        using (SQLiteCommand command = new SQLiteCommand(sql, conn))
                            using (SQLiteDataReader reader = command.ExecuteReader())
                            {
                                bool read = reader.Read();
                                Assert.True(read);
                                if (read)
                                {
                                    long b = reader.GetInt64(0);
                                    Assert.Equal(dict[a], b);
                                }
                            }
                    }
                }
            }
        }
Exemple #8
0
        public void ProperlyHandleDates()
        {
            using (FileDeleter fd = new FileDeleter(Extensions.GetTempDBFile()))
            {
                Database db = new Database(new Context(fd.Fi));
                using (SQLiteConnection conn = db.Connection)
                {
                    conn.Open();

                    conn.ExecuteNonQuery("CREATE TABLE Temp(A INTEGER NOT NULL PRIMARY KEY, B TEXT NOT NULL)");
                    Assert.True(conn.DoesTableExist("Temp"));

                    Dictionary <int, DateTimeOffset> dict = new Dictionary <int, DateTimeOffset>();
                    Random r     = new Random();
                    int    count = 100;
                    for (int i = 0; i < count; ++i)
                    {
                        int            a = r.Next();
                        DateTimeOffset b = new DateTimeOffset(2018, r.Next(1, 12), r.Next(1, 28), r.Next(0, 23), r.Next(0, 59), r.Next(0, 59), r.Next(0, 999), TimeSpan.FromHours(r.Next(-12, 12)));

                        Inserter ins = new Inserter("Temp", conn);
                        ins.Set("A", a);
                        ins.Set("B", b);
                        ins.Execute();

                        dict[a] = b;
                    }

                    foreach (int a in dict.Keys)
                    {
                        string sql = $"SELECT B FROM Temp WHERE A = {a}";
                        using (SQLiteCommand command = new SQLiteCommand(sql, conn))
                            using (SQLiteDataReader reader = command.ExecuteReader())
                            {
                                bool read = reader.Read();
                                Assert.True(read);
                                if (read)
                                {
                                    DateTimeOffset b = DateTimeOffset.Parse(reader.GetString(0));
                                    Assert.Equal(dict[a], b);
                                }
                            }
                    }
                }
            }
        }
Exemple #9
0
        public static EventFieldDeclarationSyntax AddStaticModifier(EventFieldDeclarationSyntax eventFieldDeclaration)
        {
            if (eventFieldDeclaration == null)
            {
                throw new ArgumentNullException(nameof(eventFieldDeclaration));
            }

            SyntaxTokenList modifiers = eventFieldDeclaration.Modifiers;

            if (!modifiers.Contains(SyntaxKind.StaticKeyword))
            {
                return(Inserter.InsertModifier(eventFieldDeclaration, SyntaxKind.StaticKeyword));
            }
            else
            {
                return(eventFieldDeclaration);
            }
        }
        private static void VerifyMeasureAndLocalize(
            string inDirPath, string expDirPath,
            DirectoryInfo outDir, string outDirPath)
        {
            var profile = LanguageSupports.GetCoverageModeByClassName("C");

            Inserter.InsertMeasurementCode(outDir, new Collection <FileInfo>(), null, outDir, profile, RecordingMode.TextFile);

            // .cと.hファイルが存在するか
            Assert.That(
                File.Exists(Path.Combine(outDirPath, "covman.c")),
                Is.True);
            Assert.That(
                File.Exists(Path.Combine(outDirPath, "covman.h")),
                Is.True);

            var covinfo  = Path.Combine(outDirPath, OccfNames.CoverageInfo);
            var testinfo = Path.Combine(outDirPath, OccfNames.TestInfo);

            var targets = Directory.EnumerateFiles(
                expDirPath, "*.c",
                SearchOption.AllDirectories)
                          .Concat(
                Directory.EnumerateFiles(
                    expDirPath, OccfNames.BackupSuffix,
                    SearchOption.AllDirectories))
                          .Concat(new[] { covinfo, testinfo });

            foreach (var target in targets)
            {
                AssertEqualFiles(target, expDirPath, inDirPath);
            }

            Compile(outDirPath);
            RunTest(outDirPath);

            var ret = BugLocalizer.Run(
                new[] {
                outDirPath,
                Path.Combine(outDirPath, "testresult.txt")
            });

            Assert.That(ret, Is.True);
        }
        public static Task <Document> RefactorAsync(
            Document document,
            EventFieldDeclarationSyntax eventFieldDeclaration,
            IEventSymbol eventSymbol,
            ITypeSymbol eventArgsSymbol,
            bool supportsCSharp6,
            CancellationToken cancellationToken = default(CancellationToken))
        {
            var containingMember = (MemberDeclarationSyntax)eventFieldDeclaration.Parent;

            SyntaxList <MemberDeclarationSyntax> members = containingMember.GetMembers();

            MethodDeclarationSyntax method = CreateOnEventMethod(eventSymbol, eventArgsSymbol, supportsCSharp6)
                                             .WithFormatterAnnotation();

            SyntaxList <MemberDeclarationSyntax> newMembers = Inserter.InsertMember(members, method);

            return(document.ReplaceNodeAsync(containingMember, containingMember.SetMembers(newMembers), cancellationToken));
        }
        private static async Task <Document> RefactorAsync(
            Document document,
            MemberDeclarationSyntax declaration,
            List <MemberDeclarationSyntax> assignableMembers,
            CancellationToken cancellationToken = default(CancellationToken))
        {
            MemberDeclarationSyntax parentMember = GetContainingMember(declaration);

            SyntaxList <MemberDeclarationSyntax> members = parentMember.GetMembers();

            SyntaxList <MemberDeclarationSyntax> newMembers = Inserter.InsertMember(
                members,
                CreateConstructor(GetConstructorIdentifierText(parentMember), assignableMembers));

            MemberDeclarationSyntax newNode = parentMember.SetMembers(newMembers)
                                              .WithFormatterAnnotation();

            return(await document.ReplaceNodeAsync(parentMember, newNode, cancellationToken).ConfigureAwait(false));
        }
Exemple #13
0
        /// <summary>
        /// Create a new Hyper file with a single table and write some data into it.
        /// </summary>
        /// <param name="exampleDataDir">Path to the directory with example data.</param>
        public override void Execute(string exampleDataDir)
        {
            Console.WriteLine("EXAMPLE - Insert data into a single tables within a new Hyper file.");

            // Start the Hyper process with telemetry enabled.
            using (HyperProcess hyper = new HyperProcess(Telemetry.SendUsageDataToTableau))
            {
                // Connect to hyper and create new Hyper file "superstore.hyper".
                // Replaces file if it already exists when CreateMode.CreateAndReplace is set.
                using (Connection connection = new Connection(hyper.Endpoint, "superstore.hyper", CreateMode.CreateAndReplace))
                {
                    // The table is called "Extract" and will be created in the "Extract" schema.
                    // This has historically been the default table name and schema for extracts created by Tableau.
                    TableName       extractTable           = new TableName("Extract", "Extract");
                    TableDefinition extractTableDefinition = new TableDefinition(extractTable)
                                                             .AddColumn("Customer ID", SqlType.Text(), Nullability.NotNullable)
                                                             .AddColumn("Customer Name", SqlType.Text(), Nullability.NotNullable)
                                                             .AddColumn("Loyalty Reward Points", SqlType.BigInt(), Nullability.NotNullable)
                                                             .AddColumn("Segment", SqlType.Text(), Nullability.NotNullable);

                    // Create the schema and the table
                    connection.Catalog.CreateSchema("Extract");
                    connection.Catalog.CreateTable(extractTableDefinition);

                    // Insert data into the "Extract"."Extract" table
                    using (Inserter inserter = new Inserter(connection, extractTable))
                    {
                        inserter.AddRow("DK-13375", "Dennis Kane", 518, "Consumer");
                        inserter.AddRow("EB-13705", "Ed Braxton", 815, "Corporate");
                        inserter.Execute();
                    }

                    // ExecuteScalarQuery is for executing a query that returns exactly one row with one column
                    long count = connection.ExecuteScalarQuery <long>($"SELECT COUNT(*) FROM {extractTable}");
                    Console.WriteLine($"Table {extractTable} has a count of {count} rows");
                }

                Console.WriteLine("The connection to the Hyper file has been closed.");
            }

            Console.WriteLine("The Hyper process has been shut down.");
        }
Exemple #14
0
        private static Task <Document> RefactorAsync(
            Document document,
            StructDeclarationSyntax structDeclaration,
            INamedTypeSymbol typeSymbol,
            INamedTypeSymbol equatableSymbol,
            SemanticModel semanticModel,
            CancellationToken cancellationToken)
        {
            int position = structDeclaration.SpanStart;

            SimpleBaseTypeSyntax baseType = SimpleBaseType(equatableSymbol.ToMinimalTypeSyntax(semanticModel, position));

            StructDeclarationSyntax newNode = AddBaseType(structDeclaration, baseType);

            TypeSyntax classType = typeSymbol.ToMinimalTypeSyntax(semanticModel, position);

            newNode = Inserter.InsertMember(newNode, CreateEqualsMethod(classType, semanticModel, position));

            return(document.ReplaceNodeAsync(structDeclaration, newNode, cancellationToken));
        }
Exemple #15
0
        public void NotBeNullable()
        {
            using (FileDeleter fd = new FileDeleter(Extensions.GetTempDBFile()))
            {
                Database db = new Database(new Context(fd.Fi));
                using (SQLiteConnection conn = db.Connection)
                {
                    conn.Open();

                    conn.ExecuteNonQuery("CREATE TABLE Temp(A INTEGER NOT NULL PRIMARY KEY, B TEXT NOT NULL)");
                    Assert.True(conn.DoesTableExist("Temp"));

                    Inserter i = new Inserter("Temp", conn);
                    i.Set("A", 1);
                    i.SetNull("B");

                    Assert.Throws <SQLiteException>(() => i.Execute());
                }
            }
        }
Exemple #16
0
        public static void SetValue(string path, string value, bool normalize, DateTimeOffset timestamp, SQLiteConnection conn)
        {
            if (string.IsNullOrEmpty(path))
            {
                return;
            }

            string existing_value = GetValue(path, conn);

            if (value != existing_value)
            {
                Clear(path, conn);

                Inserter insert = new Inserter("Configuration", conn);
                insert.Set("Path", path, true);
                insert.Set("Value", value ?? string.Empty, normalize);
                insert.Set("DateAdded", timestamp);
                insert.Set("IsValid", 1);
                insert.Execute();
            }
        }
Exemple #17
0
#pragma warning disable S3241 // Methods should not return values that are never used
        private async Task StartFileTransfer()
#pragma warning restore S3241 // Methods should not return values that are never used
        {
            //build staging table
            if (!Context.IsAppendingDataToExistingTable)
            {
                DestinationTableCreator TableMaker = new DestinationTableCreator(Context);
                TableMaker.CreateTable();
            }

            //create buffer
            ConcurrentQueue <List <string> > Queu = new ConcurrentQueue <List <string> >();
            //create threads to transfer file
            SourceFileReader Reader = new SourceFileReader(Context, Queu);
            Inserter         Writer = new Inserter(Context, Queu);

            Writer.done             = false;
            Reader.ReadFinished    += Writer.StopWriting;
            Writer.FinishedWriting += OnWriterFinishing;

            // start everything up and monitor for finish
            Reader.StartReading();
            for (int i = 0; i < NumberOfWriterThreads; i++)
            {
                Writer.CreateConcurrentWriter();
            }

            await Task.Run(() =>
            {
                while (NumberOfWriterThreads > NumberOfFinishedThreads)
                {
                    Task.Delay(1000).Wait();
                }
            });


            btnStartTransfer.Enabled = true;
            OnLoadStageOneFinished();
        }
Exemple #18
0
        public static ConstructorDeclarationSyntax AddStaticModifier(ConstructorDeclarationSyntax constructorDeclaration)
        {
            if (constructorDeclaration == null)
            {
                throw new ArgumentNullException(nameof(constructorDeclaration));
            }

            SyntaxTokenList modifiers = constructorDeclaration.Modifiers;

            if (!modifiers.Contains(SyntaxKind.StaticKeyword))
            {
                SyntaxTokenList newModifiers = modifiers;

                if (modifiers.ContainsAccessModifier())
                {
                    newModifiers = modifiers.RemoveAccessModifiers();

                    if (newModifiers.Any())
                    {
                        newModifiers = newModifiers.ReplaceAt(0, newModifiers[0].WithLeadingTrivia(modifiers[0].LeadingTrivia));
                        newModifiers = Inserter.InsertModifier(newModifiers, SyntaxKind.StaticKeyword);
                    }
                    else
                    {
                        newModifiers = Inserter.InsertModifier(newModifiers, CSharpFactory.StaticKeyword().WithLeadingTrivia(modifiers[0].LeadingTrivia));
                    }
                }
                else
                {
                    newModifiers = Inserter.InsertModifier(newModifiers, SyntaxKind.StaticKeyword);
                }

                return(constructorDeclaration.WithModifiers(newModifiers));
            }
            else
            {
                return(constructorDeclaration);
            }
        }
Exemple #19
0
        public static MemberDeclarationSyntax AddNewDocumentationComment(
            MemberDeclarationSyntax memberDeclaration,
            DocumentationCommentGeneratorSettings settings,
            SemanticModel semanticModel,
            CancellationToken cancellationToken = default(CancellationToken))
        {
            if (memberDeclaration == null)
            {
                throw new ArgumentNullException(nameof(memberDeclaration));
            }

            if (CanGenerateFromBase(memberDeclaration.Kind()))
            {
                BaseDocumentationCommentInfo info = GenerateFromBase(memberDeclaration, semanticModel, cancellationToken);

                if (info.Success)
                {
                    return(Inserter.InsertDocumentationComment(memberDeclaration, info.Trivia, indent: true));
                }
            }

            return(AddNewDocumentationComment(memberDeclaration, settings));
        }
Exemple #20
0
        private static SyntaxTokenList GetNewModifiers(SyntaxTokenList modifiers, Accessibility accessibility)
        {
            switch (accessibility)
            {
            case Accessibility.Public:
            {
                return(Inserter.InsertModifier(modifiers, SyntaxKind.PublicKeyword));
            }

            case Accessibility.Internal:
            {
                return(Inserter.InsertModifier(modifiers, SyntaxKind.InternalKeyword));
            }

            case Accessibility.Protected:
            {
                return(Inserter.InsertModifier(modifiers, SyntaxKind.ProtectedKeyword));
            }

            case Accessibility.ProtectedOrInternal:
            {
                modifiers = Inserter.InsertModifier(modifiers, SyntaxKind.ProtectedKeyword);
                return(Inserter.InsertModifier(modifiers, SyntaxKind.InternalKeyword));
            }

            case Accessibility.Private:
            {
                return(Inserter.InsertModifier(modifiers, SyntaxKind.PrivateKeyword));
            }

            default:
            {
                Debug.Assert(false, accessibility.ToString());
                return(modifiers);
            }
            }
        }
Exemple #21
0
        /// <summary>
        /// Updates a device's status. If the new status is null, the existing status should be invalidated and no new
        /// entry added. If the new status is non-null, see it the existing status matches the new status. If the new
        /// and old status are identical, do nothing. If the new and old status are different somehow (the status itself,
        /// the is-alarm flag or the message are different), invalidate the old status and insert a new status.
        ///
        /// A single device may have different statuses, so we need to restrict our decisions to a set of types, which
        /// is included in the 3rd parameter. For example, the memory statuses are adequate, low, or critically low. Only
        /// one of these should be 'active' at a given time.
        /// </summary>
        /// <param name="device_id">The ID of the device we're checking</param>
        /// <param name="type">The new type. Can be null to indicate the status should be cleared</param>
        /// <param name="statuses">The full set of statuses we should be considering. Will be a subset of all
        /// the statuses a device can have.</param>
        /// <param name="message">A message regarding the status</param>
        /// <param name="conn">The DB connection to use</param>
        protected static void SetDeviceStatus(long device_id, EStatusType?type, List <EStatusType> statuses, string message, SQLiteConnection conn)
        {
            if (type.HasValue)
            {
                Debug.Assert(statuses.Contains(type.Value));
            }

            EAlertLevel alert_level = (type.HasValue ? type.Value.GetAlertLevel() : null) ?? EAlertLevel.Normal;
            string      in_clause   = statuses.Join();
            string      clause      = $"DeviceID = {device_id} AND StatusType IN ({in_clause}) AND IsValid = 1";
            string      sql         = $"SELECT StatusType, IsAlarm, Message FROM DeviceStatus WHERE {clause};";
            bool        insert      = type.HasValue;
            bool        remove      = type.HasValue == false;

            if (type.HasValue)
            {
                // We may be inserting a new type. We need to see if the current value for the device/status is the
                // same, or has changed. If it's the same we don't need to do anything. If it's changed, we'll want to
                // mark the old value as invalid, and insert the new value.
                using (SQLiteCommand command = new SQLiteCommand(sql, conn))
                    using (SQLiteDataReader reader = command.ExecuteReader())
                    {
                        if (reader.Read())
                        {
                            EStatusType existing_type        = (EStatusType)reader.GetInt32(0);
                            EAlertLevel existing_alert_level = (EAlertLevel)reader.GetInt32(1);
                            string      existing_message     = reader.IsDBNull(2) ? string.Empty : reader.GetString(2);

                            // An existing record exists, so insert the new one and update the old one if something's changed.
                            // If nothing changed, we'll leave the old one alone
                            bool something_changed =
                                (type.Value != existing_type) ||
                                (alert_level != existing_alert_level) ||
                                (string.Compare(message, existing_message) != 0);

                            // If something has changed, we'll want to remove the old version, and insert the new
                            // version. If nothing changed, we don't want to do either.
                            insert = remove = something_changed;
                        }
                        // If it wasn't found, just insert, which is the default
                    }
            }
            // In this case there's no status value, so that means were clearing out the old one, if it exists.

            if (insert || remove)
            {
                if (remove)
                {
                    Updater updater = new Updater("DeviceStatus", clause, conn);
                    updater.Set("IsValid", 0);
                    updater.Execute();
                }

                if (insert)
                {
                    Inserter inserter = new Inserter("DeviceStatus", conn);
                    inserter.Set("DeviceID", device_id);
                    inserter.Set("StatusType", (int)type);
                    inserter.Set("IsAlarm", (int)alert_level);
                    inserter.Set("Date", DateTimeOffset.Now);
                    inserter.Set("Message", message, false);
                    inserter.Set("IsValid", 1);
                    inserter.Execute();
                }
            }
            // else, no change
        }
 public void InsertNumber_ThrowArgumentOutOfRangeException()
 {
     NUnit.Framework.Assert.Throws <ArgumentOutOfRangeException>(() => Inserter.InsertNumber(8, 12, -4, 2));
     NUnit.Framework.Assert.Throws <ArgumentOutOfRangeException>(() => Inserter.InsertNumber(8, 12, -4, -2));
 }
 public int InsertTest(int a, int b, int i, int j)
 {
     return(Inserter.InsertNumber(a, b, i, j));
 }
 public void InsertNumber_ThrowException_WrongInterval()
 {
     Inserter.InsertNumber(7, 12, 9, 6);
 }
Exemple #25
0
 public void InsertNumberBoundaryArgumentsTest()
 {
     Assert.AreEqual(Int32.MinValue + 1, Inserter.InsertNumber(Int32.MinValue, Int32.MaxValue, 0, 0));
     Assert.AreEqual(-8, Inserter.InsertNumber(-8, -15, 31, 31));
     Assert.AreEqual(15, Inserter.InsertNumber(8, 15, 0, 31));
 }
Exemple #26
0
 public void InsertNumberArgumentExceptionTest()
 {
     Assert.ThrowsException <ArgumentException>(() => Inserter.InsertNumber(-15, -15, 32, 33));
     Assert.ThrowsException <ArgumentException>(() => Inserter.InsertNumber(-15, -15, -1, -2));
     Assert.ThrowsException <ArgumentException>(() => Inserter.InsertNumber(-15, -15, 8, 3));
 }
 public void InsertNumberMethod_IndexArgsLowerThanZero_ArgumentOutOfRangeException()
 {
     Inserter.InsertNumber(8, 15, -1, -1);
 }
 public void InsertNumberMethod_FirstIndBiggerThanSecondInd_ArgumentOutOfRangeException()
 {
     Inserter.InsertNumber(8, 15, 10, 5);
 }
 public void InsertNumber_ThrowArgumentException()
 {
     NUnit.Framework.Assert.Throws <ArgumentException>(() => Inserter.InsertNumber(8, 12, 4, 2));
 }
 public void InsertNumberMethod_IndexArgsBiggerThanRange_ArgumentOutOfRangeException()
 {
     Inserter.InsertNumber(8, 15, 32, 32);
 }
Exemple #31
0
 public void InsertNumberNegativeNumbersTest()
 {
     Assert.AreEqual(-15, Inserter.InsertNumber(-15, -15, 0, 0));
     Assert.AreEqual(-7, Inserter.InsertNumber(-8, -15, 0, 0));
     Assert.AreEqual(-120, Inserter.InsertNumber(-8, -15, 3, 8));
 }