示例#1
0
        private void btnSelect_Click(object sender, EventArgs e)
        {
            _mySearchId = patientSearch.Text;
            dictionary = createCheckPatientExistsDictionary(_mySearchId);
            dc = new DatabaseConnector();
            dtPatient = checkPatientExists(dictionary);

            if (int.Parse(dtPatient.Rows[0][0].ToString()) > 0)
            {
                ViewDemography cd = new ViewDemography();
                cd.patientId = int.Parse(patientSearch.Text);
                patientSearch.Clear();
                cd.MdiParent = this.MdiParent;
                cd.Show();
            }
            else
            {
                MessageBox.Show("Patient does not exist.");

                DialogResult result = MessageBox.Show("Create New Patient Demography?", "New Demography", MessageBoxButtons.OKCancel,
                    MessageBoxIcon.Question);

                if (result == DialogResult.OK)
                {
                    
                    CreateDemForm create = new CreateDemForm();
                    create.MdiParent = this.MdiParent;
                    create.Show();
                }
            }
        }
    void Start()
    {
        dConnector = new DatabaseConnector(DatabaseName);

        if (resetDatabase) {
            PlayerPrefs.DeleteAll ();
        }

        newDB = PlayerPrefs.GetInt ("newDB");
        if (newDB == 0) {
            createTables.onClick.AddListener (() => {
                try{
                    //Create tables
                    dConnector.CreateChapterTables ();
                    //Lock DB with key
                    dConnector.SetKey (DBKey);
                    //Flip NewDB
                    newDB = 1;
                    PlayerPrefs.SetInt ("newDB", newDB);
                    createTables.enabled = false;
                    createTables.image.color = new Color(1f,1f,1f,0.3f);

                }catch(Exception){
                    //Database already exist
                    createTables.enabled = false;
                    createTables.image.color = new Color(1f,1f,1f,0.3f);
                    newDB = 1;
                    PlayerPrefs.SetInt ("newDB", newDB);

                }
            });
        } else {
            createTables.enabled = false;
            createTables.image.color = new Color(1f,1f,1f,0.3f);
        }

        submitButton.onClick.AddListener(()=>{
            string pass = password.text;
            if(pass == DBKey)
            {
                //Unlock Db with KEY
                dConnector.Key (DBKey);
                generateLevels();
                passwordPanel.SetActive(false);
            }
            else{
                password.text = "Invalid Password";
            }
        });
    }
        private void btnSave_Click(object sender, EventArgs e)
        {
            Dictionary<String, String> dictionary = null;
            DatabaseConnector dc = null;
            dc = new DatabaseConnector();
            dictionary = new Dictionary<string, string>();
            dictionary.Add("@name", txt_MediName.Text);
            dictionary.Add("@description ", txt_Description.Text);

            bool result = dc.putdata("EnterMedication", dictionary);
            if (result == true)
            {
                MessageBox.Show("Record Saved Successfully");
                txt_Description.Text = "";
                txt_MediName.Text = "";
                txt_MediName.Focus();
            }
            else
            {
                MessageBox.Show("Failed to save record ");
            }
        }
示例#4
0
        public List<Platform> GetAvailablePlatforms()
        {
            //Get all available Platforms from theGamesDB
            XmlDocument ResultXML = new XmlDocument();
            WebRequest ResultRequest;
            WebResponse ResultResponse;

            //Try to reach TheGameDB - return null if this fails (internet connection is not established, GameDB is down, etc.)
            try
            {
                ResultRequest = WebRequest.Create("http://thegamesdb.net/api/GetPlatformsList.php");
                ResultResponse = ResultRequest.GetResponse();
                ResultXML.Load(ResultResponse.GetResponseStream());
            }
            catch
            {
                DatabaseConnector DBConnector = new DatabaseConnector(LogInstance);
                return DBConnector.Platforms;
            }

            if (ResultXML.InnerXml == "")
                return null;

            List<Platform> XMLResults = new List<Platform>();

            foreach (XmlNode ResultNode in ResultXML.SelectNodes("Data/Platforms/Platform"))
            {
                Platform temp = new Platform();
                temp.Name = ResultNode.SelectSingleNode("name").InnerText;
                temp.ID = int.Parse(ResultNode.SelectSingleNode("id").InnerText);
                temp.Enabled = true;
                XMLResults.Add(temp);
            }

            return XMLResults;
        }
 /// <summary>
 /// This method collects the User form the database
 /// it used to do more before I tranfered my queries to one file
 /// but I have left if so I can keep all user information in one file.
 /// </summary>
 /// <param name="uid">The userID</param>
 /// <returns>The user requested</returns>
 public static Users GetUser(int uid)
 {
     return(DatabaseConnector.GetUser(uid));
 }
 /// <summary>
 /// Lưu lại các thay đổi (thêm mới hoặc sửa)
 /// </summary>
 /// <param name="databaseConnector"></param>
 /// <param name="procedureName"></param>
 /// <param name="entity"></param>
 /// <returns></returns>
 private Task <int> SaveChangeAndReturnRecordEffect <T>(DatabaseConnector databaseConnector, string procedureName, T entity)
 {
     databaseConnector.MapParameterValueAndEntityProperty <T>(procedureName, entity);
     return(databaseConnector.ExecuteNonQuery());
 }
		public void LoadSingleRowWithNestedEntity() {

			string query = @"SELECT Merchant.Name, Merchant.MerchantId, MerchantConfiguration.IsEnabled, MerchantConfiguration.Url
                             FROM Merchant
                             INNER JOIN MerchantConfiguration ON MerchantConfiguration.MerchantId = Merchant.MerchantId
                             WHERE Merchant.MerchantId = 1";

			MerchantEntity actual = null;

			using (DatabaseConnector databaseConnector = new DatabaseConnector(connectionString)) {
				databaseConnector.OnOutput += databaseConnector_OnOutput;
				actual = databaseConnector.ExecuteReaderFetchAll<MerchantEntity>(query).FirstOrDefault();
			}

			string output = this.ConnectorOutput.ToString();

			Assert.IsNotNull(actual);
			Assert.IsNotNull(actual.MerchantConfiguration);

			Assert.AreEqual("Merchant Number One", actual.Name);
			Assert.AreEqual(1, actual.MerchantId);

			Assert.IsTrue(actual.MerchantConfiguration.IsEnabled);
			Assert.AreEqual("http://www.merchantnumberone.com.br", actual.MerchantConfiguration.Url);
		}
示例#8
0
 public async void setProductGroupInDB(clsProductGroup pProductGroup)
 {
     DatabaseResponse dbres = await DatabaseConnector.putDataAsync("/productGroups", pProductGroup.UID, pProductGroup);
 }
        public IActionResult EditUser(EditUser p)
        {
            if (DatabaseConnector.signeduser.id != -1)
            {
                DatabaseConnector db = new DatabaseConnector();
                User u = db.getUser(DatabaseConnector.myPostId);
                if (u.imageName == "")
                {
                    p.imagePath = "~/ProfileImages/default.jpg";
                    p.imageName = "None";
                }
                else
                {
                    string[] arr = u.imageName.Split(".");
                    p.imagePath = "~/ProfileImages/" + u.username + "." + arr[1];
                    p.imageName = u.imageName;
                }
                if (ModelState.IsValid)
                {
                    if (p.password != null)
                    {
                        if (p.password.Length < 8)
                        {
                            ModelState.AddModelError("newPassword", "Password must be of at least 8 Characters..!");
                            return(View(p));
                        }
                    }

                    if (u.username != p.username)
                    {
                        if (!db.isUsernameValid(p.username))
                        {
                            ModelState.AddModelError("username", "Enter Usename is not Valid");
                            return(View(p));
                        }
                        if (db.isUsernameExist(p.username, u.id, true))
                        {
                            ModelState.AddModelError("username", "User with this name already Exists");
                            return(View(p));
                        }
                        string   extension = Path.GetExtension(u.imageName);
                        string   filepath  = Path.Combine("C:/Users/Abid Shafique/Desktop/Assignment no 3/Assignment no 3/wwwroot/ProfileImages/", u.username + extension);
                        string   filepath1 = Path.Combine("C:/Users/Abid Shafique/Desktop/Assignment no 3/Assignment no 3/wwwroot/ProfileImages/", p.username + extension);
                        FileInfo f         = new FileInfo(filepath);
                        f.CopyTo(filepath1);
                        f.Delete();
                    }

                    if (u.email != p.email)
                    {
                        if (!db.checkEmail(p.email))
                        {
                            ModelState.AddModelError("email", "Entered Email is not in Correct Format");
                            return(View(p));
                        }
                        if (db.isEmailExist(p.email, u.id, true))
                        {
                            ModelState.AddModelError("email", "Already Accout Exists on this Email");
                            return(View(p));
                        }
                    }
                    User user = new User();
                    user.id = u.id;
                    if (p.myImage != null)
                    {
                        string filename   = Path.GetFileName(p.myImage.FileName);
                        string extension  = Path.GetExtension(p.myImage.FileName);
                        string extension1 = Path.GetExtension(u.imageName);
                        string filepath   = Path.Combine("C:/Users/Abid Shafique/Desktop/Assignment no 3/Assignment no 3/wwwroot/ProfileImages/", p.username + extension);
                        string filepath1  = Path.Combine("C:/Users/Abid Shafique/Desktop/Assignment no 3/Assignment no 3/wwwroot/ProfileImages/", p.username + extension1);

                        FileInfo file = new FileInfo(filepath1);
                        if (file.Exists)
                        {
                            file.Delete();
                        }

                        using (FileStream stream = new FileStream(filepath, FileMode.Create))
                        {
                            p.myImage.CopyTo(stream);
                        }
                        user.imageName = filename;
                    }
                    else
                    {
                        user.imageName = u.imageName;
                    }
                    if (p.password != null)
                    {
                        user.password = p.password;
                    }
                    else
                    {
                        user.password = u.password;
                    }
                    user.email    = p.email;
                    user.username = p.username;
                    DatabaseConnector.signeduser = user;
                    db.UpdateProfile(user);

                    return(View("HomePage", db.getAllUsers()));
                }
                else
                {
                    return(View(p));
                }
            }
            else
            {
                return(View("Index"));
            }
        }
示例#10
0
 public void GetPlayers_GetPlayerOfTeam33()
 {
     database = new DatabaseConnector();
     Assert.IsNotNull(database.GetPlayerByTeem(33));
 }
示例#11
0
        /// <summary>
        /// Thêm mới và trả về kết quả từ store sử dụng connector truyền vào
        /// </summary>
        /// <param name="entity"></param>
        /// <param name="databaseConnector"></param>
        /// <returns></returns>
        protected virtual async Task <object> InsertAndReturnSingleValue(T entity, DatabaseConnector databaseConnector)
        {
            var storeName = DatabaseUtility.GeneateStoreName <T>(ProcdureTypeName.Insert);

            return(await InsertAndReturnSingleValue(storeName, entity, databaseConnector));
        }
		public void ExecuteNonQuery() {

			string query = @"UPDATE Merchant SET Merchant.Name = Merchant.Name WHERE Merchant.MerchantId = 1;";

			int actual = 0;

			using (DatabaseConnector databaseConnector = new DatabaseConnector(connectionString)) {
				actual = databaseConnector.ExecuteNonQuery(query);
			}

			Assert.AreEqual(1, actual);
		}
		public void ExecuteNonQueryWithNullQueryString() {

			using (DatabaseConnector databaseConnector = new DatabaseConnector(connectionString)) {
				databaseConnector.ExecuteNonQuery(null);
			}
		}
		public void LoadDatabaseTimeWithoutResult() {

			string query = @"SELECT GETDATE() WHERE 1 <> 1;";

			DateTime actual;

			using (DatabaseConnector databaseConnector = new DatabaseConnector(connectionString)) {
				actual = databaseConnector.ExecuteScalar<DateTime>(query);
			}

			Assert.AreEqual(DateTime.MinValue, actual);
		}
		public void LoadMerchantNameFromId() {

			string query = @"SELECT Name FROM Merchant WHERE MerchantId = @MerchantId;";

			string actual;

			using (DatabaseConnector databaseConnector = new DatabaseConnector(connectionString)) {
				databaseConnector.OnOutput += databaseConnector_OnOutput;
				actual = databaseConnector.ExecuteScalar<string>(query, new { MerchantId = 1 });
			}

			string output = this.ConnectorOutput.ToString();

			Assert.AreEqual("Merchant Number One", actual);
		}
		public void LoadDatabaseDateTimeWithoutQuery() {

			using (DatabaseConnector databaseConnector = new DatabaseConnector(connectionString)) {
				object actual = databaseConnector.ExecuteScalar<DateTime>(null);
			}
		}
		public void LoadDatabaseDateTimeWithScalarToInt() {

			string query = @"SELECT GETDATE();";

			object actual;

			using (DatabaseConnector databaseConnector = new DatabaseConnector(connectionString)) {
				actual = databaseConnector.ExecuteScalar<int>(query);
			}
		}
		public void LoadDatabaseDateTimeWithScalar() {

			string query = @"SELECT GETDATE();";

			object actual;

			using (DatabaseConnector databaseConnector = new DatabaseConnector(connectionString)) {
				databaseConnector.OnOutput += databaseConnector_OnOutput;
				actual = databaseConnector.ExecuteScalar<DateTime>(query);
			}

			string output = this.ConnectorOutput.ToString();

			Assert.IsNotNull(actual);
			Assert.IsInstanceOfType(actual, typeof(DateTime));
		}
 private void Start()
 {
     Initialize();
     connector = new RestConnector();
 }
		public void InsertMerchantWithDatabaseRollback() {

			string query = @"INSERT INTO Merchant (Name) VALUES ('Temp Merchant');";

			SqlTransaction sqlTransaction = DatabaseConnector.BeginGlobalTransaction(connectionString);

			DatabaseConnector databaseConnector = new DatabaseConnector(connectionString);

			databaseConnector.ExecuteNonQuery(query);

			Nullable<int> merchantId = databaseConnector.ExecuteScalar<Nullable<int>>("SELECT MerchantId FROM Merchant WHERE Name = 'Temp Merchant';");

			sqlTransaction.Rollback();

			merchantId = databaseConnector.ExecuteScalar<Nullable<int>>("SELECT MerchantId FROM Merchant WHERE Name = 'Temp Merchant';");

			databaseConnector.Close();
		}
示例#21
0
        private static async Task ProcessSucceededTranscriptionAsync(string transcriptionLocation, string subscriptionKey, TranscriptionStartedMessage serviceBusMessage, string jobName, ILogger log)
        {
            log.LogInformation($"Got succeeded transcription for job {jobName}");

            var jsonContainer       = FetchTranscriptionEnvironmentVariables.JsonResultOutputContainer;
            var textAnalyticsKey    = FetchTranscriptionEnvironmentVariables.TextAnalyticsKey;
            var textAnalyticsRegion = FetchTranscriptionEnvironmentVariables.TextAnalyticsRegion;

            var consolidatedContainer = FetchTranscriptionEnvironmentVariables.ConsolidatedFilesOutputContainer;

            var transcriptionFiles = await BatchClient.GetTranscriptionFilesAsync(transcriptionLocation, subscriptionKey, log).ConfigureAwait(false);

            log.LogInformation($"Received transcription files.");
            var resultFiles = transcriptionFiles.Values.Where(t => t.Kind == TranscriptionFileKind.Transcription);
            var containsMultipleTranscriptions = resultFiles.Skip(1).Any();

            var textAnalyticsInfoProvided = !string.IsNullOrEmpty(textAnalyticsKey) &&
                                            !string.IsNullOrEmpty(textAnalyticsRegion) &&
                                            !textAnalyticsRegion.Equals("none", StringComparison.OrdinalIgnoreCase);

            var textAnalytics = textAnalyticsInfoProvided ? new TextAnalytics(serviceBusMessage.Locale, textAnalyticsKey, textAnalyticsRegion, log) : null;

            var generalErrorsStringBuilder = new StringBuilder();

            foreach (var resultFile in resultFiles)
            {
                log.LogInformation($"Getting result for file {resultFile.Name}");

                var transcriptionResult = await BatchClient.GetSpeechTranscriptFromSasAsync(resultFile.Links.ContentUrl, log).ConfigureAwait(false);

                if (string.IsNullOrEmpty(transcriptionResult.Source))
                {
                    var errorMessage = $"Transcription source is unknown, skipping evaluation.";
                    log.LogError(errorMessage);

                    generalErrorsStringBuilder.AppendLine(errorMessage);
                    continue;
                }

                var fileName = StorageConnector.GetFileNameFromUri(new Uri(transcriptionResult.Source));

                if (transcriptionResult.RecognizedPhrases != null && transcriptionResult.RecognizedPhrases.All(phrase => phrase.RecognitionStatus.Equals("Success", StringComparison.Ordinal)))
                {
                    var textAnalyticsErrors = new List <string>();

                    if (FetchTranscriptionEnvironmentVariables.SentimentAnalysisSetting != SentimentAnalysisSetting.None)
                    {
                        var sentimentErrors = await textAnalytics.AddSentimentToTranscriptAsync(transcriptionResult, FetchTranscriptionEnvironmentVariables.SentimentAnalysisSetting).ConfigureAwait(false);

                        textAnalyticsErrors.AddRange(sentimentErrors);
                    }

                    if (FetchTranscriptionEnvironmentVariables.EntityRedactionSetting != EntityRedactionSetting.None)
                    {
                        var entityRedactionErrors = await textAnalytics.RedactEntitiesAsync(transcriptionResult, FetchTranscriptionEnvironmentVariables.EntityRedactionSetting).ConfigureAwait(false);

                        textAnalyticsErrors.AddRange(entityRedactionErrors);
                    }

                    if (textAnalyticsErrors.Any())
                    {
                        var distinctErrors = textAnalyticsErrors.Distinct();
                        var errorMessage   = $"File {(string.IsNullOrEmpty(fileName) ? "unknown" : fileName)}:\n{string.Join('\n', distinctErrors)}";

                        generalErrorsStringBuilder.AppendLine(errorMessage);
                    }
                }

                var editedTranscriptionResultJson = JsonConvert.SerializeObject(
                    transcriptionResult,
                    Newtonsoft.Json.Formatting.Indented,
                    new JsonSerializerSettings
                {
                    NullValueHandling = NullValueHandling.Ignore
                });

                var jsonFileName        = $"{fileName}.json";
                var archiveFileLocation = System.IO.Path.GetFileNameWithoutExtension(fileName);

                await StorageConnectorInstance.WriteTextFileToBlobAsync(editedTranscriptionResultJson, jsonContainer, jsonFileName, log).ConfigureAwait(false);

                if (FetchTranscriptionEnvironmentVariables.CreateConsolidatedOutputFiles)
                {
                    var audioArchiveFileName = $"{archiveFileLocation}/{fileName}";
                    var jsonArchiveFileName  = $"{archiveFileLocation}/{jsonFileName}";

                    await StorageConnectorInstance.MoveFileAsync(FetchTranscriptionEnvironmentVariables.AudioInputContainer, fileName, consolidatedContainer, audioArchiveFileName, true, log).ConfigureAwait(false);

                    await StorageConnectorInstance.WriteTextFileToBlobAsync(editedTranscriptionResultJson, consolidatedContainer, jsonArchiveFileName, log).ConfigureAwait(false);
                }

                if (FetchTranscriptionEnvironmentVariables.CreateHtmlResultFile)
                {
                    var htmlContainer  = FetchTranscriptionEnvironmentVariables.HtmlResultOutputContainer;
                    var htmlFileName   = $"{fileName}.html";
                    var displayResults = TranscriptionToHtml.ToHtml(transcriptionResult, jobName);
                    await StorageConnectorInstance.WriteTextFileToBlobAsync(displayResults, htmlContainer, htmlFileName, log).ConfigureAwait(false);

                    if (FetchTranscriptionEnvironmentVariables.CreateConsolidatedOutputFiles)
                    {
                        var htmlArchiveFileName = $"{archiveFileLocation}/{htmlFileName}";
                        await StorageConnectorInstance.WriteTextFileToBlobAsync(displayResults, consolidatedContainer, htmlArchiveFileName, log).ConfigureAwait(false);
                    }
                }

                if (FetchTranscriptionEnvironmentVariables.UseSqlDatabase)
                {
                    var duration         = XmlConvert.ToTimeSpan(transcriptionResult.Duration);
                    var approximatedCost = CostEstimation.GetCostEstimation(
                        duration,
                        transcriptionResult.CombinedRecognizedPhrases.Count(),
                        serviceBusMessage.UsesCustomModel,
                        FetchTranscriptionEnvironmentVariables.SentimentAnalysisSetting,
                        FetchTranscriptionEnvironmentVariables.EntityRedactionSetting);

                    var jobId = containsMultipleTranscriptions ? Guid.NewGuid() : new Guid(transcriptionLocation.Split('/').LastOrDefault());
                    var dbConnectionString = FetchTranscriptionEnvironmentVariables.DatabaseConnectionString;
                    using var dbConnector = new DatabaseConnector(log, dbConnectionString);
                    await dbConnector.StoreTranscriptionAsync(
                        jobId,
                        serviceBusMessage.Locale,
                        string.IsNullOrEmpty(fileName)?jobName : fileName,
                        (float)approximatedCost,
                        transcriptionResult).ConfigureAwait(false);
                }

                if (FetchTranscriptionEnvironmentVariables.CreateAudioProcessedContainer)
                {
                    await StorageConnectorInstance.MoveFileAsync(FetchTranscriptionEnvironmentVariables.AudioInputContainer, fileName, FetchTranscriptionEnvironmentVariables.AudioProcessedContainer, fileName, false, log).ConfigureAwait(false);
                }
            }

            var generalErrors = generalErrorsStringBuilder.ToString();

            if (!string.IsNullOrEmpty(generalErrors))
            {
                var errorTxtname = $"jobs/{jobName}.txt";

                await StorageConnectorInstance.WriteTextFileToBlobAsync(
                    generalErrors,
                    FetchTranscriptionEnvironmentVariables.ErrorReportOutputContainer,
                    errorTxtname,
                    log).ConfigureAwait(false);
            }

            var reportFile        = transcriptionFiles.Values.Where(t => t.Kind == TranscriptionFileKind.TranscriptionReport).FirstOrDefault();
            var reportFileContent = await BatchClient.GetTranscriptionReportFileFromSasAsync(reportFile.Links.ContentUrl, log).ConfigureAwait(false);

            await ProcessReportFileAsync(reportFileContent, log).ConfigureAwait(false);

            BatchClient.DeleteTranscriptionAsync(transcriptionLocation, subscriptionKey, log).ConfigureAwait(false).GetAwaiter().GetResult();
        }
		public void LoadDateTimeWithDatabaseCommitTransactionAndEmptyConnectionString() {

			string query = @"SELECT GETDATE();";

			DatabaseConnector.BeginGlobalTransaction(connectionString);

			try {
				using (DatabaseConnector databaseConnector = new DatabaseConnector(string.Empty)) {
					DateTime actual = databaseConnector.ExecuteScalar<DateTime>(query);
				}
			}
			finally {
				DatabaseConnector.CommitGlobalTransaction();
			}
		}
示例#23
0
 /// <summary>
 /// Thêm mới với database với connector truyền vào
 /// </summary>
 /// <param name="entity">Dữ liệu thêm mới</param>
 /// <param name="procedureName">procuder thêm mới</param>
 /// <param name="databaseConnector">connector</param>
 /// <returns></returns>
 public async Task <object> AddAsync(T entity, string procedureName, DatabaseConnector databaseConnector)
 {
     return(await InsertAndReturnSingleValue(procedureName, entity, databaseConnector));
 }
		public void LoadMerchantsAndRollbackWithLocalTransaction() {

			string query = @"SELECT Merchant.Name FROM Merchant WHERE MerchantId = @MerchantId;";

			MerchantData actual = null;

			DatabaseConnector databaseConnector = new DatabaseConnector(connectionString);

			try {
				// Inicializa uma transação de banco de dados.
				databaseConnector.BeginTransaction();

				actual = databaseConnector.ExecuteReaderFetchAll<MerchantData>(query, new { MerchantId = 1 }).FirstOrDefault();

				Assert.IsNotNull(actual);
				Assert.AreEqual("Merchant Number One", actual.Name);

				actual = databaseConnector.ExecuteReaderFetchAll<MerchantData>(query, new { MerchantId = 2 }).FirstOrDefault();

				Assert.IsNotNull(actual);
				Assert.AreEqual("Another Merchant", actual.Name);
			}
			finally {
				databaseConnector.Rollback();
				databaseConnector.Close();
			}
		}
示例#25
0
        public async void getProductGroups()
        {
            DatabaseResponse dbres = await DatabaseConnector.getDataAsync("/productGroups");

            _productGroups = JsonConvert.DeserializeObject <Dictionary <string, clsProductGroup> >(dbres.jsonData);
        }
		public void CommitNullTransaction() {

			using (DatabaseConnector databaseConnector = new DatabaseConnector(connectionString)) {

				databaseConnector.Commit();
			}
		}
示例#27
0
 public async void deleteProductGroupFromDB(clsProductGroup pProductGroup)
 {
     DatabaseResponse dbres = await DatabaseConnector.deleteDataAsync("/productGroups", pProductGroup.UID, pProductGroup);
 }
		public void RollbackNullTransaction() {

			using (DatabaseConnector databaseConnector = new DatabaseConnector(connectionString)) {

				databaseConnector.Rollback();
			}
		}
示例#29
0
        //PROPERTIES

        //CONSTRUCTOR
        public MainWindow()
        {
            InitializeComponent();
            this.Loaded += new RoutedEventHandler(MainWindow_Loaded);
            dataAccesser = new DatabaseConnector();
        }
		public void LoadDateTimeWithDatabaseRollbackTransaction() {

			string query = @"SELECT GETDATE();";

			DatabaseConnector.BeginGlobalTransaction(connectionString);

			try {
				using (DatabaseConnector databaseConnector = new DatabaseConnector()) {
					DateTime actual = databaseConnector.ExecuteScalar<DateTime>(query);
				}
			}
			finally {
				DatabaseConnector.RollbackGlobalTransaction();
			}
		}
示例#31
0
        /// <summary>
        /// This will convert a workset into a number of question sets based on the user
        /// </summary>
        /// <param name="WorksetID"></param>
        /// <param name="_context"></param>
        public GroupResultsViewModel(int WorksetID)
        {
            //Get each question set that has been answered by the students in the group.
            var sets = DatabaseConnector.GetWhere <QuestionSets>($"WorkSetID = {WorksetID}").ToList();
            int correct = 0, total = 0;
            List <UserQuestions>     usrSpecificSets = new List <UserQuestions>();
            List <CompletedQuestion> allQuestions    = new List <CompletedQuestion>();

            var dbQuestionTypes = DatabaseConnector.Get <QuestionTypes>();

            //Itterates through each question set.
            foreach (var set in sets)
            {
                // Collect the list of questions for this set.
                var questionsDB = DatabaseConnector.GetWhere <Questions>($"QuestionSetID={set.QuestionSetID}").ToList();

                List <CompletedQuestion> questionsLists = new List <CompletedQuestion>();

                //Convert each question in the set into a program usable one.
                foreach (var question in questionsDB)
                {
                    questionsLists.Add(new CompletedQuestion()
                    {
                        Type            = dbQuestionTypes.First(x => x.TypeID == question.Question_Type),
                        AnsweredCorrect = question.AnswerCorrect
                    });
                    total++;
                    if (question.AnswerCorrect > 0)
                    {
                        correct++;
                    }
                }

                //Add this question to the list of all questions completed by the students.
                allQuestions.AddRange(questionsLists);
                string name = "User not found / deleted";
                Users  usr  = UserHelper.GetUser(set.UserID);
                if (usr != null)
                {
                    name = usr.First_Name + " " + usr.Last_Name;
                }

                //See if we have already added a question set by this user.
                if (usrSpecificSets.FirstOrDefault(x => x.UserID == set.UserID) == null)
                {
                    //If not create a new one.
                    usrSpecificSets.Add(new UserQuestions()
                    {
                        UserID = set.UserID,
                        Name   = name,
                        //Set the percentage scores (highest and lowest) to the current one.
                        WorstPercentage = new PercentageModel()
                        {
                            Current = questionsLists.Where(x => x.AnsweredCorrect > 0).Count(),
                            Total   = questionsLists.Count()
                        },
                        Percentage = new PercentageModel()
                        {
                            Current = questionsLists.Where(x => x.AnsweredCorrect > 0).Count(),
                            Total   = questionsLists.Count()
                        },
                        Questions      = new CompletedQuestion[][] { questionsLists.ToArray() },
                        Attempts       = 1,
                        NumberAnswered = questionsLists.Where(x => x.AnsweredCorrect != 0).Count()
                    });
                }
                else
                {
                    //Get the user's question information from the list.
                    UserQuestions userQuestionSet = usrSpecificSets.FirstOrDefault(x => x.UserID == set.UserID);
                    //Increase the number of attempt to the current number;
                    userQuestionSet.Attempts += 1;

                    //Add the new questions to the list of questions answered by the user.
                    var qrs = new List <CompletedQuestion[]>()
                    {
                        questionsLists.ToArray()
                    };
                    qrs.AddRange(userQuestionSet.Questions);
                    userQuestionSet.Questions = qrs.ToArray();

                    //Calculate result as percentage score of the current question set and
                    //check to see if it is higher or lower than other attempts.
                    var percent = new PercentageModel()
                    {
                        Current = questionsLists.Where(x => x.AnsweredCorrect > 0).Count(),
                        Total   = questionsLists.Count()
                    };

                    if (userQuestionSet.Percentage.Percentage < percent.Percentage)
                    {
                        userQuestionSet.Percentage = percent;
                    }
                    else if (userQuestionSet.WorstPercentage.Percentage > percent.Percentage)
                    {
                        userQuestionSet.WorstPercentage = percent;
                    }

                    //Check if the number of questions answered is greater than before.
                    //If so, set the number of questions answered equal to this set's number of questions answered.
                    if (questionsLists.Where(x => x.AnsweredCorrect != 0).Count() > userQuestionSet.NumberAnswered)
                    {
                        userQuestionSet.NumberAnswered = questionsLists.Where(x => x.AnsweredCorrect != 0).Count();
                    }
                }
            }

            foreach (var item in usrSpecificSets)
            {
                // Grab all of the questions completed by the user and compile them into a single array.
                var allQuestionsByUser = new List <CompletedQuestion>();
                foreach (var list in item.Questions)
                {
                    allQuestionsByUser.AddRange(list);
                }


                decimal bestper = 0.0m, worstper = 100.0m;

                // Group the questions by their type.
                foreach (var group in allQuestionsByUser.GroupBy(q => q.Type))
                {
                    // Count how many questions of a type the users got correct.
                    int correctForType = 0;
                    foreach (var question in group)
                    {
                        if (question.AnsweredCorrect > 0)
                        {
                            correctForType++;
                        }
                    }

                    // Calculate the percentage of this type which were correct.
                    decimal percent = ((decimal)correctForType / (decimal)group.Count()) * 100.0m;

                    // Check if the highest and lowest percentages are different to the current values,
                    // and set them to the new value if they are.
                    if (percent > bestper)
                    {
                        bestper       = percent;
                        item.bestType = group.Key.Type_Name + " @ " + bestper.ToString("0.###") + "%";
                    }
                    else if (percent < worstper)
                    {
                        worstper       = percent;
                        item.worstType = group.Key.Type_Name + " @ " + worstper.ToString("0.###") + "%";
                    }
                }
            }

            if (sets.Count != 0)
            {
                // Calculates where the student sits on a distribution, compared to other students.
                for (int i = 0; i < usrSpecificSets.Count; i++)
                {
                    usrSpecificSets[i].sameCount = usrSpecificSets
                                                   .Where(x => x.Percentage.Percentage == usrSpecificSets[i].Percentage.Percentage)
                                                   .Count();
                }

                // Get the percentage of questions by their induvidual types.
                List = (from question in allQuestions
                        group question by question.Type.TypeID into QGroup
                        select new PercentageModel
                {
                    Current = QGroup.Where(x => x.AnsweredCorrect > 0).Count(),
                    Total = QGroup.Count()
                }).ToArray();

                //  Compile the name of question types.
                questionTypes = (from question in allQuestions
                                 select question.Type.Type_Name).ToArray();
                // Remove all repeats from the array.
                questionTypes = questionTypes.Unique().ToArray();
            }

            // Set the class variable equal to the local list.
            Averages = usrSpecificSets.ToArray();
            Question = allQuestions.ToArray();

            // Calculate total percentage for the group.
            Percentage = new PercentageModel()
            {
                Current = correct,
                Total   = total
            };
        }
		public void CreateConnectorWithNullTransaction() {

			using (DatabaseConnector databaseConnector = new DatabaseConnector()) { }
		}
 /// <summary>
 /// Checks to see if a user owns a workset:
 /// It used to do more before I tranfered my queries to one file
 /// but I have left if so I can keep all user information in one file
 /// making it easier to access.
 /// </summary>
 /// <param name="uid">the User ID</param>
 /// <param name="worksetID">the Workset ID</param>
 /// <returns></returns>
 public static bool OwnsWorkset(int uid, int worksetID)
 {
     return(DatabaseConnector.OwnsWorkset(uid, worksetID));
 }
		public void LoadMultipleRowsWithEnumProperty() {

			string query = @"SELECT Merchant.Name, Merchant.Status FROM Merchant WHERE Merchant.MerchantId IN (1, 2) ORDER BY Merchant.MerchantId;";

			IEnumerable<MerchantData> actual = null;

			using (DatabaseConnector databaseConnector = new DatabaseConnector(connectionString)) {

				actual = databaseConnector.ExecuteReaderFetchAll<MerchantData>(query);
			}

			Assert.IsNotNull(actual);
			Assert.AreEqual(2, actual.Count());

			Assert.AreEqual(StatusType.Created, actual.ElementAt(0).Status);
			Assert.AreEqual(StatusType.Disabled, actual.ElementAt(1).Status);
		}
 /// <summary>
 /// Gets the user based on their username and the organisation they are a part of.
 /// It used to do more before I tranfered my queries to one file
 /// but I have left if so I can keep all user information in one file.
 /// </summary>
 /// <param name="username">The username of the user</param>
 /// <param name="organisationID"></param>
 /// <returns></returns>
 public static Users GetUser(string username, int organisationID)
 {
     return(DatabaseConnector.GetUser(username, organisationID));
 }
		public void LoadSingleRowWithInvalidEnumProperty() {

			string query = @"SELECT Merchant.Name, Merchant.Status FROM Merchant WHERE Merchant.MerchantId = 3;";

			MerchantData actual = null;

			using (DatabaseConnector databaseConnector = new DatabaseConnector(connectionString)) {

				actual = databaseConnector.ExecuteReaderFetchAll<MerchantData>(query).FirstOrDefault();
			}
		}
示例#37
0
 public UserAccountDL()
 {
     _dbConnector = new DatabaseConnector();
 }
		public void LoadSingleRowWithEnumParameter() {

			string query = @"SELECT Merchant.Name FROM Merchant WHERE Merchant.Status = @Status;";

			MerchantData actual = null;

			using (DatabaseConnector databaseConnector = new DatabaseConnector(connectionString)) {

				actual = databaseConnector.ExecuteReaderFetchAll<MerchantData>(query, new { Status = StatusType.Disabled }).FirstOrDefault();
			}

			Assert.IsNotNull(actual);
			Assert.AreEqual("Another Merchant", actual.Name);
		}
        public override string GetHtml()
        {
            var html = string.Empty;

            List <Tuple <DateTime, int> > values = DatabaseConnector.GetStepsPerTimeFraction(DateTimeHelper.GetStartOfDay(_date), DateTimeHelper.GetEndOfDay(_date), MINUTES_PER_BAR);

            if (values.FindAll(x => x.Item2 != 0).Count < 1)
            {
                html += VisHelper.NotEnoughData();
                return(html);
            }

            //CSS
            html += "<style>";

            html += ".axis path,.axis line {";
            html += "fill: none;";
            html += "stroke: #000;";
            html += "shape - rendering: crispEdges;";
            html += "}";

            html += ".axis text {";
            html += "}";

            html += ".tick {";
            html += "stroke - dasharray: 1, 2;";
            html += "}";

            html += ".bar {";
            html += "fill: FireBrick;";
            html += "}";

            html += "</style>";

            //HTML
            html += "<svg id='visualisation'></svg>";
            html += "<p style='text-align: center; font-size: 0.66em;'>Hint: Visualizes your steps per " + MINUTES_PER_BAR + " minutes. For more detailed information, visit: <a href='http://fitbit.com' target=_blank>fitbit.com</a>. (Last synced: " + DatabaseConnector.GetLastTimeSynced() + ").</p>";

            //SCRIPT
            html += "<script>";

            html += "InitChart();";

            html += "function InitChart() {";

            html += GenerateJSData(values);

            html += "var actualHeight = document.getElementsByClassName('item Wide')[0].offsetHeight;";
            html += "var actualWidth = document.getElementsByClassName('item Wide')[0].offsetWidth;";
            html += "var vis = d3.select('#visualisation'),";
            html += "WIDTH = actualWidth, HEIGHT = actualHeight * 0.75,";
            html += "MARGINS = {top: 20, right: 20, bottom: 20, left: 50";
            html += "},";

            html += "xRange = d3.scale.ordinal().rangeRoundBands([MARGINS.left, WIDTH - MARGINS.right], 0.1).domain(barData.map(function(d) {";
            html += "return d.x;";
            html += "})),";

            html += "yRange = d3.scale.linear().range([HEIGHT - MARGINS.top, MARGINS.bottom]).domain([0,";
            html += "d3.max(barData, function(d) {";
            html += "return d.y;";
            html += "})]),";

            html += "xAxis = d3.svg.axis()";
            html += ".scale(xRange)";
            html += ".tickValues([" + GenerateTicks(values) + "])";
            html += ".tickSize(5),";

            html += "yAxis = d3.svg.axis().scale(yRange).tickSize(5).orient('left').tickSubdivide(true);";

            html += "vis.attr('height', HEIGHT).attr('width', WIDTH);";
            html += "vis.append('svg:g').attr('class', 'x axis').attr('transform', 'translate(0,' + (HEIGHT - MARGINS.bottom) + ')').call(xAxis);";
            html += "vis.append('svg:g').attr('class', 'y axis').attr('transform', 'translate(' + (MARGINS.left) + ',0)').call(yAxis);";

            html += "vis.selectAll('rect').data(barData).enter().append('rect').attr('x', function(d) {";
            html += "return xRange(d.x);";
            html += "})";
            html += ".attr('y', function(d) {";
            html += "return yRange(d.y);";
            html += "})";
            html += ".attr('width', xRange.rangeBand())";
            html += ".attr('height', function(d) {";
            html += "return ((HEIGHT - MARGINS.bottom) - yRange(d.y));";
            html += "})";
            html += ".attr('fill', '" + Shared.Settings.RetrospectionColorHex + "')";
            html += ".on('mouseover', function(d) {";
            html += "d3.select(this).attr('fill', '" + Shared.Settings.GrayColor + "');";
            html += "document.getElementById(d.x).style.opacity='0';";
            html += "document.getElementById('average').style.opacity='1';";
            html += "document.getElementById('avg' + d.x).style.opacity='1';";
            html += "})";
            html += ".on('mouseout', function(d) {";
            html += "d3.select(this)";
            html += ".attr('fill', '" + Shared.Settings.RetrospectionColorHex + "');";
            html += "document.getElementById(d.x).style.opacity='1';";
            html += "document.getElementById('average').style.opacity='0';";
            html += "document.getElementById('avg' + d.x).style.opacity='0';";
            html += "});";

            html += "var valueLine1 = d3.svg.line().x(function(d) {return xRange(d.x); }).y(function(d) { return yRange(d.a); });";
            html += "vis.append('path').style('stroke', '" + Shared.Settings.RetrospectionColorHex + "').attr('d', valueLine1(barData)).attr('fill', 'none').attr('id', 'average').attr('opacity', 0);";

            html += "vis.selectAll('avgText').data(barData).enter().append('text')";
            html += ".attr('x', function(d){return xRange(d.x) + xRange.rangeBand() / 2;})";
            html += ".attr('y', function(d){return yRange(d.a) - 5;})";
            html += ".attr('fill', '" + Shared.Settings.RetrospectionColorHex + "')";
            html += ".attr('text-anchor', 'middle')";
            html += ".attr('id', function(d){return 'avg' + d.x;})";
            html += ".attr('opacity', 0)";
            html += ".text(function(d){return (d.y - d.a).toFixed(0);});";

            html += "vis.selectAll('legText').data(barData).enter().append('text').attr('x', function(d) {";
            html += "return xRange(d.x) + xRange.rangeBand() / 2;";
            html += "})";
            html += ".attr('id', function(d) {";
            html += "return d.x";
            html += "})";
            html += ".attr('text-anchor', 'middle')";
            html += ".attr('fill', 'black')";
            html += ".attr('y', function(d) {";
            html += "return yRange(d.y) - 5;";
            html += "})";
            html += ".text(function(d) {";
            html += "if (d.y > 0) {";
            html += "return d.y;}";
            html += "else{return '';}})";
            html += ";}";

            html += "</script>";

            return(html);
        }
		public void ParseIntValueToBooleanProperty() {

			string query = @"SELECT Merchant.MerchantId FROM Merchant;";

			IEnumerable<MerchantBool> actual = null;

			using (DatabaseConnector databaseConnector = new DatabaseConnector(connectionString)) {

				actual = databaseConnector.ExecuteReaderFetchAll<MerchantBool>(query);
			}

			Assert.IsNotNull(actual);
			Assert.AreEqual(3, actual.Count());
			Assert.IsFalse(actual.Any(p => p.MerchantId == false));
		}
示例#41
0
        public void Init_DatabaseConnector_Class()
        {
            DatabaseConnector databaseConnector = new DatabaseConnector();

            Assert.IsNotNull(databaseConnector);
        }
		public void SearchWithEmptyStringParameter() {

			string query = @"SELECT Merchant.MerchantId FROM Merchant WHERE Merchant.Name = @Name;";

			IEnumerable<MerchantData> actual = null;

			using (DatabaseConnector databaseConnector = new DatabaseConnector(connectionString)) {

				actual = databaseConnector.ExecuteReaderFetchAll<MerchantData>(query, new { Name = string.Empty });
			}

			Assert.IsNotNull(actual);
			Assert.IsFalse(actual.Any());
		}
示例#43
0
        /// <summary>
        /// Thêm mới sử dụng connnector là tham số đầu vào Trả về số bản ghi thành công
        /// </summary>
        /// <param name="entity"></param>
        /// <param name="databaseConnector"></param>
        /// <returns></returns>
        protected virtual async Task <object> InsertAndReturnNumberRecordEffect(T entity, DatabaseConnector databaseConnector)
        {
            var storeName = DatabaseUtility.GeneateStoreName <T>(ProcdureTypeName.Insert);
            var result    = await SaveChangeAndReturnRecordEffect(databaseConnector, storeName, entity);

            return(result);
        }
		public void BulkInsertAttribute() {

			IList<BulkDataAttribute> source = new List<BulkDataAttribute>();

			int dataCount = 100;

			DateTime currentDate = DateTime.UtcNow;

			for (int i = 0; i < dataCount; i++) {

				BulkDataAttribute bulkDataAttribute = new BulkDataAttribute();

				bulkDataAttribute.Banana = string.Format("Name-{0}", i);

				if (i % 2 == 0) { bulkDataAttribute.Maca = i.ToString(); }

				bulkDataAttribute.Goiaba = currentDate;

				source.Add(bulkDataAttribute);
			}

			string query = @"DELETE FROM BulkData;";

			int actual = 0;

			using (DatabaseConnector databaseConnector = new DatabaseConnector(connectionString)) {

				// Limpa qualquer informação pré-existente.
				databaseConnector.ExecuteNonQuery(query);

				// Insere os registros.
				databaseConnector.BulkInsert("BulkData", source);

				// Exclui os registros e armazena a quantidade excluída.
				actual = databaseConnector.ExecuteNonQuery(query);
			}

			Assert.AreEqual(dataCount, actual);
		}
示例#45
0
        /// <summary>
        /// Thêm mới và trả về kết quả từ store
        /// Chưa commit transition
        /// </summary>
        /// <param name="procedureName"></param>
        /// <param name="entity"></param>
        /// <param name="databaseConnector"></param>
        /// <returns></returns>
        protected virtual async Task <object> InsertAndReturnSingleValue(string procedureName, T entity, DatabaseConnector databaseConnector)
        {
            var value = await SaveChangeAndReturnSingleValue(databaseConnector, procedureName, entity);

            return(value);
        }
		public void BulkInsertMissingMandatoryField() {

			IList<BulkData> source = new List<BulkData>();

			int dataCount = 1;

			DateTime currentDate = DateTime.UtcNow;

			for (int i = 0; i < dataCount; i++) {

				BulkData bulkData = new BulkData();

				bulkData.Name = string.Format("Name-{0}", i);

				if (i % 2 == 0) { bulkData.Value = i.ToString(); }

				source.Add(bulkData);
			}

			using (DatabaseConnector databaseConnector = new DatabaseConnector(connectionString)) {

				// Insere os registros.
				databaseConnector.BulkInsert("BulkData", source);
			}
		}
示例#47
0
 //Set data
 public async void setProductInDB(clsProduct pProduct)
 {
     DatabaseResponse dbres = await DatabaseConnector.putDataAsync("/products", pProduct.UID, pProduct);
 }
		public void BulkInsertEmptyTableName() {

			using (DatabaseConnector databaseConnector = new DatabaseConnector(connectionString)) {

				databaseConnector.BulkInsert(string.Empty, new List<int>());
			}
		}
示例#49
0
 //Delete data
 public async void deleteProductFromDB(clsProduct pProduct)
 {
     DatabaseResponse dbres = await DatabaseConnector.deleteDataAsync("/products", pProduct.UID, pProduct);
 }
		public void BulkInsertNullCollection() {

			using (DatabaseConnector databaseConnector = new DatabaseConnector(connectionString)) {

				databaseConnector.BulkInsert("BulkData", null);
			}
		}
示例#51
0
        public MainWindowViewModel()
        {
            // Display version
            Version version = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version;

            // Version increases each day, since 10/10/2018
            VersionNr = $"{version.Major}.{version.MajorRevision}.{version.Build}";

            // Read eventually unsent data
            StartupAndReadUnsentData();

            // Initialize connection status string
            SqlConnectionStatus = ModbusConnectionStatus = "Disconnected";

            XDocument doc = new XDocument();

            try
            {
                doc = XDocument.Load("mb_config.xml");
            }
            catch
            {
                GlobalCommands.ShowError.Execute(new Exception("Impossible to load XML configuration file."));
            }

            var mb = doc.Root.Descendants("Modbus");
            var sq = doc.Root.Descendants("MySql");

            string mbaddr = ParseXmlElement(mb.Elements("addr").Nodes());
            string mbport = ParseXmlElement(mb.Elements("port").Nodes());
            string mbfreq = ParseXmlElement(mb.Elements("data_frequency_sec").Nodes());

            string sqladdr      = ParseXmlElement(sq.Elements("addr").Nodes());
            string sqlname      = ParseXmlElement(sq.Elements("db_name").Nodes());
            string sqltablename = ParseXmlElement(sq.Elements("table_name").Nodes());
            string sqlusername  = ParseXmlElement(sq.Elements("username").Nodes());
            string sqlpass      = ParseXmlElement(sq.Elements("pwd").Nodes());

            MbConnector = new ModbusConnector(new ModbusCfg()
            {
                Address = mbaddr,
                Port    = Convert.ToInt16(mbport),
                Freq    = Convert.ToInt16(mbfreq)
            });

            DbConnector = new DatabaseConnector(new SqlCfg()
            {
                Address   = sqladdr,
                DBname    = sqlname,
                TableName = sqltablename,
                Username  = sqlusername,
                Password  = sqlpass
            });

            MbConnector.OnDataReceivedEvent    += new EventHandler(MbDataReceived);
            MbConnector.ConnectionChangedEvent += new EventHandler(MbConnectionStatusChanged);
            MbConnector.ErrorEvent             += new EventHandler(MbErrorHandler);
            MbConnector.OnAlarmReceivedEvent   += new EventHandler(MbAlarmReceived);
            DbConnector.OnDataTransmittedEvent += new EventHandler(SqlDataTransmitted);
            DbConnector.ConnectionChangedEvent += new EventHandler(SqlConnectionStatusChanged);
            DbConnector.ErrorEvent             += new EventHandler(SqlErrorHandler);

            MbConnectorTh = new Thread(MbConnector.ModbusConnectorThread);
            MbConnectorTh.IsBackground = true;
            MbConnectorTh.Start();
            DbConnectorTh = new Thread(DbConnector.DatabaseConnectorThread);
            DbConnectorTh.IsBackground = true;
            DbConnectorTh.Start();

            // Refresh queue counter
            MbRxDataCounter  = 0.ToString();
            SqlTxDataCounter = 0.ToString();

            Thread RefreshQueueCounterTh = new Thread(RefreshQueueCounter);

            RefreshQueueCounterTh.IsBackground = true;
            RefreshQueueCounterTh.Start();

            Thread RefreshJobStatusTh = new Thread(RefreshJobStatus);

            RefreshJobStatusTh.IsBackground = true;
            RefreshJobStatusTh.Start();
        }
		public void LoadPagedData() {

			string query = @"SELECT Merchant.Name, Merchant.MerchantId, Merchant.MerchantKey FROM Merchant;";

            PagedResult<MerchantData> actual;

			using (DatabaseConnector databaseConnector = new DatabaseConnector(connectionString)) {

				actual = databaseConnector.ExecuteReader<MerchantData>(query, 1, 2, "MerchantId", SortDirection.DESC);
			}

			Assert.AreEqual(3, actual.TotalRecords);
			Assert.IsNotNull(actual.Data);
			Assert.AreEqual(2, actual.Data.Count());

			Assert.AreEqual(3, actual.Data.ElementAt(0).MerchantId);
			Assert.AreEqual(2, actual.Data.ElementAt(1).MerchantId);
		}
        public IActionResult CreateUser(SignUp obj)
        {
            if (DatabaseConnector.signeduser.id != -1)
            {
                DatabaseConnector db = new DatabaseConnector();
                if (ModelState.IsValid)
                {
                    if (db.isUsernameValid(obj.username))
                    {
                        if (db.checkEmail(obj.email))
                        {
                            if (obj.password.Length >= 8)
                            {
                                if (obj.password == obj.retypePassword)
                                {
                                    if (db.isUsernameExist(obj.username, -1, false))
                                    {
                                        ModelState.AddModelError("username", "This username is already taken..!");
                                        return(View());
                                    }
                                    else
                                    {
                                        if (db.isEmailExist(obj.email, -1, false))
                                        {
                                            ModelState.AddModelError("email", "Already Account Exists on this Email..!");
                                            return(View());
                                        }
                                        else
                                        {
                                            User user = new User();
                                            user.username = obj.username;
                                            user.password = obj.password;
                                            user.email    = obj.email;
                                            if (obj.myImage != null)
                                            {
                                                string filename  = Path.GetFileName(obj.myImage.FileName);
                                                string extension = Path.GetExtension(obj.myImage.FileName);
                                                string filepath  = Path.Combine("C:/Users/Abid Shafique/Desktop/Assignment no 3/Assignment no 3/wwwroot/ProfileImages/", user.username + extension);
                                                using (FileStream stream = new FileStream(filepath, FileMode.Create))
                                                {
                                                    obj.myImage.CopyTo(stream);
                                                }
                                                user.imageName = filename;
                                            }

                                            db.AddUserInDBMS(user);
                                            return(View("HomePage", db.getAllUsers()));
                                        }
                                    }
                                }
                                else
                                {
                                    ModelState.AddModelError("retypePassword", "Retype Password doesn't match with Password..!");
                                    return(View());
                                }
                            }
                            else
                            {
                                ModelState.AddModelError("password", "Password must be of at least 8 Characters..!");
                                return(View());
                            }
                        }
                        else
                        {
                            ModelState.AddModelError("email", "Entered Email is not in Correct Format");
                            return(View());
                        }
                    }
                    else
                    {
                        ModelState.AddModelError("username", "Enter Usename without Space");
                        return(View());
                    }
                }
                else
                {
                    return(View());
                }
            }
            else
            {
                return(View("Index"));
            }
        }
示例#54
0
        public ExperimentSimulator(DatabaseConnector databaseConnector)
        {
            Claws.NotNull(() => databaseConnector);

            this.databaseConnector = databaseConnector;
        }
示例#55
0
 public BaseController()
 {
     _dbConnector = new DatabaseConnector();
 }
 /// <summary>
 /// Checks to see if the user is in a specific role
 /// It used to do more before I tranfered my queries to one file
 /// but I have left if so I can keep all user information in one file
 /// making it easier to access.
 /// </summary>
 /// <param name="uid">UserID as an int</param>
 /// <param name="roleName">The name of the role</param>
 /// <returns></returns>
 public static bool UserInRole(int uid, string roleName)
 {
     return(DatabaseConnector.UserInRole(uid, roleName));
 }
示例#57
0
 /// <summary>
 /// Lưu lại các thay đổi (thêm mới hoặc sửa)
 /// </summary>
 /// <param name="databaseConnector"></param>
 /// <param name="procedureName"></param>
 /// <param name="entity"></param>
 /// <returns></returns>
 private Task <object> SaveChangeAndReturnSingleValue <T>(DatabaseConnector databaseConnector, string procedureName, T entity)
 {
     databaseConnector.MapParameterValueAndEntityProperty <T>(procedureName, entity);
     return(databaseConnector.ExecuteScalar());
 }
 /// <summary>
 /// Checks to see if the user has rights to view the workset
 /// This includes checking if they own the workset or
 /// are just a student in that group trying to view that workset.
 /// It used to do more before I tranfered my queries to one file
 /// but I have left if so I can keep all user information in one file
 /// making it easier to access.
 /// </summary>
 /// <param name="uid">User id</param>
 /// <param name="worksetID">Id of the workset</param>
 /// <returns>Whether the student has the right to view that workset</returns>
 public static bool UserHasBasicAccess(int uid, int worksetID)
 {
     return(DatabaseConnector.OwnsWorkset(uid, worksetID) || DatabaseConnector.HasAccessTo(uid, worksetID));
 }
示例#59
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env, IConfiguration configuration, DatabaseConnector databaseConnector, ISongChooser songChooser)
        {
            databaseConnector.Setup(configuration["SongDatabase:Server"], configuration["SongDatabase:Database"],
                                    configuration["SongDatabase:User"], configuration["SongDatabase:Password"]);
            songChooser.SetDatabaseConnection(databaseConnector);

            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseDefaultFiles()
            .UseStaticFiles()
            .UseWebSockets()
            .UseRouting()
            .UseAuthorization()
            .UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });

            // app.UseHttpsRedirection();
        }
		public void LoadRowWithEmptyQuery() {

			using (DatabaseConnector databaseConnector = new DatabaseConnector(connectionString)) {
				databaseConnector.ExecuteReaderFetchAll<int>(string.Empty);
			}
		}