public string Get(string id) { string result = ""; try { using (WorkProtectionEntities entities = new WorkProtectionEntities()) { var userData = entities.PatientTable.FirstOrDefault(e => e.JobTabNumber == id); Guid ident = userData.Guid; string surname = userData.LastName; string name = userData.FirstName; string patronymic = userData.MiddleName; string profession = userData.Profession; if (String.IsNullOrEmpty(profession)) { result = "Пользователь не найден"; } else { UserInfo userInfo = new UserInfo(ident, surname, name, patronymic, profession); result = JsonConvert.SerializeObject(userInfo); } } } catch (Exception ex) { result = "Пользователь не найден"; } return(result); }
public string Briefing(HttpRequestMessage message) { try { var msg = message.Content.ReadAsStringAsync().Result; var date = JObject.Parse(msg)["Date"]; var patientGuid = JObject.Parse(msg)["UserGuid"]; var instructuonGuid = JObject.Parse(msg)["InstructionGuid"]; var statusId = JObject.Parse(msg)["StatusId"]; var timeSeconds = JObject.Parse(msg)["TimeSeconds"]; var instructionType = JObject.Parse(msg)["InstructionType"]; var deviceGuid = JObject.Parse(msg)["DeviceGuid"]; DateTime dateOfBrief = Convert.ToDateTime(date); Guid patient = new Guid(patientGuid.ToString()); Guid instruction = new Guid(instructuonGuid.ToString()); int status = Convert.ToInt16(statusId); int time = Convert.ToInt16(timeSeconds); int type = Convert.ToInt16(instructionType); Guid device = new Guid(deviceGuid.ToString()); using (WorkProtectionEntities entities = new WorkProtectionEntities()) { //получение текущего максимального идентификатора int num = (from brief in entities.Briefing orderby brief.Id descending select brief.Id).First(); num++; //создание новой записи в БД Briefing briefing = new Briefing(); briefing.Id = num; briefing.InstructionGuid = instruction; briefing.InstructionType = type; briefing.PatientGuid = patient; briefing.StatusId = status; briefing.TimeSeconds = time; briefing.Date = dateOfBrief; briefing.DeviceGuid = device; entities.Briefing.Add(briefing); entities.SaveChanges(); } return("Success"); } catch (Exception ex) { return(ex.ToString()); } }
public HttpResponseMessage Get(string id) { string userPhoto; try { using (WorkProtectionEntities entities = new WorkProtectionEntities()) { var photoOfUser = entities.PatientPhoto.FirstOrDefault(e => e.PatientGuid.ToString() == id); if (photoOfUser != null) { userPhoto = photoOfUser.SrcOriginal; } else { userPhoto = "default.png"; } } } catch (Exception ex) { userPhoto = "error"; } HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.OK); string fileName = userPhoto; string filePath = System.Web.HttpContext.Current.Server.MapPath("~/Files/Photos/"); if (!File.Exists(filePath + fileName)) { fileName = "default.png"; } filePath = filePath + fileName; ImageLoader imageLoader = new ImageLoader(filePath, fileName, response); return(imageLoader.ConvertToBytes()); }
public string Get(string id) { string result = ""; try { using (WorkProtectionEntities entities = new WorkProtectionEntities()) { //получение профессии пользователя по его id var userData = entities.PatientTable.FirstOrDefault(e => e.Guid.ToString() == id); string profession = userData.Profession; //получение инструкций по профессии var instructions = from inst in entities.InstructionProfession join pr in entities.Post on inst.ProfessionId equals pr.ID where pr.Name == profession select inst; int count = instructions.Count(); //создание массивов для отправки клиенту Guid[] ids = new Guid[count]; string[] names = new string[count]; string[] expireDates = new string[count]; string[] files = new string[count]; bool[] passed = new bool[count]; int counter = 0; //получение с использованием Guid описаний инструкций foreach (var instr in instructions) { //получение описания инструктажа var description = entities.InstructionInfo.FirstOrDefault(e => e.Guid == instr.InstructionGuid); ids[counter] = description.Guid; names[counter] = description.Name; expireDates[counter] = description.Date.ToString(); //получение пути до файла var fileOfBriefing = entities.InstructionFile.FirstOrDefault(e => e.InstructionGuid == instr.InstructionGuid); var pathOfFile = entities.AttachedFile.FirstOrDefault(e => e.Guid == fileOfBriefing.FileGuid); if ((pathOfFile.Path != null) && (pathOfFile.Path != "")) { string fileNm = pathOfFile.Name; fileNm = fileNm.Replace(".pdf", ""); files[counter] = fileNm; } else { files[counter] = "null"; } Guid temp = ids[counter]; //проверка, был ли инструктаж уже пройден var passing = from pass in entities.Briefing where (pass.PatientGuid.ToString() == id) && (pass.InstructionGuid == temp) select pass; if (!passing.Any()) { passed[counter] = false; } else { passed[counter] = true; } //переход к следующему найденному инструктажу counter++; } if (!instructions.Any()) { result = "Ничего не найдено"; } else { //создание объекта для отправки BriefingInfo briefingInfo = new BriefingInfo(ids, names, expireDates, files, passed); result = JsonConvert.SerializeObject(briefingInfo); } } } catch (Exception ex) { result = "Произошла ошибка"; } return(result); }
public string Get(string id) { string result = ""; try { using (WorkProtectionEntities entities = new WorkProtectionEntities()) { entities.Database.CommandTimeout = 120; //по идентификатору теста получаем информацию о нем Guid ident = new Guid(id); //получение имени и времени прохождения var testData = entities.SurveyTemplateFullInfo.FirstOrDefault(e => e.Guid.ToString() == id); string name = testData.Name; int time; if (testData.QuestionTime != null) { time = Convert.ToInt16(testData.QuestionTime); } else { time = 0; } //получение количеств категорий вопросов теста var questionCategoryData = from questionCategory in entities.SurveyTemplateQuestionCategory where questionCategory.TemplateGuid.ToString() == id select questionCategory; //общее число категорий int n = questionCategoryData.Count(); //получение вопросов из категорий List <int> nums = new List <int>(); List <int> categs = new List <int>(); List <Guid> idsOfQuestions = new List <Guid>(); List <string> questions = new List <string>(); List <string> typesOfQuestions = new List <string>(); List <string> namesOfFiles = new List <string>(); List <Guid> idsOfAnswers = new List <Guid>(); if (n == 1) { //получение количества вопросов и id категории var numbCat = entities.SurveyTemplateQuestionCategory.FirstOrDefault(e => e.TemplateGuid.ToString() == id); nums.Add(Convert.ToInt16(numbCat.QuestionCount)); categs.Add(Convert.ToInt16(numbCat.QuestionCategoryId)); } else if (n > 1) { foreach (var quest in questionCategoryData) { nums.Add(Convert.ToInt16(quest.QuestionCount)); categs.Add(Convert.ToInt16(quest.QuestionCategoryId)); } } for (int g = 0; g < categs.Count; g++) { //получение всех вопросов из категории categ int temp = categs[g]; var questionsData = from quesData in entities.QuestionInfo where quesData.CategoryId == temp select quesData; //получение num первых вопросов из этой категории int i = 0; foreach (var quest in questionsData) { //запись идентификатора и текста вопроса idsOfQuestions.Add(quest.Guid); if (quest.Text != null) { questions.Add(quest.Text); } else { questions.Add("null"); } //определение типа вопроса if ((quest.Image == null)) { typesOfQuestions.Add("текст"); } else if (((quest.Image[quest.Image.Length - 3] == 'a') && (quest.Image[quest.Image.Length - 2] == 'v') && (quest.Image[quest.Image.Length - 1] == 'i')) || ((quest.Image[quest.Image.Length - 3] == 'm') && (quest.Image[quest.Image.Length - 2] == 'p') && (quest.Image[quest.Image.Length - 1] == '4'))) { typesOfQuestions.Add("видео"); } else { typesOfQuestions.Add("изображение"); } //добавление пути к файлу вопроса if (quest.Image != null) { int numOfEnd = 0; for (int j = 0; j < quest.Image.Length; j++) { if (quest.Image[j] == ';') { numOfEnd = j; break; } } string nameOfFile = quest.Image.Substring(0, numOfEnd); namesOfFiles.Add(nameOfFile); } else { namesOfFiles.Add("_"); } i++; if (i == nums[g]) { break; } } } //получение вариантов ответов для вопросов List <int> numberOfAnswers = new List <int>(); List <string> answers = new List <string>(); List <int> answersCorrectness = new List <int>(); //проход по всем найденным вопросам for (int i = 0; i < idsOfQuestions.Count; i++) { Guid temp = idsOfQuestions[i]; var questionAnswerData = entities.QuestionAnswerInfo.Where(e => e.QuestionGuid == temp); numberOfAnswers.Add(questionAnswerData.Count()); foreach (var questAnsw in questionAnswerData) { string answ = questAnsw.Name; answ = answ.Replace("\"", ""); answers.Add(answ); string correctness = questAnsw.Correct; if (correctness != null) { correctness = correctness.Replace("%", ""); answersCorrectness.Add(Convert.ToInt16(correctness)); } else { answersCorrectness.Add(0); } } } //создание объекта для отправки ChosenTestInfo chosenTestInfo = new ChosenTestInfo(ident, name, time, questions.ToArray(), typesOfQuestions.ToArray(), namesOfFiles.ToArray(), numberOfAnswers.ToArray(), answers.ToArray(), answersCorrectness.ToArray()); result = JsonConvert.SerializeObject(chosenTestInfo); } } catch (Exception ex) { result = "Произошла ошибка"; } return(result); }
public string Get(string id) { string result = ""; try { using (WorkProtectionEntities entities = new WorkProtectionEntities()) { //получение списка тестов по id пользователя var testData = from test in entities.SurveyTemplateFullInfo join testUser in entities.SurveyTemplatePatientInfo on test.Guid equals testUser.TemplateGuid where testUser.PatientGuid.ToString() == id select test; if (!testData.Any()) { result = "Ничего не найдено"; } else { int n = testData.Count(); //массивы для передачи объекту теста Guid[] ids = new Guid[n]; string[] names = new string[n]; string[] expireDates = new string[n]; bool[] passed = new bool[n]; //заполнение массивов и получение оставшихся полей int i = 0; foreach (var test in testData) { ids[i] = test.Guid; names[i] = test.Name; //обработка оставшегося времени { try { if ((test.Type.ToLower() == "ежедневная") || (test.Type.ToLower() == "плановая")) { expireDates[i] = DateTime.Today.ToString(); } else if (test.Type.ToLower() == "еженедельная") { //получение последнего дня текущей недели DateTime baseDate = DateTime.Now; var thisWeekStart = baseDate.AddDays(-(int)baseDate.DayOfWeek); var thisWeekEnd = thisWeekStart.AddDays(7).AddSeconds(-1); expireDates[i] = thisWeekEnd.ToString(); } else if (test.Type.ToLower() == "ежемесячная") { string baseDate = DateTime.Now.ToString(); int currentYear = DateTime.Parse(baseDate).Year; int currentMonth = DateTime.Parse(baseDate).Month; DateTime endOfMonth = new DateTime(currentYear, currentMonth, DateTime.DaysInMonth(currentYear, currentMonth)); expireDates[i] = endOfMonth.ToString(); } } catch (Exception ex) { expireDates[i] = DateTime.Today.ToString(); } } passed[i] = false; i++; } TestInfo testInfo = new TestInfo(ids, names, expireDates, passed); result = JsonConvert.SerializeObject(testInfo); } } } catch (Exception ex) { result = "Произошла ошибка"; } return(result); }
public string Get() { string result = ""; try { using (WorkProtectionEntities entities = new WorkProtectionEntities()) { //получение списка памяток var instructionData = from instr in entities.InstructionBlitzInfo orderby instr.Date descending select instr; //количество последних n инструкций, отправляемых пользователю int n = 5; //массивы с данными для передачи объекту Guid[] ids = new Guid[n]; string[] names = new string[n]; string[] dates = new string[n]; string[] files = new string[n]; //заполнение массивов полученными данными int i = 0; foreach (var instr in instructionData) { ids[i] = instr.Guid; names[i] = instr.Name; dates[i] = instr.Date.ToString(); Guid temp = ids[i]; //получение файла для памятки var fileId = entities.InstructionBlitzFile.FirstOrDefault(e => e.InstructionBlitzGuid == temp); if (fileId != null) { var filePath = entities.AttachedFile.FirstOrDefault(e => e.Guid == fileId.FileGuid); string nameOfFile = filePath.Path.Replace("\\InstructionBlitzs\\", ""); files[i] = nameOfFile; } else { files[i] = "null"; } i++; if (i == n) { break; } } if (!instructionData.Any()) { result = "Ничего не найдено"; } else { InstructionBlitzInfo instructionBlitzInfo = new InstructionBlitzInfo(ids, names, dates, files); result = JsonConvert.SerializeObject(instructionBlitzInfo); } } } catch (Exception ex) { result = "Произошла ошибка"; } return(result); }