// MIGRATION OLD DATA!!!
        public static bool MigrateOldData(long fromId, long toId)
        {
            using (var surveysRepository = new BaseRepository<SurveysShellResult>())
            {
                List<SurveysShellResult> surveysShellResults =
                    surveysRepository.GetAllItems.Where(x => x.SurveyResultId >= fromId && x.SurveyResultId <= toId).
                        ToList();
                if (surveysShellResults == null)
                {
                    return false;
                }
                if (surveysShellResults.Count == 0)
                {
                    return false;
                }

                foreach (var surveysShellResult in surveysShellResults)
                {

                    Person person =
                        surveysRepository.Context.Persons.FirstOrDefault(x => x.Id == surveysShellResult.PersonId);
                    if (person == null)
                    {
                        continue;
                    }

                    Test test = surveysRepository.Context.Tests.FirstOrDefault(x => x.Id == surveysShellResult.MethodsId);
                    if (test == null)
                    {
                        continue;
                    }
                    String answerStr = surveysShellResult.Answer;

                    // Form profile string
                    String profile = String.Empty;
                    switch (test.CodeName)
                    {
                        case Constraints.KKettel16ACodeName:
                        case Constraints.KKettel16BCodeName:
                            KettelMethod kettel = new KettelMethod(person.Gender, person.BirthDate.Value, answerStr);
                            kettel.CreateProfile();
                            KettelOutput kettelOutput = new KettelOutput();
                            kettelOutput.CreateOutputJson(kettel);
                            profile = JsonHelper.JsonSerializer<KettelOutput>(kettelOutput);
                            break;

                        case Constraints.KSelfAppraisalCodeName:
                            SelfAppraisalMethod selfAppraisal = new SelfAppraisalMethod(answerStr);
                            selfAppraisal.CreateProfile();
                            SelfAppraisalOutput selfAppraisalOutput = new SelfAppraisalOutput();
                            selfAppraisalOutput.CreateOutputJson(selfAppraisal);
                            profile = JsonHelper.JsonSerializer<SelfAppraisalOutput>(selfAppraisalOutput);
                            break;

                        case Constraints.KSondiCodeName:
                            List<SurveysAnswer> answerItems =
                                surveysRepository.Context.SurveysAnswers.Where(
                                    x => x.SurveysResult.Id == surveysShellResult.SurveyResultId).ToList();
                            answerStr = ResultConverter.GenerateSondiAnswerString(answerItems);
                            SondiMethod sondi = new SondiMethod(answerStr);
                            sondi.CreateProfile();
                            sondi.CreateFormulaAffection();
                            sondi.CreateDMFactor();
                            sondi.CreateSocialityFactor();
                            SondiOutput sondiOutput = new SondiOutput();
                            sondiOutput.CreateOutputJson(sondi);
                            profile = JsonHelper.JsonSerializer<SondiOutput>(sondiOutput);
                            break;

                        case Constraints.KKotCodeName:
                            KotMethod kot = new KotMethod(answerStr);
                            kot.CreateProfile();
                            KotOutput kotOutput = new KotOutput();
                            kotOutput.CreateOutputJson(kot);
                            profile = JsonHelper.JsonSerializer<KotOutput>(kotOutput);
                            break;

                        case Constraints.KShutzCodeName:
                            ShutzMethod shutz = new ShutzMethod(answerStr);
                            shutz.CreateProfile();
                            ShutzOutput shutzOutput = new ShutzOutput();
                            shutzOutput.CreateOutputJson(shutz);
                            profile = JsonHelper.JsonSerializer<ShutzOutput>(shutzOutput);
                            break;

                        case Constraints.KLusherPairCodeName:
                            profile = LusherPairMethod.GetColorString(answerStr);
                            break;

                        case Constraints.KMmpiCodeName:
                            MmpiMethod mmpi = new MmpiMethod(answerStr, person.Gender);
                            mmpi.CreateProfile();
                            profile = mmpi.CutProfileStr;
                            break;

                        default:
                            break;
                    }

                    // Save profile in Conclusion.Data
                    Service service =
                        surveysRepository.Context.Services.FirstOrDefault(
                            x =>
                            x.MethodsId == surveysShellResult.MethodsId &&
                            String.Equals(x.ConclusionType.Code, Constraints.KConclusionTypeProfile));

                    if (service != null)
                    {
                        Conclusion conclusion =
                            surveysRepository.Context.Conclusions.FirstOrDefault(
                                x => x.SurveysResult.Id == surveysShellResult.SurveyResultId && x.Service.Id == service.Id);
                        if (conclusion == null)
                        {
                            Console.WriteLine("no conclusion with surveys id = " + surveysShellResult.SurveyResultId);
                            continue;
                        }
                        conclusion.Data = profile;
                        surveysRepository.Context.Entry(conclusion).State = EntityState.Modified;
                    }

                }
                surveysRepository.Context.SaveChanges();
                return true;
            }
        }
        public static String GenerateDataProfile(long surveysResultId, List<SurveysAnswerContent> surveysAnswerContents)
        {
            using (var conclusionRepository = new BaseRepository<Conclusion>())
            {
                SurveysResult surveysResult =
                    conclusionRepository.Context.SurveysResults.FirstOrDefault(x => x.Id == surveysResultId);
                if (surveysResult == null)
                {
                    throw new SurveysResultDoesNotExistException();
                }

                String answerStr = String.Empty;

                Test test = conclusionRepository.Context.Tests.FirstOrDefault(x => x.Id == surveysResult.MethodsId);
                Person person = conclusionRepository.Context.Persons.FirstOrDefault(x => x.Id == surveysResult.Person.Id);

                // for KOT
                //if (String.Equals(test.CodeName, Constraints.KKotCodeName))
                //{
                //    // Get answer str from SurveyShellResult.Answer
                //    SurveysShellResult shellResult =
                //        conclusionRepository.Context.SurveysShellResults.FirstOrDefault(
                //            x => x.SurveyResultId == surveysResultId);
                //    if (shellResult != null)
                //    {
                //        answerStr = shellResult.Answer;
                //    }
                //}
                //else
                //{
                    answerStr = ResultConverter.GenerateAnswerString(test.CodeName, surveysAnswerContents);
                //}

                // Form profile string
                String profile = String.Empty;
                switch (test.CodeName)
                {
                    case Constraints.KKettel16ACodeName:
                    case Constraints.KKettel16BCodeName:
                        KettelMethod kettel = new KettelMethod(person.Gender, person.BirthDate.Value, answerStr);
                        kettel.CreateProfile();
                        KettelOutput kettelOutput = new KettelOutput();
                        kettelOutput.CreateOutputJson(kettel);
                        profile = JsonHelper.JsonSerializer<KettelOutput>(kettelOutput);
                        break;

                    case Constraints.KSelfAppraisalCodeName:
                        SelfAppraisalMethod selfAppraisal = new SelfAppraisalMethod(answerStr);
                        selfAppraisal.CreateProfile();
                        SelfAppraisalOutput selfAppraisalOutput = new SelfAppraisalOutput();
                        selfAppraisalOutput.CreateOutputJson(selfAppraisal);
                        profile = JsonHelper.JsonSerializer<SelfAppraisalOutput>(selfAppraisalOutput);
                        break;

                    case Constraints.KSondiCodeName:
                        SondiMethod sondi = new SondiMethod(answerStr);
                        sondi.CreateProfile();
                        sondi.CreateFormulaAffection();
                        sondi.CreateDMFactor();
                        sondi.CreateSocialityFactor();
                        SondiOutput sondiOutput = new SondiOutput();
                        sondiOutput.CreateOutputJson(sondi);
                        profile = JsonHelper.JsonSerializer<SondiOutput>(sondiOutput);
                        break;

                    case Constraints.KKotCodeName:
                        KotMethod kot = new KotMethod(answerStr);
                        kot.CreateProfile();
                        KotOutput kotOutput = new KotOutput();
                        kotOutput.CreateOutputJson(kot);
                        profile = JsonHelper.JsonSerializer<KotOutput>(kotOutput);
                        break;

                    case Constraints.KShutzCodeName:
                        ShutzMethod shutz = new ShutzMethod(answerStr);
                        shutz.CreateProfile();
                        ShutzOutput shutzOutput = new ShutzOutput();
                        shutzOutput.CreateOutputJson(shutz);
                        profile = JsonHelper.JsonSerializer<ShutzOutput>(shutzOutput);
                        break;

                    case Constraints.KLusherPairCodeName:
                        profile = LusherPairMethod.GetColorString(answerStr);
                        break;

                    case Constraints.KMmpiCodeName:
                        MmpiMethod mmpi = new MmpiMethod(answerStr, person.Gender);
                        mmpi.CreateProfile();
                        profile = mmpi.CutProfileStr;
                        break;

                    default:
                        break;
                }

                // Save profile in Conclusion.Data
                Service service =
                    conclusionRepository.Context.Services.FirstOrDefault(
                        x =>
                        x.MethodsId == surveysResult.MethodsId &&
                        String.Equals(x.MethodsType, surveysResult.MethodsType) &&
                        String.Equals(x.ConclusionType.Code, Constraints.KConclusionTypeProfile));

                if (service != null)
                {
                    Conclusion conclusion =
                        conclusionRepository.GetAllItems.FirstOrDefault(
                            x => x.SurveysResult.Id == surveysResultId && x.Service.Id == service.Id);
                    conclusion.Data = profile;
                    if (!conclusionRepository.Update(conclusion).Status)
                    {
                        throw new UpdateException();
                    }
                }
                return profile;
            }
        }
        public Object GenerateProfile(Guid resultId)
        {
            using (var resultRepo = new BaseRepository<Result>())
            {
                var result = resultRepo.GetAllItems.FirstOrDefault(x => x.Id == resultId);
                if (result == null)
                {
                    throw new ResultDoesNotExistException();
                }

                var user = _resultRepository.GetUserByResult(resultId);
                var test = _resultRepository.GetTestByResult(resultId);
                var resultItems = _resultRepository.GetResultItemsByResult(resultId);
                var shellResult = _resultRepository.GetShellResultByResult(resultId);

                #region not need now

                var profileFounded = resultRepo.Context.Profiles.FirstOrDefault(x => x.Id == resultId);
                if (profileFounded == null)
                {
                    //String profileStr = @"<p>КОММУНИКАТИВНАЯ СФЕРА</p><p>Преимущественное открытое, дружеское общение с окружающими, навыки общения развиты достаточно. Стремление к активности, доминированию среди сверстников. Настойчивость в достижении поставленной цели. Уверенность в своей правоте. В значимых для себя ситуациях возможно проявление упрямства. Стремление к популярности в окружении. Достаточная высокая самоуверенность.</p><p>ЭМОЦИОНАЛЬНО-ВОЛЕВАЯ СФЕРА</p><p>Воображение недостаточно развито, мышление в основном конкретное, возможны трудности в ситуациях требующих абстрактного мышления. Возможны проявления капризности, непостоянства в значимых для себя ситуациях. Стремление уклониться от трудностей. Недостаточное постоянство в отношениях и интересах. Действия могут опережать их продуманность. Наивность, затруднения в планировании своего поведения в сочетании со стремлением уклониться от повседневных проблем и трудностей создают картину психического инфантилизма. Зависимость от сверстников, поспешность в решениях. Возможна излишняя сентиментальность. Некоторое сужение поля восприятия. Уверенность в правильности своих действий, снижение процессов рефлексии, ослабление процессов целеполагания, трудности в формировании мотивации обучения. Неудовлетворенность своим положением в группе сверстников, сочетаясь с ощущением давления со стороны семейного круга создает предиспозицию для отклонений в поведении.</p>";
                    String profileStr = @"<p>Идет интерпретация</p>";

                    //==============================

                    //Create Folder and txt info file
                    var directoryName = user.Id + "_" + test.CodeName + "_" + result.TestDate.ToString("dd.MM.yyyy_HH.mm.ss");
                    var directory = Constraints.KInterpretationDirectoryPath + directoryName;
                    try
                    {
                        // Determine whether the directory not exists.
                        if (!Directory.Exists(directory))
                        {
                            // Try to create the directory.
                            Directory.CreateDirectory(directory);
                        }
                    }
                    catch (Exception)
                    {
                        throw new DirectoryNotFoundException();
                    }

                    try
                    {
                        // Create txt file info
                        var fileName = @"\info.txt";
                        var fileInfo = new FileInfo(directory + fileName);

                        if (!fileInfo.Exists)
                        {
                            //Create a file to write to.
                            using (var streamWriter = fileInfo.CreateText())
                            {
                                streamWriter.WriteLine("===========================");
                                streamWriter.WriteLine("ResultId: " + resultId);
                                streamWriter.WriteLine("===========================");
                                streamWriter.Write(user.ToString());
                                streamWriter.WriteLine();
                                streamWriter.WriteLine("===========================");
                                streamWriter.Write(test.ToString());
                                streamWriter.WriteLine("===========================");
                                streamWriter.WriteLine(result.TestDate.ToString());
                                streamWriter.WriteLine("===========================");

                                //var shellResult = resultRepo.Context.ShellResults.FirstOrDefault(x => x.ResultId == resultId);

                                //if (shellResult == null)
                                //{
                                //    throw new ResultDoesNotExistException();
                                //}
                                streamWriter.WriteLine("Method_ID in consul: " + shellResult.MethodId);
                                streamWriter.WriteLine("===========================");
                                streamWriter.WriteLine(shellResult.Answer);
                                streamWriter.WriteLine("===========================");
                                streamWriter.WriteLine(shellResult.Answer.Replace(" ", null));

                                streamWriter.Close();
                            }
                        }
                    }
                    catch (Exception)
                    {
                        throw new FileWriteException();
                    }

                    // Create OldUser and Result in ConsulDB
                    //WriteUserResultInConsul(result, OldUser, test, shellResult);

                    // Create profile in DB
                    var profile = new Profile
                    {
                        Body = profileStr,
                        Id = resultId,
                        ImageDirectory = directoryName,

                    };
                    result.Profile = profile;

                    if (!resultRepo.Update(result).Status)
                    {
                        throw new UpdateException();
                    }
                }

                #endregion

                // Form profile
                Object body = new object();
                switch (test.CodeName)
                {
                    case Constraints.KKettel16ACodeName:
                    case Constraints.KKettel16BCodeName:
                        KettelMethod kettel = new KettelMethod();
                        kettel.CreateProfile();
                        KettelOutput kettelOutput = new KettelOutput();
                        body = kettelOutput.CreateOutputJson(kettel);
                        break;

                    case Constraints.KSelfAppraisalCodeName:
                        SelfAppraisalMethod selfAppraisal = new SelfAppraisalMethod(shellResult.Answer);
                        selfAppraisal.CreateProfile();
                        SelfAppraisalOutput selfAppraisalOutput = new SelfAppraisalOutput();
                        body = selfAppraisalOutput.CreateOutputJson(selfAppraisal);
                        break;

                    case Constraints.KSondiCodeName:
                        // Convert to 1 2 3 4 5 6 7 8 ... answer str
                        ResultConverter converter = new ResultConverter(user, test, resultItems);
                        var answers = converter.FormAnswers(false);
                        SondiMethod sondi = new SondiMethod(answers);
                        sondi.CreateProfile();
                        sondi.CreateFormulaAffection();
                        sondi.CreateDMFactor();
                        sondi.CreateSocialityFactor();
                        SondiOutput sondiOutput = new SondiOutput();
                        body = sondiOutput.CreateOutputJson(sondi);
                        break;

                    case Constraints.KKotCodeName:
                        KotMethod kot = new KotMethod(shellResult.Answer);
                        kot.CreateProfile();
                        KotOutput kotOutput = new KotOutput();
                        body = kotOutput.CreateOutputJson(kot);
                        break;
                    default:
                        break;

                    case Constraints.KShutzCodeName:
                        ShutzMethod shutz = new ShutzMethod(shellResult.Answer);
                        shutz.CreateProfile();
                        ShutzOutput shutzOutput = new ShutzOutput();
                        body = shutzOutput.CreateOutputJson(shutz);
                        break;

                    case Constraints.KMmpiCodeName:
                        MmpiMethod mmpi = new MmpiMethod(shellResult.Answer, false);
                        mmpi.CreateProfile();
                        body = mmpi.CutProfileStr;
                        break;

                }

                GeneralProfile generalProfile = new GeneralProfile
                                          {
                                              Id = resultId,
                                              PersonId = user.Id,
                                              TestId = test.Id,
                                              TestDate = result.TestDate,
                                              Body = body
                                          };
                return generalProfile;

            }
            return null;
        }