private static void InsertGenesisStudent(FullStudent fullStudent, IDatabaseConnector dbConnector) { // no record returned, add the genesis block // generate previous node hash for genesis student // generate genesis student hash, and salthash and combined hash BasicStudent genesisStudent = StudentMapper.GenesisStudentNode(); // SHA512 hash of 512 for the previous for genesisStudent string hashForGenesisStudentPrevious = Hash.GetHashString("Test");// Hash.GetBCryptHashAutoSalt("Test"); string genesisStudentSerialized = JsonConvert.SerializeObject(genesisStudent); string genesisStudentHash = Hash.GetHashString(genesisStudentSerialized); Console.WriteLine($"Genesis studnet"); Console.WriteLine(genesisStudentSerialized); string[] genesissaltAndSaltHashArray = Hash.GetRandomSaltWithHash(); string genesissalt = genesissaltAndSaltHashArray[0]; string genesissaltHash = genesissaltAndSaltHashArray[1]; string genesisstudentHashPlusSaltHash = Hash.GetHashString(genesisStudentHash + genesissaltHash); fullStudent = StudentMapper.Map(genesisStudent, hashForGenesisStudentPrevious, genesisstudentHashPlusSaltHash, genesissalt); // add the full hash of the previous student fullStudent.PreviousFullRecordHash = hashForGenesisStudentPrevious; HttpStatusCode genesisrecordInsertedStatusCode = dbConnector.InsertStudentRecord(fullStudent); }
public static FullStudent Map(BasicStudent basicStudent, string prevRecordHash, string currentNodeHash, string salt, int id = 1) { FullStudent fullStudent = new FullStudent { FirstName = basicStudent.FirstName, MiddleName = basicStudent.MiddleName, LastName = basicStudent.LastName, DateOfBirth = basicStudent.DateOfBirth, Organization = basicStudent.Organization, SchoolDivision = basicStudent.SchoolDivision, Degree = basicStudent.Degree, Awarded = basicStudent.Awarded, Major = basicStudent.Major, RecordId = id, PreviousRecordHash = prevRecordHash, CurrentNodeHash = currentNodeHash, Salt = salt }; // set id, // set previous recordhash // set currentnodehash return(fullStudent); }
private async void retrieveStudentButton_Click(object sender, EventArgs e) { if (firstName.Text.Length == 0 || middleName.Text.Length == 0 || lastName.Text.Length == 0) { MessageBox.Show("The name fields cannot be empty!"); return; } List <FullStudent> students = await GetAllFullStudents(); Func <FullStudent, bool> predicate = x => x.FirstName == firstName.Text && x.LastName == lastName.Text && x.MiddleName == middleName.Text; try { FullStudent fullStudent = students.First(predicate); if (fullStudent != null) { string fullStudentJSON = JsonConvert.SerializeObject(fullStudent); BasicStudent basicStudent = StudentMapper.FullStudentToBasicStudent(fullStudent); string basicStudentJSON = JsonConvert.SerializeObject(basicStudent); basicStudentTextBox.Text = basicStudentJSON; fullStudentTextBox.Text = fullStudentJSON; } } catch (Exception exp) { MessageBox.Show(exp.Message); } }
public static string GetHTMLString(BasicStudent student) { string fullname = $"{student.FirstName} {student.MiddleName} {student.LastName}"; string output = $"<style>#header{{text-align:center}}h1{{color:red}} .title{{color:black}}</style><div id=\"header\"><h1>California State University, Northridge</h1><h1 class=\"title\">DegreeVerify Certificate</h1><hr><h4>Date Requested:</h4> {DateTime.Now}<hr></div><div id=mainBody><h3>Information Verified</h3><br><br><p><h5>Name on School's Records:</h5>{fullname} <br><h5>Date Awarded:</h5> {student.Awarded.ToShortDateString()}<br><h5>Degree Title:</h5> {student.Degree}<br><h5>Name of School:</h5> {student.Organization}<br><h5>School Division:</h5> {student.SchoolDivision} <br><h5>Major Course(s) of Study:</h5> {student.Major}<br></div>"; return(output); }
public Pdf(BasicStudent student, IConverter converter) { Title = $"{student.FirstName} {student.MiddleName} {student.LastName} Academic Records"; Converter = converter; htmlData = TemplateGenerator.GetHTMLString(student); setDocumentSettings(); }
private void LoadJson(string filename) { using (StreamReader reader = new StreamReader(filename)) { string json = reader.ReadToEnd(); basicStudent = JsonConvert.DeserializeObject <BasicStudent>(json); } }
public dynamic GetFullStudentRecordFromName(BasicStudent student) { string query = $"SELECT * FROM c where c.FirstName='{student.FirstName}' and c.MiddleName='{student.MiddleName}' and c.LastName='{student.LastName}'"; dynamic document = client.CreateDocumentQuery <dynamic>( UriFactory.CreateDocumentCollectionUri(PreviousDatabaseName, PreviousTableName), query ).AsEnumerable().FirstOrDefault(); return(document); }
public ActionResult Edit(BasicStudent std) { //update student in DB using EntityFramework in real-life application //update list by removing old student and adding updated student for demo purpose var student = studentList.Where(s => s.StudentId == std.StudentId).FirstOrDefault(); studentList.Remove(student); studentList.Add(std); return(RedirectToAction("Index")); }
string CalculateCurrentFullStudentHash(FullStudent currentFullStudent) { BasicStudent currentBasicStudent = StudentMapper.FullStudentToBasicStudent(currentFullStudent); string currentBasic = JsonConvert.SerializeObject(currentBasicStudent); string currentBasicHash = Hash.GetHashString(currentBasic); string currentSalt = currentFullStudent.Salt; string currentSaltHash = Hash.GetHashString(currentSalt); string fullHash = Hash.GetHashString(currentBasicHash + currentSaltHash); return(fullHash); }
public static BasicStudent GenesisStudentNode() { BasicStudent basicStudent = new BasicStudent { FirstName = "Matty", MiddleName = "the", LastName = "Matador", DateOfBirth = DateTime.UnixEpoch, Organization = "California State University - Northridge", SchoolDivision = "College of Eng/ Comp Sci", Degree = "Master of Science", Awarded = DateTime.UnixEpoch, Major = "Computer Science", }; return(basicStudent); }
public static BasicStudent FullStudentToBasicStudent(FullStudent fullStudent) { BasicStudent basicStudent = new BasicStudent() { FirstName = fullStudent.FirstName, MiddleName = fullStudent.MiddleName, LastName = fullStudent.LastName, DateOfBirth = fullStudent.DateOfBirth, Organization = fullStudent.Organization, SchoolDivision = fullStudent.SchoolDivision, Degree = fullStudent.Degree, Awarded = fullStudent.Awarded, Major = fullStudent.Major }; return(basicStudent); }
private void generateRecord_Click(object sender, EventArgs e) { if (firstName.Text.Length == 0 || middleName.Text.Length == 0 || lastName.Text.Length == 0) { MessageBox.Show("Enter the text in the missing fields please"); return; } BasicStudent tempStudent = new BasicStudent() { FirstName = firstName.Text.CapitalizeEveryLetterOnSplit(' '), MiddleName = middleName.Text.CapitalizeEveryLetterOnSplit(' '), LastName = lastName.Text.CapitalizeEveryLetterOnSplit(' '), DateOfBirth = dateOfBirthPicker.Value, Organization = organization.Text, SchoolDivision = schoolDivision.Text, Degree = degree.Text, Awarded = dateAwarded.Value, Major = major.Text }; // serialize JSON directly to a file string directoryName = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); string filename = $"{tempStudent.FirstName}{tempStudent.MiddleName}{tempStudent.LastName}.json"; using (StreamWriter file = File.CreateText($@"{directoryName}/{filename}")) { JsonSerializer serializer = new JsonSerializer(); serializer.Serialize(file, tempStudent); MessageBox.Show("File generated"); this.Close(); } }
public static async Task <HttpResponseMessage> Run( [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req, ILogger log) { log.LogInformation("C# HTTP trigger function processed a request."); string requestBody = await new StreamReader(req.Body).ReadToEndAsync(); BasicStudent studentToAdd = JsonConvert.DeserializeObject <BasicStudent>(requestBody); // When returning, lets return the full student so that it may be tested further var json = JsonConvert.SerializeObject(studentToAdd, Formatting.Indented); var successMessageToReturn = new HttpResponseMessage(HttpStatusCode.Created) { Content = new StringContent(json, Encoding.UTF8, "application/json") }; var failureMessageToReturn = new HttpResponseMessage(HttpStatusCode.NotFound); var url = Environment.GetEnvironmentVariable("cosmosUrl"); var accessKey = Environment.GetEnvironmentVariable("cosmosAccesskey"); IDatabaseConnector dbConnector = new CosmosConnector(url, accessKey); HttpStatusCode databaseCreatedSuccessfulyStatusCode = await dbConnector.CreateDataBase("StudentDatabase"); HttpStatusCode tableCreatedSuccessfullyStatusCode = await dbConnector.CreateTable(dbConnector.PreviousDatabaseName, "StudentRecords"); // last record holds the last inserted record var lastRecord = await dbConnector.GetLastAddedStudentRecordByStudentId(); FullStudent fullStudentToAdd = null; bool addingForFirstTime = false; // if no record was retrieved (empty database, insert genesis block) if (lastRecord.Count == 0) { InsertGenesisStudent(fullStudentToAdd, dbConnector); addingForFirstTime = true; } if (addingForFirstTime) { // If we are adding for the first time, lets get the record of the last student added from the database lastRecord = await dbConnector.GetLastAddedStudentRecordByStudentId(); } string studentToAddSerialized = JsonConvert.SerializeObject(studentToAdd); string studentToAddHash = Hash.GetHashString(studentToAddSerialized); string[] saltAndSaltHashArray = Hash.GetRandomSaltWithHash(); string salt = saltAndSaltHashArray[0]; string saltHash = saltAndSaltHashArray[1]; string studentHashPlusSaltHash = Hash.GetHashString(studentToAddHash + saltHash); dynamic previousRecord = lastRecord[0]; var dict = (IDictionary <string, object>)previousRecord; string previousRecordHash = dict["CurrentNodeHash"] as string; int previousRecordId = Convert.ToInt32(dict["RecordId"]); fullStudentToAdd = StudentMapper.Map(studentToAdd, previousRecordHash, studentHashPlusSaltHash, salt, previousRecordId + 1); //string previousstudentfullhash = dict["PreviousFullRecordHash"] as string; // calculate out the full record hash of the previous full student FullStudent previousFullStudent = StudentMapper.DictionaryObjectToFullStudent(dict); string previousFullStudentSerialized = JsonConvert.SerializeObject(previousFullStudent); Console.WriteLine(previousFullStudentSerialized); string previousFullBCryptHash = Hash.GetHashString(previousFullStudentSerialized);//Hash.GetBCryptHashAutoSalt(previousFullStudentSerialized); // save the full hash of the previous student fullStudentToAdd.PreviousFullRecordHash = previousFullBCryptHash; HttpStatusCode recordInsertedStatusCode = dbConnector.InsertStudentRecord(fullStudentToAdd); if (recordInsertedStatusCode == HttpStatusCode.Created) { return(successMessageToReturn); } else { return(failureMessageToReturn); } }
private async void startVerifyButton_Click(object sender, EventArgs e) { progressBar1.Value = 25; List <FullStudent> students = await GetAllFullStudents(); progressBar1.Value = 50; Console.WriteLine($"Total records: {students.Count}"); string student1 = ""; string student2 = ""; numOfRecords.Text = students.Count.ToString(); // now that we have the fullstudent records, we can start the verfication of them all BasicStudent genesisStudent = StudentMapper.GenesisStudentNode(); // start at the end of the records and then recalculate the hash of the node and check if it matches with the one on record // then recalculate the hash of the previous node and check to see if it matches with the currents previous on record // if both are valid, then the record is considered to be valid // otherwise, the record is invalid // Print some debug info alongside bool valid = true; for (int i = students.Count - 1; i >= 0; i--) { bool currentHashMatch = true; bool previousHashMatch = true; bool previousFullHashMatch = true; FullStudent currentFullStudent = students[i]; Console.WriteLine($"Current Student: {currentFullStudent.FirstName}"); string recalculatedCurrentNodeHash = CalculateCurrentFullStudentHash(currentFullStudent); if (recalculatedCurrentNodeHash != currentFullStudent.CurrentNodeHash) { currentHashMatch = false; } if (i == 0) { Console.WriteLine($"Genesis Node Previous: Test"); string previousGenesisHash = Hash.GetHashString("Test"); if (currentFullStudent.PreviousRecordHash != previousGenesisHash) { previousHashMatch = false; } if (previousGenesisHash != currentFullStudent.PreviousFullRecordHash) { previousFullHashMatch = false; } } else { FullStudent previousFullStudent = students[i - 1]; Console.WriteLine($"Previous Student: {previousFullStudent.FirstName}"); string recalculatedPreviousNodeHash = CalculateCurrentFullStudentHash(previousFullStudent); if (currentFullStudent.PreviousRecordHash != recalculatedPreviousNodeHash) { previousHashMatch = false; student2 = previousFullStudent.FirstName; } // new string previousFullHashObject = JsonConvert.SerializeObject(previousFullStudent); string previousFullHash = Hash.GetHashString(previousFullHashObject); if (previousFullHash != currentFullStudent.PreviousFullRecordHash) { previousFullHashMatch = false; } } if (!currentHashMatch || !previousHashMatch || !previousFullHashMatch) // also check the fullnodehashmatch { valid = false; student1 = currentFullStudent.FirstName; break; } } progressBar1.Value = 100; if (valid) { MessageBox.Show("Hash Verified and Unmodified", "Success"); } else { if (student2.Length == 0) { MessageBox.Show($"Hash mismatch on {student1}", "Error"); } else { MessageBox.Show($"Hash mismatch on {student1} and {student2}", "Error"); } } }
public HttpStatusCode InsertStudentRecord(BasicStudent student) { var response = this.CreateStudentocumentIfNotExists(PreviousDatabaseName, PreviousTableName, student).GetAwaiter().GetResult(); return(response); }
private async Task <HttpStatusCode> CreateStudentocumentIfNotExists(string databaseName, string collectionName, BasicStudent student) { var response = await this.client.CreateDocumentAsync(UriFactory.CreateDocumentCollectionUri(databaseName, collectionName), student); var statusCode = response.StatusCode; return(statusCode); }
public static async Task <HttpResponseMessage> Run( [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req, ILogger log, ExecutionContext context) { log.LogInformation($"C# HTTP trigger function processed request #{++count}."); bool isLocal = UtilityFunctions.UtilityFunctions.IsLocalEnvironment(); string response = isLocal ? "Function is running on local environment." : "Function is running on Azure."; Console.WriteLine(response); // load the connection string for the db var config = new ConfigurationBuilder() .SetBasePath(context.FunctionAppDirectory) .AddJsonFile("local.settings.json", optional: true, reloadOnChange: true) .AddEnvironmentVariables() .Build(); string requestBody = await new StreamReader(req.Body).ReadToEndAsync(); dynamic data = JsonConvert.DeserializeObject(requestBody); Student student = JsonConvert.DeserializeObject <Student>(requestBody); student.FirstName = student.FirstName.CapitalizeEveryLetterOnSplit(' '); student.MiddleName = student.MiddleName.CapitalizeEveryLetterOnSplit(' '); student.LastName = student.LastName.CapitalizeEveryLetterOnSplit(' '); // search the cosmosdb for the record and then grab the record dynamic studentCosmosRecord; string uri = config.GetConnectionString("address"); string accessKey = config.GetConnectionString("accessKey"); using (CosmosConnector dbConnector = new CosmosConnector(uri, accessKey)) { dbConnector.UseDataBase("StudentDatabase"); dbConnector.UseTableName("StudentRecords"); studentCosmosRecord = dbConnector.GetFullStudentRecordFromName(student); } dynamic previousRecord = studentCosmosRecord; var dict = (IDictionary <string, object>)previousRecord; BasicStudent basicStudent = new BasicStudent() { FirstName = dict["FirstName"] as string, MiddleName = dict["MiddleName"] as string, LastName = dict["LastName"] as string, DateOfBirth = (DateTime)dict["DateOfBirth"], Organization = dict["Organization"] as string, SchoolDivision = dict["SchoolDivision"] as string, Degree = dict["Degree"] as string, Awarded = (DateTime)dict["Awarded"], Major = dict["Major"] as string }; // send the record data to the pdf template generator and generate pdf Pdf studentPdf = new Pdf(basicStudent, converter); string pdfOutput = studentPdf.SaveToBase64String(); // send pdf back as response object dataToSendBack = new { Pdf = pdfOutput }; var json = JsonConvert.SerializeObject(dataToSendBack, Formatting.Indented); var successMessageToReturn = new HttpResponseMessage(HttpStatusCode.Accepted) { Content = new StringContent(json, Encoding.UTF8, "application/json") }; var failureMessageToReturn = new HttpResponseMessage(HttpStatusCode.NotFound); return(student.FirstName != null ? successMessageToReturn : failureMessageToReturn); }