public async Task ThenAllRoutesAreReturned()
        {
            if (!_context.TryGetValue <HttpResponseMessage>(ContextKeys.HttpResponse, out var result))
            {
                Assert.Fail($"scenario context does not contain value for key [{ContextKeys.HttpResponse}]");
            }

            var model = await HttpUtilities.ReadContent <GetRoutesListResponse>(result.Content);

            model.Routes.Should().BeEquivalentTo(DbUtilities.GetTestRoutes().ToList(), config =>
                                                 config.Excluding(route => route.Standards));
        }
        public static void ConfigureInMemoryDB(this IServiceCollection services)
        {
            Console.WriteLine("\t--Configring DBContext-InMemory test-location-01");

            // Remove the app's DatabaseContext registration.
            var descriptors = services.Where(d => d.ServiceType == typeof(DbContext) ||
                                             d.ServiceType == typeof(DbContextOptions <PhonebookContext>)).ToList();

            foreach (var descriptor in descriptors)
            {
                Console.WriteLine("Removing `{0}` => `{1}`", descriptor.ServiceType?.FullName, descriptor.ImplementationType?.FullName);
                services.Remove(descriptor);
            }

            var random = new Random();

            // Add DatabaseContext using an in-memory database for testing.
            services.AddDbContext <DbContext, PhonebookContext>((_, options) =>
            {
                options.UseInMemoryDatabase("DB-" + random.Next());
                options.EnableSensitiveDataLogging(true);
            });

            // Build the service provider.
            var sp = services.BuildServiceProvider();

            // Create a scope to obtain a reference to the database
            // context (DatabaseContext).
            using (var scope = sp.CreateScope())
            {
                var scopedServices = scope.ServiceProvider;
                var db             = scopedServices.GetService <DbContext>();
                var logger         = scopedServices
                                     .GetRequiredService <ILogger <BaseControllerTest> >();

                // Ensure the database is created.
                db.Database.EnsureCreated();

                try
                {
                    // Seed the database with test data.
                    DbUtilities.InitializeDbForTests(db);

                    Console.WriteLine("\t--Users count just after seed {0}", db.Set <Domain.Models.User>().ToList().Count);
                }
                catch (Exception ex)
                {
                    logger.LogError(ex, "An error occurred seeding the " +
                                    "database with test messages. Error: {Message}", ex.Message);
                }
            }
        }
Example #3
0
        public static user RegisterClientUser(string paraUserName, string paraPassword, string paraMobileNumber, user.UserType paratype)
        {
            Dictionary <string, Object> tmpInsertParameters = new Dictionary <string, object>();

            tmpInsertParameters.Add("UserName", paraUserName);
            tmpInsertParameters.Add("Password", paraPassword);
            tmpInsertParameters.Add("MobileNumber", paraMobileNumber);
            user tmpUser = DbUtilities.InsertUser(tmpInsertParameters);

            DbUtilities.enableUserStatus(paraUserName, user.UserStatus.USER_STATUS_ONLINE | user.UserStatus.USER_STATUS_VERIFING);
            return(tmpUser);
            // throw new NotImplementedException();
        }
Example #4
0
        public async Task ThenAllValidStandardsReturned()
        {
            if (!_context.TryGetValue <HttpResponseMessage>(ContextKeys.HttpResponse, out var result))
            {
                Assert.Fail($"scenario context does not contain value for key [{ContextKeys.HttpResponse}]");
            }

            var model = await HttpUtilities.ReadContent <GetStandardsListResponse>(result.Content);

            model.Total.Should().Be(DbUtilities.GetValidTestStandards().Count());

            model.Standards.Should().BeEquivalentTo(DbUtilities.GetValidTestStandards(), StandardEquivalencyAssertionOptions);
        }
        private async static Task <string> AddNewSubscriptionAndGetName(string mail, string number, int?diffPercent, int?diffPln)
        {
            using SqlConnection conn = ConnectionFactory.CreateConnection();
            conn.Open();
            Subscriber subscriber = DbUtilities.GetOrCreateSubscriber(conn, mail);
            LegoSet    set        = await DbUtilities.GetOrCreateSet(conn, int.Parse(number));

            Subscription subscription = CreateSubscription(subscriber, set, diffPercent, diffPln);

            DbUtilities.CreateOrUpdateSubscriptionInDb(conn, subscription);

            return(set.Name);
        }
Example #6
0
        private void ExportDBs()
        {
            Output.WriteToFile("===== EXPORT DBS... =====");

            DbUtilities dbu = new DbUtilities();

            Output.WriteToFile("StationGeoData.db");
            dbu.ExportDB_Geostation(Application.StartupPath.Replace("PumpAnalysis", "PumpData"));
            //System.Threading.Thread.Sleep(5000); //5 sec
            Output.WriteToFile("Archived.db");
            dbu.ExportDB_Archived(Application.StartupPath.Replace("PumpAnalysis", "PumpData"));
            //System.Threading.Thread.Sleep(5000); //5 sec
            Output.WriteToFile("===== DBS EXPORTED... =====");
        }
Example #7
0
        public DataTransfer(ILogger <Worker> logger,
                            AppSettings appSetting,
                            IQueueService queueService)
        {
            _dbConn       = new DbUtilities();
            _logger       = logger;
            _appSeting    = appSetting;
            _queueService = queueService;
            var            builder       = new ConfigurationBuilder();
            IConfiguration configuration = builder.Build();

            _fileStorage = new AzureFileStorageServiceCommon(configuration);
            _fileStorage.SetConnectionString(appSetting.StorageAccount);
        }
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env, WeatherReadingsAPIContext context)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                app.UseSwagger();
                app.UseSwaggerUI(c =>
                {
                    c.SwaggerEndpoint("/swagger/v1/swagger.json", "WeatherReadingsAPI v1");
                    c.RoutePrefix = "swagger";
                }

                                 );
            }

            app.UseDefaultFiles();
            app.UseStaticFiles();
            app.UseHttpsRedirection();



            // Configure cors
            app.UseCors(x => x
                        //.AllowAnyOrigin() // Not allowed together with AllowCredential
                        //.WithOrigins("http://localhost:8080", "http://localhost:5000" )
                        .SetIsOriginAllowed(x => _ = true)
                        .AllowAnyMethod()
                        .AllowAnyHeader()
                        .AllowCredentials()
                        );



            app.UseRouting();

            app.UseAuthentication();

            app.UseAuthorization();


            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
                endpoints.MapHub <ServerSignal>("/reporthub");
            });



            DbUtilities.SeedData(context);
        }
        public void DeleteProject(Project project)
        {
            using (var conn = Connection)
            {
                conn.Open();
                using (var cmd = conn.CreateCommand())
                {
                    string hasComponentsToDelete = "";
                    if (project.Components.Count > 0)
                    {
                        var    componentBeingDeleted = project.Components;
                        string recurrsiveDeletes     = "";
                        for (int i = 0; i < componentBeingDeleted.Count; i++)
                        {
                            int comId = componentBeingDeleted[i].Id;

                            //Add the Sql '@' to the 'In' chain for this index of the Component List
                            string deleteParam = "@deleteId" + i;
                            recurrsiveDeletes += deleteParam;
                            //Add a comma between the statement if its not the last one in the list
                            if (i != componentBeingDeleted.Count - 1)
                            {
                                recurrsiveDeletes += ", ";
                            }
                            //Tie this Id value to the command text as it is being built
                            DbUtilities.AddParameter(cmd, deleteParam, comId);
                        }
                        hasComponentsToDelete = @"
                                        DELETE FROM SubContractorBid
                                        WHERE ProjectComponentId IN (  "
                                                + recurrsiveDeletes + " ) " +
                                                @"DELETE FROM ProjectComponentImages
                                        WHERE ProjectComponentId IN ( "
                                                + recurrsiveDeletes + " ) ";
                    }

                    cmd.CommandText = hasComponentsToDelete +
                                      @"DELETE FROM ProjectComponent
                                        WHERE ProjectId = @Id
                        
                                        DELETE FROM Project
                                        WHERE Id = @Id
                                        ";
                    DbUtilities.AddParameter(cmd, "@Id", project.Id);

                    cmd.ExecuteNonQuery();
                }
            }
        }
Example #10
0
        private void CreateNewGeoPoint()                                                            //create new point from gridRow and connect it with this Row
        {
            string Lat  = dgvReceiptData.SelectedRows[0].Cells["RealLat"].Value.ToString().Trim();  //.Replace('.', ',');
            string Long = dgvReceiptData.SelectedRows[0].Cells["RealLong"].Value.ToString().Trim(); //.Replace('.', ',');

            String DecSep = System.Globalization.CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator;

            if (DecSep == ",")
            {
                Lat  = Lat.Replace('.', ',');
                Long = Long.Replace('.', ',');
            }
            else
            {
                Lat  = Lat.Replace(',', '.');
                Long = Long.Replace(',', '.');
            }

            string Address = dgvReceiptData.SelectedRows[0].Cells["Address"].Value.ToString().Trim();
            string Dealer  = dgvReceiptData.SelectedRows[0].Cells["Dealer"].Value.ToString().Trim();
            string Brand   = dgvReceiptData.SelectedRows[0].Cells["Brand"].Value.ToString().Trim();

            NewGasStation frmGasStation = new NewGasStation();

            frmGasStation.txtLat.Text     = Lat;
            frmGasStation.txtLong.Text    = Long;
            frmGasStation.txtAddress.Text = Address;
            frmGasStation.txtDealer.Text  = Dealer;

            List <Brand> brands = DbUtilities.GetSqlBrandsList();

            frmGasStation.cbBrand.Items.AddRange(DbUtilities.GetBrandsComboboxItemsList(brands).ToArray <ComboboxItem>());
            frmGasStation.cbBrand.SelectedIndex = frmGasStation.cbBrand.FindStringExact(Brand);

            //frmGasStation.txtExtraDataId.Text = dgvReceiptData.SelectedRows[0].Cells["ExtraDataId"].Value.ToString();
            frmGasStation.ExtraDataId = Convert.ToInt32(dgvReceiptData.SelectedRows[0].Cells["ExtraDataId"].Value);

            List <PostalCode> postalCodes = DbUtilities.GetSqlPostalCodesList();

            frmGasStation.cbPostalCode.Items.AddRange(DbUtilities.GetPostalCodesComboboxItemsList(postalCodes).ToArray <ComboboxItem>());

            DialogResult dlgRes = frmGasStation.ShowDialog();

            if (dlgRes == DialogResult.Yes)
            {
                //(refresh grid or) update geostationId
                dgvReceiptData.SelectedRows[0].Cells["GeostationId"].Value = frmGasStation.NewGeostationId;
            }
        }
Example #11
0
        private void geocodingTest()
        {
            DbUtilities d             = new DbUtilities();
            string      geo_json_data = d.getAllDataFromJsonFile(@"C:\Users\hkylidis\Desktop\rev_geocoding_el.json");

            GeoCoding a = d.stringToGenericObject <GeoCoding>(geo_json_data);

            if (a.status.ToUpper() == "OK")
            {
                string areaLevel1 = a.results.Where(i => i.types.Contains("administrative_area_level_1")).FirstOrDefault().address_components.Where(i => i.types.Contains("administrative_area_level_1")).FirstOrDefault().long_name;
                string areaLevel2 = a.results.Where(i => i.types.Contains("administrative_area_level_2")).FirstOrDefault().address_components.Where(i => i.types.Contains("administrative_area_level_2")).FirstOrDefault().long_name;
                string areaLevel3 = a.results.Where(i => i.types.Contains("administrative_area_level_3")).FirstOrDefault().address_components.Where(i => i.types.Contains("administrative_area_level_3")).FirstOrDefault().long_name;
                string areaLevel4 = a.results.Where(i => i.types.Contains("administrative_area_level_4")).FirstOrDefault().address_components.Where(i => i.types.Contains("administrative_area_level_4")).FirstOrDefault().long_name;
            }
        }
        public async Task ThenAllShortlistItemsForUserAreReturned()
        {
            if (!_context.TryGetValue <HttpResponseMessage>(ContextKeys.HttpResponse, out var result))
            {
                Assert.Fail($"scenario context does not contain value for key [{ContextKeys.HttpResponse}]");
            }

            var model = await HttpUtilities.ReadContent <GetShortlistForUserResponse>(result.Content);

            var allShortlistsForUser = DbUtilities.GetAllShortlists()
                                       .Where(shortlist => shortlist.ShortlistUserId == Guid.Parse(DbUtilities.ShortlistUserId));

            model.Shortlist.Should().BeEquivalentTo(allShortlistsForUser, options => options
                                                    .ExcludingMissingMembers()
                                                    );
        }
Example #13
0
        public async Task ThenAllNotApprovedStandardsAreReturned()
        {
            if (!_context.TryGetValue <HttpResponseMessage>(ContextKeys.HttpResponse, out var result))
            {
                Assert.Fail($"scenario context does not contain value for key [{ContextKeys.HttpResponse}]");
            }

            var model = await HttpUtilities.ReadContent <GetStandardsListResponse>(result.Content);

            var standardsList = new List <Standard>();

            standardsList.AddRange(DbUtilities.GetNotYetApprovedTestStandards());

            model.Standards.Should().BeEquivalentTo(standardsList, StandardEquivalencyAssertionOptions);
            model.Total.Should().Be(standardsList.Count);
        }
Example #14
0
        protected override void ConfigureWebHost(IWebHostBuilder builder)
        {
            builder.ConfigureServices(services =>
            {
                // Remove the app's DbContext registration.
                var descriptor = services.SingleOrDefault(
                    d => d.ServiceType ==
                    typeof(DbContextOptions <NotesDbContext>));

                if (descriptor != null)
                {
                    services.Remove(descriptor);
                }

                // Add app's DbContext using an in-memory database for testing.
                services.AddDbContext <NotesDbContext>((options, context) =>
                {
                    context.UseInMemoryDatabase("InMemoryDbForTesting");
                });

                // Build the service provider.
                var serviceProvider = services.BuildServiceProvider();

                // Create a scope to obtain a reference to the db context.
                using (var scope = serviceProvider.CreateScope())
                {
                    var scopedServices = scope.ServiceProvider;
                    var db             = scopedServices.GetRequiredService <NotesDbContext>();
                    var logger         = scopedServices
                                         .GetRequiredService <ILogger <CustomWebApplicationFactory <TStartup> > >();

                    // Ensure the database is created.
                    db.Database.EnsureCreated();

                    try
                    {
                        // Seed the database with test data.
                        DbUtilities.InitializeDbForTests(db);
                    }
                    catch (Exception ex)
                    {
                        logger.LogError(ex, "An error occurred seeding the database with test data. Error: { Message }", ex.Message);
                    }
                }
            });
        }
Example #15
0
        private IEnumerable <Standard> GetExpected(Table table)
        {
            var testRoutes = DbUtilities.GetTestRoutes();
            var standards  = new List <Standard>();

            foreach (var row in table.Rows)
            {
                standards.Add(DbUtilities.GetAllTestStandards().Single(standard =>
                                                                       standard.Title == row["title"] &&
                                                                       standard.RouteCode == testRoutes.Single(sector => sector.Name == row["route"]).Id&&
                                                                       standard.Level == int.Parse(row["level"]) &&
                                                                       standard.Version == decimal.Parse(row["version"]) &&
                                                                       standard.Status == row["status"]));
            }

            return(standards);
        }
Example #16
0
        private static Calling GetCallLogs(RingCentalLoginInfo obj, DataBaseInfo dataBaseInfo)
        {
            try
            {
                var callLogUrl = obj.Url + obj.UrlRoute;

                DateTimeFormatInfo usDtfi = new CultureInfo("en-US", false).DateTimeFormat;

                var dtm = DateTime.Now.AddMinutes(-30);
                //var dtm = Convert.ToDateTime("2018-10-08 00:00",usDtfi);
                dtm = TimeZoneInfo.ConvertTimeToUtc(dtm);
                var dtmEnd = DateTime.Now.AddMinutes(15);
                //var dtmEnd = Convert.ToDateTime("2018-10-08 23:59", usDtfi);
                dtmEnd = TimeZoneInfo.ConvertTimeToUtc(dtmEnd);

                // var dtm = DateTime.Now.AddDays(-6);
                // var dtmEnd = DateTime.Now.AddDays(-5);

                var yyyy = dtm.ToString("yyyy");
                var mm   = dtm.ToString("MM");
                var dd   = dtm.ToString("dd");

                var filterData = "view=Simple&perPage=100&dateFrom=" + yyyy + "-" + mm + "-" + dd + "T" + dtm.ToString("HH:mm") + ":00.000Z&dateTo=" + dtmEnd.ToString("yyyy") + "-" + dtmEnd.ToString("MM") + "-" + dtmEnd.ToString("dd") + "T" + dtmEnd.ToString("HH:mm") + ":59.000Z";

                callLogUrl = callLogUrl + "?" + filterData;
                string responseContent;
                var    request = System.Net.WebRequest.Create(callLogUrl);
                request.Headers.Add("Authorization", $"Bearer " + accessToken);

                var newStream     = request.GetResponse().GetResponseStream();
                var newreadStream = new StreamReader(newStream, Encoding.UTF8);
                responseContent = newreadStream.ReadToEnd();

                var jsonDict = Newtonsoft.Json.JsonConvert.DeserializeObject <Calling>(responseContent);

                var dbset = new DbUtilities();
                dbset.LogProcess(obj, dataBaseInfo, responseContent);

                return(jsonDict);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Example #17
0
        public UserCrudTests()
        {
            var dbOptionsBuilder = new DbContextOptionsBuilder <ApiContext>().UseInMemoryDatabase("InMemoryTestDb");
            var db = new ApiContext(dbOptionsBuilder.Options);

            DbUtilities.InitDbForTests(db);
            _mapper = new MapperConfiguration(c =>
            {
                c.AddProfile <UserMapper>();
            }).CreateMapper();

            var appSettings = new AppSettings()
            {
                Secret = Guid.NewGuid().ToString(),
            };

            _userService = new UserService(db, Options.Create(appSettings), _mapper);
        }
        public async Task ThenFrameworkIsReturned()
        {
            if (!_context.TryGetValue <HttpResponseMessage>(ContextKeys.HttpResponse, out var result))
            {
                Assert.Fail($"scenario context does not contain value for key [{ContextKeys.HttpResponse}]");
            }

            var model = await HttpUtilities.ReadContent <GetFrameworkResponse>(result.Content);

            var expected = DbUtilities.GetFramework("1");

            model.Should().BeEquivalentTo(expected, options => options
                                          .Excluding(frm => frm.FundingPeriods)
                                          .Excluding(frm => frm.TypicalLengthFrom)
                                          .Excluding(frm => frm.TypicalLengthTo)
                                          .Excluding(frm => frm.TypicalLengthUnit)
                                          );
        }
 private void CreateDMSModel(ConnectParameters connector)
 {
     try
     {
         string      contentRootPath = _env.ContentRootPath;
         string      sqlFile         = contentRootPath + @"\DataBase\DataScienceManagement.sql";
         string      sql             = System.IO.File.ReadAllText(sqlFile);
         DbUtilities dbConn          = new DbUtilities();
         dbConn.OpenConnection(connector);
         dbConn.SQLExecute(sql);
         dbConn.CloseConnection();
     }
     catch (Exception ex)
     {
         Exception error = new Exception("Create DMS Model Error: ", ex);
         throw error;
     }
 }
Example #20
0
        private static HttpResponseMessage TryListSubscriptions(string mail)
        {
            using SqlConnection conn = ConnectionFactory.CreateConnection();
            conn.Open();

            if (!DbUtilities.SubscriberExists(conn, mail))
            {
                return(new HttpResponseMessage(HttpStatusCode.BadRequest));
            }

            List <SubscriptionToList> subscribedSets = DbUtilities.GetActiveSubscriptionsOfUser(conn, mail);
            var json = JsonConvert.SerializeObject(new { subscriptions = subscribedSets }, Formatting.Indented);

            return(new HttpResponseMessage(HttpStatusCode.OK)
            {
                Content = new StringContent(json, Encoding.UTF8, "application/json")
            });
        }
Example #21
0
        public IHttpActionResult ForgotPassword(ActivationRequest request)
        {
            try
            {
                var user = DbUtilities.GetUserByEmail(request.Email);
                if (user != null)
                {
                    string validStatus = ValidationUtilities.ValidateForActivation(request, user, true);
                    if (validStatus == Constants.SUCCESS_MSG)
                    {
                        User account = _context.Users.Where(a => a.Email == request.Email).SingleOrDefault();
                        //if (IsPasswordCorrect(request.Password, account))
                        //    return BadRequest(ErrorCodes.PASSWORD_ALREADY_USED.ToString());
                        byte[] pwdhash = AuthorizationUtilities.hash(request.Password, account.Salt);

                        //  account.UpdatedAt = DateTime.UtcNow;
                        account.ModifiedBy  = request.Email;
                        account.IsActivated = true;
                        account.OTPCode     = "";

                        //add the new password to the database
                        account.Password     = pwdhash;
                        account.PwdStartDate = DateTimeOffset.UtcNow;
                        account.IsLocked     = false;
                        _context.SaveChanges();
                        return(Ok(HttpUtilities.CustomResp(ErrorCodes.PWD_UPDATED.ToString())));
                    }
                    else
                    {
                        return(BadRequest(validStatus));
                    }
                }
                else
                {
                    //user doesn't exists
                    return(BadRequest(ErrorCodes.INVALID_USER.ToString()));
                }
            }
            catch (Exception ex)
            {
                LGSELogger.Error(ex);
                return(InternalServerError(ex));
            }
        }
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env,
                              ApplicationDbContext context)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseHttpsRedirection();

            // Configure cors
            app.UseCors(x => x
                        //.AllowAnyOrigin() // Not allowed together with AllowCredential
                        //.WithOrigins("http://localhost:8080", "http://localhost:8081" "http://localhost:5000" )
                        .SetIsOriginAllowed(x => _ = true)
                        .AllowAnyMethod()
                        .AllowAnyHeader()
                        .AllowCredentials()
                        );

            // Enable middleware to serve generated Swagger as a JSON endpoint.
            app.UseSwagger();

            // Enable middleware to serve swagger-ui (HTML, JS, CSS, etc.),
            // specifying the Swagger JSON endpoint.
            app.UseSwaggerUI(c =>
            {
                c.SwaggerEndpoint("/swagger/v1/swagger.json", "Models API V1");
                c.RoutePrefix = string.Empty; // To serve the Swagger UI at the app's root
            });

            app.UseRouting();

            app.UseAuthentication();
            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });

            DbUtilities.SeedData(context);
        }
Example #23
0
        public async Task <ActionResult <List <DmsIndex> > > Get(string source)
        {
            ConnectParameters connector = Common.GetConnectParameters(connectionString, container, source);

            if (connector == null)
            {
                return(BadRequest());
            }
            DbUtilities     dbConn = new DbUtilities();
            List <DmsIndex> index  = new List <DmsIndex>();

            try
            {
                dbConn.OpenConnection(connector);
                DbQueries dbq    = new DbQueries();
                string    select = dbq["Index"];
                string    query  = " where INDEXLEVEL = 1";
                DataTable dt     = dbConn.GetDataTable(select, query);
                foreach (DataRow qcRow in dt.Rows)
                {
                    string dataType     = qcRow["Dataname"].ToString();
                    string indexNode    = qcRow["Text_IndexNode"].ToString();
                    int    indexId      = Convert.ToInt32(qcRow["INDEXID"]);
                    string strProcedure = $"EXEC spGetDescendants '{indexNode}'";
                    query = "";
                    DataTable qc          = dbConn.GetDataTable(strProcedure, query);
                    int       nrOfObjects = qc.Rows.Count - 1;
                    index.Add(new DmsIndex()
                    {
                        Id                  = indexId,
                        DataType            = dataType,
                        NumberOfDataObjects = nrOfObjects
                    });
                }
            }
            catch (Exception)
            {
                return(BadRequest());
            }

            dbConn.CloseConnection();
            return(index);
        }
Example #24
0
        public void AddCompleteDateToComponent(ProjectComponent component)
        {
            using (var conn = Connection)
            {
                conn.Open();
                using (var cmd = conn.CreateCommand())
                {
                    cmd.CommandText = @"
                                        UPDATE ProjectComponent 
                                        SET DateComplete = @DateComplete
                                        WHERE Id = @id
                                        ";
                    DbUtilities.AddParameter(cmd, "@DateComplete", component.DateComplete);
                    DbUtilities.AddParameter(cmd, "@id", component.Id);

                    cmd.ExecuteNonQuery();
                }
            }
        }
Example #25
0
        protected void btnLogIn_Click(object sender, EventArgs e)
        {
            if (Page.IsValid)
            {
                string username = txtUsername.Text;
                string password = txtPassword.Text;

                if (DbUtilities.ValidateUser(username, password))
                {
                    Session["Username"] = username;
                    Response.Redirect("~/Views/Search.aspx");
                }
                else
                {
                    txtUsername.Text = string.Empty;
                    txtPassword.Text = string.Empty;
                }
            }
        }
Example #26
0
        public void AddComponentImage(ProjectComponentImages image)
        {
            using (var conn = Connection)
            {
                conn.Open();
                using (var cmd = conn.CreateCommand())
                {
                    cmd.CommandText = @"
                                        INSERT INTO ProjectComponentImages ( ProjectComponentId, ProjectComponentImageUrl)
                                        OUTPUT Inserted.Id
                                        Values (@ProjectComponentId, @ProjectComponentImageUrl)
                                        ";
                    DbUtilities.AddParameter(cmd, "@ProjectComponentId", image.ProjectComponentId);
                    DbUtilities.AddParameter(cmd, "@ProjectComponentImageUrl", image.ProjectComponentImageUrl);

                    image.Id = (int)cmd.ExecuteScalar();
                }
            }
        }
        public static Boolean gotSMSfromUser(string paraUserName, string paraSMS)
        {
            string s;

            ir.expert.signalR.SysetemHub.debug_connections.TryGetValue(paraUserName + paraSMS, out s);
            if (s != null)
            {
                Microsoft.AspNet.SignalR.GlobalHost.ConnectionManager.GetHubContext("SysetemHub").Clients.Client(s).showAppFace(1, "ok,we got sms!");
                if (DbUtilities.isUserStatusEnable(paraUserName, user.user.UserStatus.USER_STATUS_VERIFING))
                {
                    if (isUserSMSandVerifyKeyOK(paraUserName, paraSMS, paraUserName))
                    {
                        DbUtilities.disableUserStatus(paraUserName, user.user.UserStatus.USER_STATUS_VERIFING);
                    }
                }
                return(true);
            }
            return(false);
        }
Example #28
0
        public void AcceptBid(SubContractorBid bid)
        {
            using (var conn = Connection)
            {
                conn.Open();
                using (var cmd = conn.CreateCommand())
                {
                    cmd.CommandText = @"
                                        UPDATE SubContractorBid
                                        SET SubAccepted = @SubAccepted
                                        WHERE Id = @id
                                        ";
                    DbUtilities.AddParameter(cmd, "@SubAccepted", bid.SubAccepted);
                    DbUtilities.AddParameter(cmd, "@id", bid.Id);

                    cmd.ExecuteNonQuery();
                }
            }
        }
Example #29
0
        /// <summary>
        /// Does the validations on the user.
        /// </summary>
        /// <param name="user"></param>
        /// <returns></returns>
        public static string ValidateUserDetails(RegisterRequest user)
        {
            string errorMessage         = string.Empty;
            string userValidationErrors = ValidateModel(user);

            if (!userValidationErrors.Equals(string.Empty))
            {
                return(userValidationErrors);
            }

            var account = dbContext.Users.SingleOrDefault(a => a.Email == user.Email);
            var role    = dbContext.Roles.SingleOrDefault(a => a.Id == user.RoleId);

            if (account != null && !account.IsActivated)
            {
                return(ErrorCodes.USER_EXISTS_NOT_ACTIVATED.ToString());
            }
            else if (account != null)
            {
                return(ErrorCodes.USER_EXISTS.ToString());
            }
            else if (!DbUtilities.ValidateUserDomain(user.Email))
            {
                return(ErrorCodes.DOMAIN_IS_INACTIVE.ToString());
            }
            else if (string.IsNullOrWhiteSpace(user.Email))
            {
                return(ErrorCodes.EMAIL_ADD_REQ.ToString());
            }
            else if (!string.IsNullOrEmpty(user.RoleId) && role == null)
            {
                return(ErrorCodes.INVALID_ROLE.ToString());
            }
            else if (user.RoleId == "8FE7DBCB-DCC3-4AC1-803A-5336621C8359" && string.IsNullOrEmpty(user.EUSR))
            {
                return(ErrorCodes.EUSR_REQ.ToString());
            }
            else
            {
                return(string.Empty);
            }
        }
        static ColumnProperties GetColumnSchema(DbUtilities dbConn, string sql)
        {
            ColumnProperties colProps      = new ColumnProperties();
            string           attributeType = "";
            string           table         = GetTable(sql);
            string           select        = $"Select * from INFORMATION_SCHEMA.COLUMNS ";
            string           query         = $" where TABLE_NAME = '{table}'";
            DataTable        dt            = dbConn.GetDataTable(select, query);

            string[] sqlAttributes = Common.GetAttributes(sql);
            dt.CaseSensitive = false;

            foreach (string attribute in sqlAttributes)
            {
                string attributeIndex = attribute.Trim();
                query = $"COLUMN_NAME = '{attributeIndex}'";
                DataRow[] dtRows = dt.Select(query);
                if (dtRows.Length == 1)
                {
                    attributeType = dtRows[0]["DATA_TYPE"].ToString();
                    if (attributeType == "nvarchar")
                    {
                        string charLength = dtRows[0]["CHARACTER_MAXIMUM_LENGTH"].ToString();
                        attributeType = attributeType + "(" + charLength + ")";
                    }
                    else if (attributeType == "numeric")
                    {
                        string numericPrecision = dtRows[0]["NUMERIC_PRECISION"].ToString();
                        string numericScale     = dtRows[0]["NUMERIC_SCALE"].ToString();
                        attributeType = attributeType + "(" + numericPrecision + "," + numericScale + ")";
                    }
                }
                else
                {
                    Console.WriteLine("Warning: attribute not found");
                }

                colProps[attributeIndex] = attributeType;
            }

            return(colProps);
        }