예제 #1
0
        // [Fact]
        public void GiveEpicComeback()
        {
            NpgsqlConnection _connection = new NpgsqlConnection(connString);

            _connection.Open();

            IHabitRepository repo = new PostgresHabitRepository(_connection, null);

            Guid id     = new Guid("41684bad-554b-4194-8fc2-d192273b9aa8");
            Guid userID = new Guid("e28c8034-f90d-48aa-8e55-2aad1282f3bd");

            Habit    habit = repo.FindHabitByID(id, userID);
            DateTime now   = DateTime.Now;

            habit.DoHabit(now);
            repo.DoHabit(habit, now);

            for (int i = 10; i < 20; i++)
            {
                now = DateTime.Now.AddDays(i);
                habit.DoHabit(now);
                repo.DoHabit(habit, now);
            }

            Habit habit2 = repo.FindHabitByID(id, userID);

            _connection.Close();
            HabitLogMemento hm = (HabitLogMemento)habit2.HabitLog.GetMemento();

            // Habit habit2 = repo.FindHabitByID(id, userID);
            // Badge badge = bRepo.FindByUserID(userID);
            // Assert.Equal("Dominating", badge.Name);

            _connection.Close();
        }
예제 #2
0
    public static void LogBeforeSave(Habit habit, TypeUpdate typeUpdate, HabitField field, object newValue, string logDescription, MSSQLLocalDBEntities context)
    {
        var habitLog = new HabitLog
        {
            ChangeDescription = logDescription,
            DoneDate          = DateTime.Now,
            HabitId           = habit.Id
        };

        switch (field)
        {
        case HabitField.Name:
            habitLog.OldValue = habit.Name;
            break;

        case HabitField.DoneDate:
            habitLog.OldValue = habit.DoneDate?.ToString();
            break;

        case HabitField.NewRecord:
            break;

        case HabitField.DeleteRecord:
            break;

        default:
            habitLog.OldValue = "";
            break;
        }
        habitLog.NewValue = newValue.ToString();
        context.HabitLogs.Add(habitLog);
        context.SaveChanges();
    }
예제 #3
0
        public HabitResponse GetHabitById(Guid userId, Guid habitId)
        {
            ValidateUserID(userId, habitId);
            Habit habit = habitRepository.GetHabitById(habitId);

            return(ConvertFromHabitToHabitResponse(habit));
        }
        public async Task UpdateHabitsAsync_WithCorrectData_ShouldReturnCorrectResult()
        {
            var color = new Color
            {
                Id   = 1,
                Name = "Test",
                Hex  = "TestHex",
            };

            var calendar = new Calendar
            {
                Id    = "CalendarId",
                Title = "Default",
                DefaultCalendarColor   = color,
                DefaultCalendarColorId = color.Id,
            };

            var goal = new Goal
            {
                Id         = "TestId",
                Title      = "Test",
                Calendar   = calendar,
                CalendarId = calendar.Id,
                IsActive   = true,
                Color      = color,
                ColorId    = color.Id,
            };

            var habit = new Habit
            {
                Id            = "TestId",
                Title         = "Test",
                StartDateTime = new DateTime(2020, 02, 02, 12, 0, 0),
                EndDateTime   = new DateTime(2020, 02, 02, 12, 30, 0),
                GoalId        = goal.Id,
                Goal          = goal,
                IsCompleted   = false,
            };

            var currentDate      = DateTime.Parse("02/02/2020");
            var startEndDatetime = new StartEndDateTime
            {
                Start = new DateTime(2020, 02, 02, 12, 0, 0),
                End   = new DateTime(2020, 02, 02, 12, 30, 0),
            };

            this.dateTimeService
            .Setup(x => x.GenerateDatesForMonthAhead(It.IsAny <int>(), It.IsAny <int>(), It.IsAny <string>(), It.IsAny <DateTime>()))
            .Returns(new List <StartEndDateTime> {
                startEndDatetime
            });

            this.habitsRepository.Setup(x => x.All()).Returns(new List <Habit> {
                habit
            }.AsQueryable());
            var result = await this.habitService.UpdateHabitsAsync(goal, habit.Id);

            this.habitsRepository.Verify(x => x.All(), Times.Exactly(2));
            this.habitsRepository.Verify(x => x.SaveChangesAsync(), Times.Exactly(2));
        }
예제 #5
0
        public void CreateHabit()
        {
            NpgsqlConnection _connection = new NpgsqlConnection(connString);

            _connection.Open();

            IHabitRepository repo = new PostgresHabitRepository(_connection, null);
            string           name = "sleep";

            string[] day_off = { "Sun" };

            Habit h = new Habit(name, day_off, user_id);

            repo.Create(h);

            Habit h2 = repo.FindById(h.ID);

            Assert.NotNull(h2);

            Assert.Equal(h.ID, h2.ID);
            Assert.Equal(h.UserID, h2.UserID);
            Assert.Equal(h.Name, h2.Name);
            Assert.Equal(h.DaysOff, h2.DaysOff);

            _connection.Close();
        }
        async Task DeleteHabit(Habit habit)
        {
            // TODO: sync DataService list with db list
            await DataService.DeleteHabit(habit);

            State.SelectedHabit = null;
        }
예제 #7
0
        public async Task CreateHabit(Habit habit)
        {
            var jsonData   = JsonConvert.SerializeObject(habit);
            var jsonResult = await PostDataAsync("api/habit/create", jsonData);

            return;
        }
예제 #8
0
        public void HabitTrackTest()
        {
            User         popo = User.NewUser("Popo");
            List <Habit> list = new List <Habit>();

            Habit habit  = Habit.addNewHabit(popo.ID, "Belajar", new string[] { "Tue", "Wed" });
            Habit habit2 = Habit.addNewHabit(popo.ID, "Mandi", new string[] { "Mon" });

            list.Add(habit);
            list.Add(habit2);

            string name = null;

            foreach (var i in list)
            {
                if (i.Name == habit.Name)
                {
                    name = i.Name;
                    break;
                }
            }

            Assert.NotNull(list);
            Assert.Equal(name, habit.Name);
        }
예제 #9
0
        public async Task <ActionResult <Habit> > CreateHabit(Habit habit)
        {
            try
            {
                if (!ModelState.IsValid)
                {
                    return(BadRequest("Something wrong with the model!"));
                }

                _repository.Add <Habit>(habit);

                if (await _repository.SaveChangesAsync())
                {
                    return(Ok());
                }
                else
                {
                    return(BadRequest("Something bad happened!"));
                }
            }
            catch (Exception ex)
            {
                return(StatusCode(StatusCodes.Status500InternalServerError, ex.Message));
            }
        }
        public List <Habit> FindByUserId(Guid user_id)
        {
            List <Habit> _list = new List <Habit>();
            string       query = @"select id, name, user_id, CAST(days_off as text) from ""habit"" where user_id = @user_id and deleted_at is null";

            using (var cmd = new NpgsqlCommand(query, _connection, _transaction))
            {
                cmd.Parameters.AddWithValue("user_id", user_id);
                using (NpgsqlDataReader reader = cmd.ExecuteReader())
                {
                    while (reader.Read())
                    {
                        Guid   id       = reader.GetGuid(0);
                        string name     = reader.GetString(1);
                        Guid   _user_id = reader.GetGuid(2);
                        string daysoff  = reader.GetString(3);

                        string[] dday = daysoff.Split(new Char[] { '{', '}', '"', ',' }, StringSplitOptions.RemoveEmptyEntries);

                        for (int index = 0; index < dday.Length; index++)
                        {
                            dday[index] = dday[index].Trim();
                        }

                        Habit h = new Habit(id, _user_id, name, dday, new Logs());
                        _list.Add(h);
                    }
                }
                return(_list);
            }
        }
예제 #11
0
        public HttpResponseMessage CreateHabit(Habit habit)
        {
            MySqlConnection conn = new MySqlConnection(CONNECTION_STRING);

            try
            {
                conn.Open();

                string       rtn = "create_habit_procedure";
                MySqlCommand cmd = new MySqlCommand(rtn, conn);
                cmd.CommandType = CommandType.StoredProcedure;

                cmd.Parameters.AddWithValue("@id", habit.ID.ToString());
                cmd.Parameters.AddWithValue("@description", habit.Description);
                cmd.Parameters.AddWithValue("@difficulty", habit.Difficulty.ToString());
                cmd.Parameters.AddWithValue("@username", habit.Username);

                cmd.ExecuteNonQuery();
                return(base.BuildSuccessResult(HttpStatusCode.OK));
            }
            catch (Exception)
            {
                return(base.BuildErrorResult(HttpStatusCode.BadRequest, "Error creating habit!"));
            }
            finally
            {
                conn.Close();
            }
        }
예제 #12
0
        public ActionResult <Habits> AddNewHabit(Guid userID, [FromBody] RequestData data)
        {
            NpgsqlConnection _connection = new NpgsqlConnection(connString);

            _connection.Open();
            IHabitRepository repo1 = new HabitRepository(_connection, null);

            IGainer logGainer = new LogSuccess();

            try
            {
                Habit h = HabitFactory.Create(data.Name, data.days, userID, logGainer);

                repo1.CreateHabit(h, data.days);

                repo1.AddLog(h.ID);

                repo1.AddStreak(h.ID, h.getStreak());
                return(new Habits()
                {
                    ID = h.ID,
                    name = h.name,
                    user_id = h.users,
                    Log_count = h.Logs,
                    days = h.daysoff,
                    current_streak = h.current_streak,
                    longest_streak = h.longest_streak
                });
            }
            catch
            {
                return(NotFound("user not found"));
            }
        }
예제 #13
0
        public void CheckHabit2()
        {
            Guid     habit_id = Guid.NewGuid();
            Guid     user_id  = Guid.NewGuid();
            DateTime now      = DateTime.Now;

            Days[] dayoff = new Days[] { new Days("Mon"), new Days("Sun") };
            Habit  h      = new Habit(habit_id, "Nyanyi", dayoff, user_id, now);


            h.DoHabit(DateTime.Now.AddDays(0)); //Sun

            // h.DoHabit(DateTime.Now.AddDays(1)); //Mon
            h.DoHabit(DateTime.Now.AddDays(3)); //Wed
            h.DoHabit(DateTime.Now.AddDays(4)); //Thu

            h.DoHabit(DateTime.Now.AddDays(6)); //Sun
            h.DoHabit(DateTime.Now.AddDays(7)); //Sun

            HabitLogMemento hm = (HabitLogMemento)h.HabitLog.GetMemento();

            Assert.Equal(2, hm.longest_streak);
            Assert.Equal(2, hm.current_streak);
            Assert.Equal(5, hm.log_count);
        }
예제 #14
0
        public async Task <IActionResult> Edit(int id, [Bind("Id,Date,DailyHabit,Intention,Feedback")] Habit habit)
        {
            if (id != habit.Id)
            {
                return(NotFound());
            }

            if (ModelState.IsValid)
            {
                try
                {
                    _context.Update(habit);
                    await _context.SaveChangesAsync();
                }
                catch (DbUpdateConcurrencyException)
                {
                    if (!HabitExists(habit.Id))
                    {
                        return(NotFound());
                    }
                    else
                    {
                        throw;
                    }
                }
                return(RedirectToAction(nameof(Index)));
            }
            return(View(habit));
        }
예제 #15
0
        public ActionResult <Habits> Log(Guid userID, Guid id)
        {
            NpgsqlConnection _connection = new NpgsqlConnection(connString);

            _connection.Open();
            IHabitRepository repo1 = new HabitRepository(_connection, null);

            try
            {
                Habit h = repo1.FindByID(id, userID);

                repo1.AddLog(id);
                Habit habit = HabitFactory.AddLog(h);

                _connection.Close();
                return(new Habits()
                {
                    ID = habit.ID,
                    name = habit.name,
                    user_id = habit.users,
                    days = habit.daysoff,
                    Log_count = habit.Logs,
                    current_streak = habit.current_streak,
                    longest_streak = habit.longest_streak
                });
            }
            catch
            {
                return(NotFound("Failed"));
            }
        }
예제 #16
0
        public void NotDaysOff()
        {
            string[]  days_off = { "Sun", "Sat", "tue", "Wed", "Thu", "Fri" };
            Exception ex       = Assert.Throws <Exception>(() => h = new Habit(name, days_off));

            Assert.Equal("Make sure the days off are same format and not duplicate", ex.Message);
        }
예제 #17
0
        public void HabitLength()
        {
            string[]  days_off = { "Sun", "Tue", "Wed", "Thu", "Fri", "Sat" };
            Exception ex       = Assert.Throws <Exception>(() => h = new Habit("a", days_off));

            Assert.Equal("name length must between 2 to 100", ex.Message);
        }
예제 #18
0
        private List <DayViewModel> GetLastWeek(Habit habit)
        {
            var days     = new List <DayViewModel>();
            var lastweek = habit.DayStatuses.Where(d => d.StatusDate.Date > DateTime.Now.Date.AddDays(-7)).OrderByDescending(d => d.StatusDate);

            foreach (var date in lastweek)
            {
                DayViewModel day = new DayViewModel();
                day.DayStatus = date.Status.StatusName;
                day.DayId     = date.DayStatusId;
                day.Date      = date.StatusDate;
                day.HasNote   = (date.NoteHeadline != null && date.NoteHeadline != "") || (date.Note != null && date.Note != "");
                day.WithDay   = true;
                days.Add(day);
            }

            if (days.Count < 7)
            {
                int disabled = 7 - days.Count;
                for (int i = 0; i < disabled; i++)
                {
                    DayViewModel day = new DayViewModel();
                    day.DayStatus = "disabled";
                    day.WithDay   = true;
                    days.Add(day);
                }
            }

            days.Reverse();

            return(days);
        }
        private Habit CreateHabit()
        {
            var realmDb = Realm.GetInstance();

            var habits = realmDb.All <Habit>().ToList();

            var maxHabitId = 0;

            if (habits.Count != 0)
            {
                maxHabitId = habits.Max(h => h.Id);
            }

            Habit habit = new Habit()
            {
                Id               = maxHabitId + 1,
                TaskTitle        = TaskTitle,
                Notes            = Notes,
                PositiveSelected = PositiveSelected,
                NegativeSelected = NegativeSelected,
                Difficulty       = SelectedDifficulty,
                ResetStreak      = SelectedResetStreak
            };

            realmDb.Write(() =>
            {
                realmDb.Add(habit);
            });

            return(habit);
        }
        public async Task <IActionResult> Put(int id, [FromBody] HabitModel habitModel)
        {
            RepeatDays?result = null;

            if (habitModel.RepeatDays != null)
            {
                RepeatDays[] repeatDays = habitModel.RepeatDays.Select(o => (RepeatDays)o).ToArray();

                foreach (RepeatDays f in repeatDays)
                {
                    result |= (RepeatDays)f;
                }
                if (habitModel.Repeat == null || habitModel.Repeat != Repeat.Weekly)
                {
                    result = null;
                }
            }
            Habit habit = new Habit
            {
                Id                                                                  = habitModel.Id,
                Name                                                                = habitModel.Name,
                Description                                                         = habitModel.Description,
                StartDate                                                           = habitModel.StartDate == null?dateTimeService.GetCurrentDateTime() : (DateTime)habitModel.StartDate,
                                                             EndDate                = habitModel.EndDate,
                                                             Repeat                 = habitModel.Repeat == null ? Repeat.NoRepeat : (Repeat)habitModel.Repeat,
                                                             RepeatDays             = (RepeatDays?)result,
                                                             Colour                 = habitModel.Colour,
                                                             Mesurable              = habitModel.Mesurable,
                                                             NumberOfBlocks         = habitModel.NumberOfBlocks,
                                                             RepresentationOfBlocks = habitModel.RepresentationOfBlocks
            };

            habitService.UpdateHabit(id, habit);
            return(NoContent());
        }
        public async Task <IActionResult> Edit(Guid id, [Bind("Id,Name,HabitDays,HabitTimeNotification")] Habit habit)
        {
            if (id != habit.Id)
            {
                return(NotFound());
            }

            if (ModelState.IsValid)
            {
                try
                {
                    _context.Update(habit);
                    await _context.SaveChangesAsync();
                }
                catch (DbUpdateConcurrencyException)
                {
                    if (!HabitExists(habit.Id))
                    {
                        return(NotFound());
                    }
                    else
                    {
                        throw;
                    }
                }
                return(RedirectToAction(nameof(Index)));
            }
            return(View(habit));
        }
        public async Task <IActionResult> Post([FromBody] HabitModel habitModel)
        {
            RepeatDays[] repeatDays = habitModel.RepeatDays.Select(o => (RepeatDays)o).ToArray();
            RepeatDays?  result     = null;

            foreach (RepeatDays f in repeatDays)
            {
                result |= (RepeatDays)f;
            }
            if (habitModel.Repeat == null || habitModel.Repeat != Repeat.Weekly)
            {
                result = null;
            }
            Habit habit = new Habit
            {
                Id                                                                  = habitModel.Id,
                Name                                                                = habitModel.Name,
                Description                                                         = habitModel.Description,
                StartDate                                                           = habitModel.StartDate == null?dateTimeService.GetCurrentDateTime() : (DateTime)habitModel.StartDate,
                                                             EndDate                = habitModel.EndDate,
                                                             Repeat                 = habitModel.Repeat == null? Repeat.NoRepeat :(Repeat)habitModel.Repeat,
                                                             RepeatDays             = (RepeatDays?)result,
                                                             Colour                 = habitModel.Colour,
                                                             Mesurable              = habitModel.Mesurable,
                                                             NumberOfBlocks         = habitModel.NumberOfBlocks,
                                                             RepresentationOfBlocks = habitModel.RepresentationOfBlocks
            };

            return(CreatedAtAction("Get", new { id = habit.Id }, habitService.AddHabit(habit)));
        }
예제 #23
0
        public HttpResponseMessage postHabit(Guid user_id, Guid id)
        {
            try
            {
                var result = new HttpResponseMessage(HttpStatusCode.OK);
                var habit  = habitDatabaseEntities.Habit.Find(id);
                if (habit.user_id == user_id)
                {
                    var j = Repo.habitRepo.habitRegister(habit.name, habit.days_off, user_id);
                }
                var h = new Habit();
                h.current_streak++;
                if (h.current_streak == 5)
                {
                    // habitDatabaseEntities.Badges.Add();
                }

                h.log_count++;
                h.logs = String.Concat(h.logs, ", " + DateTime.Now.ToString());

                return(result);
            }
            catch
            {
                return(new HttpResponseMessage(HttpStatusCode.BadRequest));
            }
        }
예제 #24
0
        private Notification CreateForNotifyFinishHabit(Habit habit, string nextHabitName)
        {
            var    context = Application.Context;
            string title   = $"{habit.Name} 완료";
            string message = $"다음 습관 {nextHabitName}을 시작해주세요~";

            if (nextHabitName == "더 수행할 습관이 없습니다.")
            {
                message = nextHabitName;
            }

            Android.Net.Uri alarmSound = RingtoneManager.GetDefaultUri(RingtoneType.Notification);

            var fileName = habit.Image.Replace(".png", string.Empty);
            var imageId  = context.Resources.GetIdentifier(fileName, "drawable", context.PackageName);

            var notificationBuilder = new NotificationCompat.Builder(context, NOTIFICATION_CHANNEL_ID);
            var notification        = notificationBuilder.SetOngoing(false)
                                      .SetSmallIcon(imageId)
                                      .SetContentTitle(title)
                                      .SetContentText(message)
                                      .SetPriority((int)NotificationImportance.High)
                                      .SetVisibility(NotificationCompat.VisibilityPublic)
                                      .SetSound(alarmSound)
                                      .SetVibrate(vibrationPattern)
                                      .SetContentIntent(OpenAppIntent())
                                      .SetAutoCancel(true)
                                      .Build();

            return(notification);
        }
예제 #25
0
        // GET: Habit
        public ActionResult Index(int habitId)
        {
            Habit dbHabit    = db.Habits.First(h => h.HabitId == habitId);
            var   habitModel = new HabitViewModel(dbHabit);

            return(View(habitModel));
        }
예제 #26
0
        public async Task <bool> GenerateHabitsAsync(Goal goal, DateTime currentDate)
        {
            if (goal == null)
            {
                throw new ArgumentException(InvalidGoalModelErrorMessage);
            }

            var startEndDateTimes = this.dateTimeService.GenerateDatesForMonthAhead((int)goal.Duration, (int)goal.Frequency, goal.DayTime.ToString(), currentDate);

            foreach (var time in startEndDateTimes)
            {
                var habit = new Habit()
                {
                    Title         = goal.Title,
                    StartDateTime = time.Start,
                    EndDateTime   = time.End,
                    Goal          = goal,
                };

                await this.habitRepository.AddAsync(habit);
            }

            var result = await this.habitRepository.SaveChangesAsync();

            return(result > 0);
        }
예제 #27
0
        public async Task <IActionResult> PutHabit(int id, Habit habit)
        {
            if (id != habit.Id)
            {
                return(BadRequest());
            }

            _context.Entry(habit).State = EntityState.Modified;

            try
            {
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!HabitExists(id))
                {
                    return(NotFound());
                }
                else
                {
                    throw;
                }
            }

            return(NoContent());
        }
예제 #28
0
        public ActionResult <Habits> UpdateHabit(Guid userID, Guid id, [FromBody] RequestData data)
        {
            try
            {
                NpgsqlConnection _connection = new NpgsqlConnection(connString);
                _connection.Open();
                IHabitRepository repo1 = new HabitRepository(_connection, null);
                Habit            h     = HabitFactory.Update(id, userID, data.Name, data.days);
                repo1.UpdateHabit(h.ID, h.users, h.name, data.days);

                return(new Habits()
                {
                    ID = h.ID,
                    name = h.name,
                    user_id = h.users,
                    Log_count = h.Logs,
                    days = h.daysoff,
                    current_streak = h.current_streak,
                    longest_streak = h.longest_streak
                });
            }
            catch
            {
                return(NotFound("error"));
            }
        }
예제 #29
0
        public void Holiday()
        {
            string[]  days_off = { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" };
            Exception ex       = Assert.Throws <Exception>(() => h = new Habit(name, days_off));

            Assert.Equal("Days off may not be as many as 7", ex.Message);
        }
예제 #30
0
        public ActionResult <Habits> DeleteHabit(Guid userID, Guid id)
        {
            NpgsqlConnection _connection = new NpgsqlConnection(connString);

            _connection.Open();
            IHabitRepository repo1 = new HabitRepository(_connection, null);

            try
            {
                Habit h = repo1.FindByID(id, userID);
                repo1.DeleteHabit(id, userID);
                return(new Habits()
                {
                    ID = h.ID,
                    name = h.name,
                    user_id = h.users,
                    days = h.daysoff,
                    Log_count = h.Logs,
                    current_streak = h.current_streak,
                    longest_streak = h.longest_streak
                });
            }
            catch
            {
                return(NotFound("Failed!"));
            }
        }
예제 #31
0
    protected void btn_Submit_Click(object sender, EventArgs e)
    {
        //SqlTransaction Transaction;
        //con.Open();
        //Transaction = con.BeginTransaction();
        /*  try
          {
              new SqlCommand("INSERT INTO Transact VALUES ('" +
         * Convert.ToString(Session["Sessionname"]) + "','" +
         * Convert.ToString(Session["SessionDOB"]) + "','" +
         * Convert.ToString(Session["SessionGender"]) + "','" +
         * Convert.ToString(Session["SessionMobile"]) + "','" +
         * Convert.ToString(Session["SessionCountry"]) + "','" +
         * DDL_State.SelectedItem + "','" + DDL_City.SelectedItem + "','" +
         * Convert.ToString(Session["SessionReligion"]) + "','" +
         * Convert.ToString(Session["SessionCaste"]) + "','" +
         * DDL_SubCaste.SelectedItem + "','" + Txt_Gothram.Text + "','" +
         * Convert.ToString(Session["SessionEmail"]) + "','" + Rbtn_PhysicalStatus.SelectedValue + "','" +
         * Txt_Desc.Text + "');", con, Transaction).ExecuteNonQuery();

              new SqlCommand("INSERT INTO EduDetails values ('" + Txt_Height.Text + "','" + DDL_Occupation.SelectedItem + "','" + Rbtn_EmpIn.SelectedValue + "','" + Rbtn_IncomeType.SelectedValue + "','" + DDL_IncomeType.SelectedItem + "','" + Txt_Amount.Text + "');", con, Transaction).ExecuteNonQuery();

              new SqlCommand("INSERT INTO Habit values('" + Rbtn_Food.SelectedValue + "','" + Rbtn_Smoking.SelectedValue + "','" + Rbtn_Drinking.SelectedValue + "');", con, Transaction).ExecuteNonQuery();

              new SqlCommand("INSERT INTO AstrologicalInfo values('" + Rbtn_Dhosam.SelectedValue + "','" + DDL_Star.SelectedItem + "','" + DDL_Moon.SelectedItem + "');", con, Transaction).ExecuteNonQuery();

              new SqlCommand("insert into Family values('" + Rbtn_familystatus.SelectedValue + "','" + Rbtn_FamType.SelectedValue + "','" + Rbtn_FamValue.SelectedValue + "');", con, Transaction).ExecuteNonQuery();

              Transaction.Commit();
          }
          catch
          {
              Transaction.Rollback();
          }
          con.Close();*/
        using (TransactionScope ts = new TransactionScope())
        {

            try
            {
                //using (DataContext contextObject = new DataContext(ConnectionString))
                //{
                // Open the contextObject connection state explicitly
                ObjEntity.Connection.Open();

                string hh = Session["SessionDOB"].ToString();
                // //First SaveChange method.
                MatrimonyDetail objMatrim = new MatrimonyDetail();
                objMatrim.MatrimonyID = 1;
                objMatrim.Name = Convert.ToString(Session["Sessionname"]);
                objMatrim.DOB = DateTime.Parse(hh);
                objMatrim.Gender = Convert.ToString(Session["SessionGender"]);
                objMatrim.CountryID = int.Parse(Session["SessionCountry"].ToString());
                objMatrim.MobileNo = Convert.ToString(Session["SessionMobile"]);
                objMatrim.StateID = int.Parse(DDL_State.SelectedValue);
                objMatrim.CityID = int.Parse(DDL_City.SelectedValue);
                objMatrim.ReligionID = int.Parse(Session["SessionReligion"].ToString());
                objMatrim.CasteID = int.Parse(Session["SessionCaste"].ToString());
                objMatrim.SubCasteID = 6;
                //objMatrim.SubCasteID = int.Parse(DDL_SubCaste.SelectedValue);
                objMatrim.GothraID = 1;
                objMatrim.Email = Convert.ToString(Session["SessionEmail"]);
                objMatrim.LoginPwd = Convert.ToString(Session["SessionPwd"]);

                string strMaritalStatus = "U";
                if (Rbtn_MartialStatus1.Checked == true)
                    strMaritalStatus = "U";
                else if (Rbtn_MartialStatus2.Checked == true)
                    strMaritalStatus = "M";
                else if (Rbtn_MartialStatus3.Checked == true)
                    strMaritalStatus = "D";
                else if (Rbtn_MartialStatus4.Checked == true)
                    strMaritalStatus = "A";

                objMatrim.MaritalStatus = strMaritalStatus;
                //objMatrim.TongueID = int.Parse(Session["SessionMotherTon"].ToString());

                //objMatrim.NoOfChild = DDL_NoOfChild.SelectedValue.ToString();
                objMatrim.NoOfChild = "on";
                if (Rbtn_ChildLiving1.Checked == true)
                    objMatrim.LivingWith = "Y";
                else
                    objMatrim.LivingWith = "N";

                objMatrim.DescriptionInfo = Txt_Desc.Text;
                objMatrim.ActiveInd = "N";
                objMatrim.CreatedDate = System.DateTime.Now;
                objMatrim.UpdatedDate = System.DateTime.Now;

                ObjEntity.AddToMatrimonyDetails(objMatrim);
                ObjEntity.SaveChanges();

                PhysicalAttr Objphysical = new PhysicalAttr();
                Objphysical.MatrimonyID = 1;
                Objphysical.HeightAttr = Convert.ToInt32(Txt_Height.Text);
                Objphysical.WeightAttr = Convert.ToInt32(Txt_Weight.Text);

                string ObjBodytype = "Average";

                if (Rbtn_BodyType1.Checked == true)
                    ObjBodytype = "Average";
                else if (Rbtn_BodyType2.Checked == true)
                    ObjBodytype = "Athletic";
                else if (Rbtn_BodyType3.Checked == true)
                    ObjBodytype = "Slim";
                else if (Rbtn_BodyType4.Checked == true)
                    ObjBodytype = "Heavy";

                Objphysical.BodyType = ObjBodytype;

                string ObjComplexion = "Fair";

                if (Rbtn_Complextion1.Checked == true)
                    ObjComplexion = "Fair";
                else if (Rbtn_Complextion2.Checked == true)
                    ObjComplexion = "Very Fair";
                else if (Rbtn_Complextion3.Checked == true)
                    ObjComplexion = "Wheatish";
                else if (Rbtn_Complextion4.Checked == true)
                    ObjComplexion = "Wheatish-Brown";
                else if (Rbtn_Complextion5.Checked == true)
                    ObjComplexion = "Dark";

                Objphysical.Complexion = ObjComplexion;

                string ObjPhyStatus = "Normal";

                if (Rbtn_PhysicalStatus1.Checked == true)
                    ObjPhyStatus = "Normal";
                else if (Rbtn_PhysicalStatus2.Checked == true)
                    ObjPhyStatus = "Physical Status";

                Objphysical.PhysicalStatus = ObjPhyStatus;

                ObjEntity.AddToPhysicalAttrs(Objphysical);
                ObjEntity.SaveChanges();

                EduDetail ObjEduDetail = new EduDetail();

                ObjEduDetail.MatrimonyID=1;
                ObjEduDetail.EducationID=int.Parse(DDL_HighestEdu.SelectedValue);
                ObjEduDetail.OccupID=int.Parse(DDL_Occupation.SelectedValue);

                String objemployedIn="Goverment";

                if (Rbtn_EmpIn1.Checked == true)
                   objemployedIn="Goverment";
                else if (Rbtn_EmpIn2.Checked == true)
                   objemployedIn="Private";
                else if (Rbtn_EmpIn3.Checked == true)
                    objemployedIn="Business";
                else if (Rbtn_EmpIn4.Checked == true)
                    objemployedIn="Self-Employed";
                else if (Rbtn_EmpIn5.Checked == true)
                    objemployedIn="Defence";

                ObjEduDetail.EmployedIn=objemployedIn;

                string objIncometype="Monthly Income";

                if (Rbtn_IncomeType1.Checked == true)
                   objIncometype="Monthly Income";
                else if (Rbtn_IncomeType2.Checked == true)
                   objIncometype="Annual Income";

                ObjEduDetail.IncomeType=objIncometype;
                ObjEduDetail.CurrID=int.Parse(DDL_IncomeType.SelectedValue);
                ObjEduDetail.Income = Convert.ToInt32(Txt_Amount.Text);

                ObjEntity.AddToEduDetails(ObjEduDetail);
                ObjEntity.SaveChanges();

                Habit objhabits = new Habit();

                objhabits.MatrimonyID = 1;
                string ObjFoodtype = "Non-Vegetarian";

                if (Rbtn_FoodType1.Checked == true)
                    ObjFoodtype = "Non-Vegetarian";
                else if (Rbtn_FoodType2.Checked == true)
                    ObjFoodtype = "Vegetarian";
                else if (Rbtn_FoodType3.Checked == true)
                    ObjFoodtype = "Eggetarian";
                objhabits.Food = ObjFoodtype;

                string objSmoking = "No";

                if (Rbtn_Smoking1.Checked == true)
                    objSmoking = "No";
                else if (Rbtn_Smoking2.Checked == true)
                    objSmoking = "Yes";
                else if (Rbtn_Smoking3.Checked == true)
                    objSmoking = "Occasionally";

                objhabits.Smoking = objSmoking;

                string objDrinking = "No";

                if (Rbtn_Drinking1.Checked == true)
                    objDrinking = "No";
                else if (Rbtn_Drinking2.Checked == true)
                    objDrinking = "Yes";
                else if (Rbtn_Drinking3.Checked == true)
                    objDrinking = "Occasionally";

                objhabits.Drinking = objDrinking;

                ObjEntity.AddToHabits(objhabits);
                ObjEntity.SaveChanges();

                AstrologicalInfo objastrological = new AstrologicalInfo();

                objastrological.MatrimonyID = 1;

                string objdosham="No";
                 if (Rbtn_Chevvai1.Checked == true)
                    objdosham="No";
                else if (Rbtn_Chevvai2.Checked == true)
                    objdosham="Yes";
                else if (Rbtn_Chevvai3.Checked == true)
                    objdosham="Dont Know";

                 objastrological.Dosham = objdosham;

                 objastrological.StarID = int.Parse(DDL_Star.SelectedValue);
                 objastrological.RaasiID = int.Parse(DDL_Moon.SelectedValue);

                 ObjEntity.AddToAstrologicalInfoes(objastrological);
                 ObjEntity.SaveChanges();

                 Family objfamily = new Family();
                 objfamily.MatrimonyID = 1;

                 string ObjFamilystatus = "Middle Class";

                 if (Rbtn_FamilyStatus1.Checked == true)
                     ObjFamilystatus = "Middle Class";
                 else if (Rbtn_FamilyStatus2.Checked == true)
                     ObjFamilystatus = "Upper-Middle Class";
                 else if (Rbtn_FamilyStatus3.Checked == true)
                     ObjFamilystatus = "Rich";
                  else if (Rbtn_FamilyStatus4.Checked == true)
                     ObjFamilystatus = "Affluent";

                 objfamily.FamilyStatus = ObjFamilystatus;

                 string ObjFamilyType = "Single";

                 if (Rbtn_FamilyType1.Checked == true)
                     ObjFamilystatus = "Single";
                 else if (Rbtn_FamilyType2.Checked == true)
                     ObjFamilystatus = "Nuclear";

                 objfamily.FamilyType = ObjFamilyType;

                 string ObjFamilyValue = "Orthodox";

                 if (Rbtn_FamilyValue1.Checked == true)
                     ObjFamilyValue = "Orthodox";
                 else if (Rbtn_FamilyValue2.Checked == true)
                     ObjFamilyValue = "Traditional";
                 else if (Rbtn_FamilyValue3.Checked == true)
                     ObjFamilyValue = "Moderate";
                 else if (Rbtn_FamilyValue4.Checked == true)
                     ObjFamilyValue = "Liberal";

                 objfamily.FamilyValues = ObjFamilyValue;

                 ObjEntity.AddToFamilies(objfamily);
                 ObjEntity.SaveChanges();

                //// Second SaveChange method.
                //....Codes for 2nd table.....
                //contextObject.SaveChanges();

                //// Third SaveChange method.
                //....Codes for 3rd table.....
                //contextObject.SaveChanges();

                // If execution reaches here, it indicates the successfull completion of all                  three save operation. hence comit the transaction.
                ts.Complete();
                //}
            }
            catch (Exception ex)
            {
                // If any excption is caught, roll back the entire transaction and ends the                 transaction scope
                ts.Dispose();
            }
            finally
            {
                // Close the opened connection
                if (ObjEntity.Connection.State == ConnectionState.Open)
                {
                    ObjEntity.Connection.Close();
                }
            }
        }
    }
예제 #32
0
    protected void btn_Submit_Click(object sender, EventArgs e)
    {
        using (TransactionScope ts = new TransactionScope())
        {

            try
            {
                //using (DataContext contextObject = new DataContext(ConnectionString))
                //{
                // Open the contextObject connection state explicitly
                ObjEntity.Connection.Open();

                string hh = Session["SessionDOB"].ToString();

                //First SaveChange method.
                MatrimonyDetail objMatrim = new MatrimonyDetail();
                int? intldt = ObjEntity.MatrimonyDetails.Max(u => (int?)u.MatrimonyID);

                if (intldt == null)
                {
                    objMatrim.MatrimonyID = 1;
                }
                else
                {
                    int intldt2 = ObjEntity.MatrimonyDetails.Max(u => u.MatrimonyID);
                    objMatrim.MatrimonyID = intldt2 + 1;
                }

                objMatrim.ProfileFor = Convert.ToString(Session["ProfileFor"]);
                objMatrim.Name = Convert.ToString(Session["Sessionname"]);
                objMatrim.DOB = DateTime.Parse(hh);
                objMatrim.Gender = Convert.ToString(Session["SessionGender"]);
                objMatrim.CountryID = int.Parse(Session["SessionCountry"].ToString());
                objMatrim.MobileNo = Convert.ToString(Session["SessionMobile"]);

                if (blnNoStateCity)
                {
                    objMatrim.StateID = 999;
                    objMatrim.CityID = 999;
                    objMatrim.StateName = TxtState.Text.Trim();
                    objMatrim.CityName = TxtCity.Text.Trim();
                }
                else
                {
                    objMatrim.StateID = int.Parse(DDL_State.SelectedValue);
                    objMatrim.CityID = int.Parse(DDL_City.SelectedValue);
                    objMatrim.StateName = Convert.ToString(DDL_State.SelectedItem);
                    objMatrim.CityName = "";
                }

                objMatrim.ReligionID = int.Parse(Session["SessionReligion"].ToString());
                objMatrim.CasteID = int.Parse(Session["SessionCaste"].ToString());

                //objMatrim.SubCasteID = 4;
                //objMatrim.SubCasteID = int.Parse(DDL_SubCaste.SelectedValue);
                if (blnNoSubCaste)
                {
                    objMatrim.SubCasteID = 999;
                    objMatrim.SubcasteName = Txt_SubCaste.Text.Trim();

                }
                else
                {
                    objMatrim.SubCasteID = int.Parse(DDL_SubCaste.SelectedValue);
                    objMatrim.SubcasteName = "";
                }

                //objMatrim.GothraID = 1;
                if (blnNoSubCaste)
                {
                    objMatrim.GothraID = 999;
                    objMatrim.GothraName = Txt_Gothram.Text.Trim();

                }
                else
                {
                    objMatrim.GothraID = int.Parse(DDl_Gothra.SelectedValue);
                    objMatrim.GothraName = "";
                }

                objMatrim.Email = Convert.ToString(Session["SessionEmail"]);
                objMatrim.LoginPwd = Convert.ToString(Session["SessionPwd"]);

                string strMaritalStatus = "U";
                if (Rbtn_MartialStatus1.Checked == true)
                    strMaritalStatus = "U";
                else if (Rbtn_MartialStatus2.Checked == true)
                    strMaritalStatus = "W";
                else if (Rbtn_MartialStatus3.Checked == true)
                    strMaritalStatus = "D";
                else if (Rbtn_MartialStatus4.Checked == true)
                    strMaritalStatus = "A";

                objMatrim.MaritalStatus = strMaritalStatus;
                //objMatrim.TongueID = int.Parse(Session["SessionMotherTon"].ToString());

                //objMatrim.NoOfChild = DDL_NoOfChild.SelectedValue.ToString();
                objMatrim.NoOfChild = DDL_NoOfChild.SelectedValue.ToString();
                if (Rbtn_ChildLiving1.Checked == true)
                    objMatrim.LivingWith = "Y";
                else
                    objMatrim.LivingWith = "N";

                if (Rbtn_Caste1.Checked == true)
                    objMatrim.SameCommunity = "Y";
                else
                    objMatrim.SameCommunity = "N";

                objMatrim.DescriptionInfo = Txt_Desc.Text;
                objMatrim.ActiveInd = "N";
                objMatrim.CreatedDate = DateTime.Parse(System.DateTime.Now.ToString());
                objMatrim.UpdatedDate = DateTime.Parse(System.DateTime.Now.ToString());

                ObjEntity.AddToMatrimonyDetails(objMatrim);
                ObjEntity.SaveChanges();

                PhysicalAttr objphysical = new PhysicalAttr();
                objphysical.MatrimonyID = objMatrim.MatrimonyID;
                objphysical.HeightAttr = Convert.ToInt32(Txt_Height.Text);
                objphysical.WeightAttr = Convert.ToInt32(Txt_Weight.Text);

                string ObjBodytype = "A";

                if (Rbtn_BodyType1.Checked == true)
                    ObjBodytype = "A";
                else if (Rbtn_BodyType2.Checked == true)
                    ObjBodytype = "T";
                else if (Rbtn_BodyType3.Checked == true)
                    ObjBodytype = "S";
                else if (Rbtn_BodyType4.Checked == true)
                    ObjBodytype = "H";

                objphysical.BodyType = ObjBodytype;

                string strComplexion = "F";

                if (Rbtn_Complextion1.Checked == true)
                    strComplexion = "F";
                else if (Rbtn_Complextion2.Checked == true)
                    strComplexion = "V";
                else if (Rbtn_Complextion3.Checked == true)
                    strComplexion = "W";
                else if (Rbtn_Complextion4.Checked == true)
                    strComplexion = "B";
                else if (Rbtn_Complextion5.Checked == true)
                    strComplexion = "D";

                objphysical.Complexion = strComplexion;

                string strPhyStatus = "N";

                if (Rbtn_PhysicalStatus1.Checked == true)
                    strPhyStatus = "N";
                else if (Rbtn_PhysicalStatus2.Checked == true)
                    strPhyStatus = "P";

                objphysical.PhysicalStatus = strPhyStatus;

                ObjEntity.AddToPhysicalAttrs(objphysical);
                ObjEntity.SaveChanges();

                EduDetail ObjEduDetail = new EduDetail();

                ObjEduDetail.MatrimonyID = objMatrim.MatrimonyID;
                ObjEduDetail.EducationID = int.Parse(DDL_HighestEdu.SelectedValue);
                ObjEduDetail.OccupID = int.Parse(DDL_Occupation.SelectedValue);

                String strEmployedIn = "G";

                if (Rbtn_EmpIn1.Checked == true)
                    strEmployedIn = "G";
                else if (Rbtn_EmpIn2.Checked == true)
                    strEmployedIn = "P";
                else if (Rbtn_EmpIn3.Checked == true)
                    strEmployedIn = "B";
                else if (Rbtn_EmpIn4.Checked == true)
                    strEmployedIn = "S";
                else if (Rbtn_EmpIn5.Checked == true)
                    strEmployedIn = "D";

                ObjEduDetail.EmployedIn = strEmployedIn;

                string objIncometype = "M";

                if (Rbtn_IncomeType1.Checked == true)
                    objIncometype = "M";
                else if (Rbtn_IncomeType2.Checked == true)
                    objIncometype = "A";

                ObjEduDetail.IncomeType = objIncometype;
                ObjEduDetail.CurrID = int.Parse(DDL_IncomeType.SelectedValue);
                ObjEduDetail.Income = Convert.ToInt32(Txt_Amount.Text);

                ObjEntity.AddToEduDetails(ObjEduDetail);
                ObjEntity.SaveChanges();

                Habit objhabits = new Habit();

                objhabits.MatrimonyID = objMatrim.MatrimonyID;
                string ObjFoodtype = "Non-Vegetarian";

                if (Rbtn_FoodType1.Checked == true)
                    ObjFoodtype = "N";
                else if (Rbtn_FoodType2.Checked == true)
                    ObjFoodtype = "V";
                else if (Rbtn_FoodType3.Checked == true)
                    ObjFoodtype = "E";
                objhabits.Food = ObjFoodtype;

                string objSmoking = "No";

                if (Rbtn_Smoking1.Checked == true)
                    objSmoking = "N";
                else if (Rbtn_Smoking2.Checked == true)
                    objSmoking = "Y";
                else if (Rbtn_Smoking3.Checked == true)
                    objSmoking = "O";

                objhabits.Smoking = objSmoking;

                string objDrinking = "N";

                if (Rbtn_Drinking1.Checked == true)
                    objDrinking = "N";
                else if (Rbtn_Drinking2.Checked == true)
                    objDrinking = "Y";
                else if (Rbtn_Drinking3.Checked == true)
                    objDrinking = "O";

                objhabits.Drinking = objDrinking;

                ObjEntity.AddToHabits(objhabits);
                ObjEntity.SaveChanges();

                AstrologicalInfo objastrological = new AstrologicalInfo();

                objastrological.MatrimonyID = objMatrim.MatrimonyID;

                string objdosham = "N";
                if (Rbtn_Chevvai1.Checked == true)
                    objdosham = "N";
                else if (Rbtn_Chevvai2.Checked == true)
                    objdosham = "Y";
                else if (Rbtn_Chevvai3.Checked == true)
                    objdosham = "D";

                objastrological.Dosham = objdosham;

                objastrological.StarID = int.Parse(DDL_Star.SelectedValue);
                objastrological.RaasiID = int.Parse(DDL_Moon.SelectedValue);

                ObjEntity.AddToAstrologicalInfoes(objastrological);
                ObjEntity.SaveChanges();

                Family objfamily = new Family();
                objfamily.MatrimonyID = objMatrim.MatrimonyID;

                string ObjFamilystatus = "Middle Class";

                if (Rbtn_FamilyStatus1.Checked == true)
                    ObjFamilystatus = "M";
                else if (Rbtn_FamilyStatus2.Checked == true)
                    ObjFamilystatus = "U";
                else if (Rbtn_FamilyStatus3.Checked == true)
                    ObjFamilystatus = "R";
                else if (Rbtn_FamilyStatus4.Checked == true)
                    ObjFamilystatus = "A";

                objfamily.FamilyStatus = ObjFamilystatus;

                string ObjFamilyType = "S";

                if (Rbtn_FamilyType1.Checked == true)
                    ObjFamilystatus = "S";
                else if (Rbtn_FamilyType2.Checked == true)
                    ObjFamilystatus = "N";

                objfamily.FamilyType = ObjFamilyType;

                string ObjFamilyValue = "O";

                if (Rbtn_FamilyValue1.Checked == true)
                    ObjFamilyValue = "O";
                else if (Rbtn_FamilyValue2.Checked == true)
                    ObjFamilyValue = "T";
                else if (Rbtn_FamilyValue3.Checked == true)
                    ObjFamilyValue = "M";
                else if (Rbtn_FamilyValue4.Checked == true)
                    ObjFamilyValue = "L";

                objfamily.FamilyValues = ObjFamilyValue;

                ObjEntity.AddToFamilies(objfamily);
                ObjEntity.SaveChanges();

                ts.Complete();

            }
            catch (Exception ex)
            {
                // If any excption is caught, roll back the entire transaction and ends the                 transaction scope
                ts.Dispose();
            }
            finally
            {
                // Close the opened connection
                if (ObjEntity.Connection.State == ConnectionState.Open)
                {
                    ObjEntity.Connection.Close();
                    Response.Redirect("Home.aspx");
                }
            }
        }
    }