Monday, September 11, 2017

Create habits

A person only has a certain amount of “will power” available to them each day to spend on tasks.  Turning a task into a daily habit will stop the task requiring will power to do it.  Instead, the brain will accept the new behavior as a subconscious task.  Habits don’t require will power because they become automatic behaviors that the person does every day.  It typically takes thirty days to turn a new action into a habit.  Setup the beginning of your day to look something like this:
·         Wake up at 8:00 AM
·         Breakfast
·         Meditate for 10 minutes
·         Go for a run
·         Shower
·         Start concentration music and timer, then begin work on hardest most important task
·         30 minutes tea and drink break
·         Re-focus on hardest, most important task
·         Re-focus to finish the hardest most important task for that day
·         Check email
·         Break for Lunch

You will get more done by lunch time than most people can do in a whole day.  The “after lunch” part of the day can be spent on easier tasks, like emails, design, organization and maintenance tasks where less concentration is required.

Burn calories and control weight

    You must have heard endless times how exercise is good for your health. Do you know that it can actually help you feel positive, too? Getting the legitimate amount of exercise can step up your energy levels and even help in improving your mood swings.
    One should not exercise only to tone up the body but to feel confident. Exercise strengthens your muscles, keeps your bones strong, improves  sleep patterns and strengthens immune function.
    It's never too late to start exercising, and one doesn’t have to be an athlete to exercise.  Even starting with a 30 minutes brisk walk a day can bring a major difference in your health.
    Scientific research has shown that people who exercise regularly have more energy to think clearly.  
    Here are some unbelievable health benefits of exercising daily:
    Reduces stress
    Exercising can help manage physical and mental stress . Exercise also increases concentrations of norepinephrine, a chemical that regulates brain’s response to stress.
    Improves self-confidence
    Physical fitness advances  self-esteem and improves positive self-image.
    Exercise controls weight
    When you enlist yourself in any physical activity, you burn calories. The more intense the activity, the more calories you burn.
    Exercise combats diseases
    Regular exercise saves you from stroke, metabolic syndrome, type 2 diabetes and depression.
    Exercise boosts energy
    It distributes oxygen and nutrients to tissues and helps cardiovascular system work more efficiently. When your heart and lungs work well, you get more energy to tackle the daily chores.
    Postpones disability in adults
    Running postpones the development of disability in older adults by strengthening the muscles.
    Better sleep
    Regularly exercising helps one fall asleep faster.
    TIPS:
    • Start slow
    • Start with aerobics
    • 30 minutes per day
    • 5 minutes break at intervals
    • Drink plenty of water

Monday, August 28, 2017

Enabling Exception Handling using Log4net

CREATE TABLE [dbo].[error_log](
 [Id] [int] IDENTITY(1,1) NOT NULL,
 [Date] [datetime] NOT NULL,
 [Thread] [varchar](255) NOT NULL,
 [Level] [varchar](50) NOT NULL,
 [Logger] [varchar](255) NOT NULL,
 [Message] [varchar](4000) NOT NULL,
 [Exception] [varchar](2000) NULL,
 CONSTRAINT [PK_error_log] PRIMARY KEY CLUSTERED 
(
 [Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON)
)

configSections>
    <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler,log4net" />
  </configSections>

<appSettings>
    <add key="log4net.Internal.Debug" value="true" />
</appSettings>

<log4net>
    <appender name="AdoNetAppender" type="log4net.Appender.AdoNetAppender">
      <bufferSize value="1" />
      <filter type="log4net.Filter.LevelMatchFilter">
        <acceptOnMatch value="true" />
        <levelToMatch value="ERROR" />
      </filter>
      <filter type="log4net.Filter.DenyAllFilter" />
      <connectionType value="System.Data.SqlClient.SqlConnection, System.Data, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
      <connectionStringName value="AverosAVL" />
      <commandText value="INSERT INTO error_log ([Date],[Thread],[Level],[Logger],[Message],[Exception]) VALUES (@log_date, @thread, @log_level, @logger, @message, @exception)" />
      <parameter>
        <parameterName value="@log_date" />
        <dbType value="DateTime" />
        <layout type="log4net.Layout.RawTimeStampLayout" />
      </parameter>
      <parameter>
        <parameterName value="@thread" />
        <dbType value="String" />
        <size value="255" />
        <layout type="log4net.Layout.PatternLayout">
          <conversionPattern value="%thread" />
        </layout>
      </parameter>
      <parameter>
        <parameterName value="@log_level" />
        <dbType value="String" />
        <size value="50" />
        <layout type="log4net.Layout.PatternLayout">
          <conversionPattern value="%level" />
        </layout>
      </parameter>
      <parameter>
        <parameterName value="@logger" />
        <dbType value="String" />
        <size value="255" />
        <layout type="log4net.Layout.PatternLayout">
          <conversionPattern value="%logger" />
        </layout>
      </parameter>
      <parameter>
        <parameterName value="@message" />
        <dbType value="String" />
        <size value="4000" />
        <layout type="log4net.Layout.PatternLayout">
          <conversionPattern value="%message" />
        </layout>
      </parameter>
      <parameter>
        <parameterName value="@exception" />
        <dbType value="String" />
        <size value="2000" />
        <layout type="log4net.Layout.ExceptionLayout" />
      </parameter>
    </appender>
    <root>
      <appender-ref ref="AdoNetAppender" />
    </root>

  </log4net>

Friday, August 25, 2017

Import Excel Into SQL Server using MVC


[Authorize]
    public class ImportDataController : Controller
    {
        SMSNotificationService smsNotification = new SMSNotificationService();
        // GET: ImportData
        public ActionResult Index()
        {
            return View();
        }
        [HttpPost]
        public ActionResult ImportUsers(HttpPostedFileBase file, string sendSms)
        {
            try
            {
                string ImportSMSAlertMessage = new LookupService().GetConfigurationKeyValue("ImportSMSAlertMessage");
                string role_id = new UserService().GetUserRoleByRoleKey("guide");
                string senderName = "daifnaqaba";
                string usersAlreadyExists = "";

                DataSet ds = new DataSet();
                string sendSMS = Request["sendSms"];
                if (Request.Files["file"].ContentLength > 0)
                {
                    string fileExtension =
                                         System.IO.Path.GetExtension(Request.Files["file"].FileName);

                    if (fileExtension == ".xls" || fileExtension == ".xlsx")
                    {
                        string fileLocation = Server.MapPath("~/Content/") + Request.Files["file"].FileName;
                        if (System.IO.File.Exists(fileLocation))
                        {
                            System.IO.File.Delete(fileLocation);
                        }
                        Request.Files["file"].SaveAs(fileLocation);
                        string excelConnectionString = string.Empty;
                        excelConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + fileLocation + ";Extended Properties=\"Excel 12.0;HDR=Yes;IMEX=2\"";
                        //connection String for xls file format.
                        if (fileExtension == ".xls")
                        {
                            excelConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + fileLocation + ";Extended Properties=\"Excel 8.0;HDR=Yes;IMEX=2\"";
                        }
                        //connection String for xlsx file format.
                        else if (fileExtension == ".xlsx")
                        {
                            excelConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + fileLocation + ";Extended Properties=\"Excel 12.0;HDR=Yes;IMEX=2\"";
                        }
                        //Create Connection to Excel work book and add oledb namespace
                        OleDbConnection excelConnection = new OleDbConnection(excelConnectionString);
                        excelConnection.Open();
                        DataTable dt = new DataTable();

                        dt = excelConnection.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
                        if (dt == null)
                        {
                            return null;
                        }

                        String[] excelSheets = new String[dt.Rows.Count];
                        int t = 0;
                        //excel data saves in temp file here.
                        foreach (DataRow row in dt.Rows)
                        {
                            excelSheets[t] = row["TABLE_NAME"].ToString();
                            t++;
                        }

                        OleDbConnection excelConnection1 = new OleDbConnection(excelConnectionString);


                        string query = string.Format("Select * from [{0}]", excelSheets[0]);
                        using (OleDbDataAdapter dataAdapter = new OleDbDataAdapter(query, excelConnection1))
                        {
                            dataAdapter.Fill(ds);
                        }
                        excelConnection.Close();
                    }

                    for (int i = 1; i < ds.Tables[0].Rows.Count; i++)
                    {
                        string conn = ConfigurationManager.ConnectionStrings["AverosAVLProd"].ConnectionString;
                        SqlConnection con = new SqlConnection(conn);
                        string first_name = Convert.ToString(ds.Tables[0].Rows[i][0]);
                        string email = Convert.ToString(ds.Tables[0].Rows[i][1]);
                        string password = Convert.ToString(ds.Tables[0].Rows[i][2]);
                        string user_external_identifier = email;
                        string contact_number = password;
                        DateTime created_on = DateTime.Now;

                        bool userExists = new UserService().CheckIfUserExists(email);

                        if (!userExists)
                        {
                            string query = "Insert into users(user_external_identifier,first_name,last_name,email,password,contact_number,role_id,created_on,updated_on,status) Values('" + user_external_identifier + "',N'" + first_name + "','','" + email + "','" + password + "','" + contact_number + "'," + role_id + ",'" + created_on.ToString("yyyy-MM-dd HH:mm:ss") + "','" + created_on.ToString("yyyy-MM-dd HH:mm:ss") + "','A')";
                            con.Open();
                            SqlCommand cmd = new SqlCommand(query, con);
                            int isSaved = 0;

                            isSaved = cmd.ExecuteNonQuery();
                            if (isSaved != 0)
                            {
                                TempData["SuccessMessage"] = "users created successfully.";
                            }
                            con.Close();
                        }
                        else
                        {
                            usersAlreadyExists += email + ", ";
                        }

                        if (sendSms == "on")
                        {
                            string contactNumber = smsNotification.AdjustPhoneNumber(contact_number);
                            string ImportSMSAlertMessageTranslated = ImportSMSAlertMessage.Replace("{U}", email).Replace("{P}", password);
                            string sentStatus = smsNotification.SendSMS(contactNumber, ImportSMSAlertMessageTranslated, senderName);
                            if (true || sentStatus != "")
                            {
                                string query = "Insert into sms_logs(sms_status, sent_number,sent_message,sent_date) Values(N'" + sentStatus.ToString() + "','" + contact_number + "',N'" + ImportSMSAlertMessageTranslated + "','" + created_on.ToString("yyyy-MM-dd HH:mm:ss") + "')";
                                con.Open();
                                SqlCommand cmd = new SqlCommand(query, con);
                                cmd.ExecuteNonQuery();
                                con.Close();
                            }
                        }
                    }
                }

                if (!string.IsNullOrEmpty(usersAlreadyExists))
                {
                    TempData["UsersAlreadyExist"] = usersAlreadyExists;
                }

                return RedirectToAction("Index");
            }
            catch (Exception ex)
            {
                new LogService().LogException(ex);
                TempData["SuccessMessage"] = ex.Message;
                return RedirectToAction("Index");
            }
            finally
            {
                string fileLocation = Server.MapPath("~/Content/") + Request.Files["file"].FileName;
                if (System.IO.File.Exists(fileLocation))
                {
                    System.IO.File.Delete(fileLocation);
                }
            }
        }

    }

Popular Posts