Monday 30 December 2019

How to replace all occurrences of a string in JavaScript

How to replace all occurrences of a string in JavaScript

Use the JavaScript replace() method

You can use the JavaScript replace() method in combination with the regular expression to find and replace all occurrences of a word or substring inside any string.

Let's check out an example to understand how this method basically works:

<script>
    var myStr = 'freedom is not worth having if it does not include the freedom to make mistakes.';
    var newStr = myStr.replace(/freedom/g, "liberty");
   
    // Printing the modified string
    document.write(newStr);
</script>

<script>
/* Define function for escaping user input to be treated as
   a literal string within a regular expression */
function escapeRegExp(string){
    return string.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
}

/* Define functin to find and replace specified term with replacement string */
function replaceAll(str, term, replacement) {
  return str.replace(new RegExp(escapeRegExp(term), 'g'), replacement);
}

/* Testing our replaceAll() function  */
var myStr = 'if the facts do not fit the theory, change the facts.';
var newStr = replaceAll(myStr, 'facts', 'statistics')

// Printing the modified string
document.write(newStr);
</script>

How to refresh a page with jQuery

How to refresh a page with jQuery

Use the JavaScript location.reload() Method

You can simply use the JavaScript location.reload() method to refresh or reloads the page. This method optionally accepts a Boolean parameter true or false.

If the parameter true is specified, it causes the page to always be reloaded from the server. But, if it is false (which is default) or not specified, the browser may reload the page from its cache.

Let's check out an example to understand how this method basically works:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Reload the Page Using jQuery</title>
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<script>
    $(document).ready(function(){
        $("button").click(function(){
            location.reload(true);
        });
    });
</script>
</head>
<body>
    <button type="button">Reload page</button> 
</body>
</html>

How to Remove a Property from a JavaScript Object

How to Remove a Property from a JavaScript Object

Use the delete Operator

You can use the delete operator to completely remove the properties from the JavaScript object. Deleting is the only way to actually remove a property from an object.

Setting the property to undefined or null only changes the value of the property. It does not remove property from the object. Let's take a look at the following example:

<script>
    var person = {
        name: "Harry",
        age: 16,
        gender: "Male"
    };
   
    // Deleting a property completely
    delete person.age;
    alert(person.age); // Outputs: undefined
    console.log(person); // Prints: {name: "Harry", gender: "Male"}
   
    // Setting the property value to undefined
    person.gender = undefined;
    alert(person.gender); // Outputs: undefined
    console.log(person); // Prints: {name: "Harry", gender: undefined}
</script>

How to Parse JSON in JavaScript

How to Parse JSON in JavaScript

Use the JSON.parse() Method

You can simply use the JSON.parse() method to parse a JSON string in JavaScript.

The following example will show you how to convert a JSON string into a JS object and access individual values with pure JavaScript. It works in all major browsers

<script>
// Store JSON data in a JS variable
var json = '{"name": "Harry", "age": 18, "country": "United Kingdom"}';

// Converting JSON encoded string to JS object
var obj = JSON.parse(json);

// Accessing individual value from JS object
alert(obj.name); // Outputs: Harry
alert(obj.age); // Outputs: 18
alert(obj.country); // Outputs: United Kingdom
</script>

How to find substring between the two words using jQuery

Use the JavaScript match() method

You can use the JavaScript match() method to extract substring between two words.

The following example will show you how to extract substring between the two words using the match() method and a simple regular expression pattern.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery Get Substring Between Two Words</title>
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<script>
    $(document).ready(function(){
        $("button").click(function(){
            var myStr = "The quick brown fox jumps over the lazy dog.";
            var subStr = myStr.match("quick(.*)lazy");
            alert(subStr[1]);
        });
    });
</script>
</head>
<body>
    <p>Click the following button to get the substring between the word "quick" and "lazy" from the string "The quick brown fox jumps over the lazy dog."</p>
    <button type="button">Get Substring</button>
</body>
</html>

How to Get the Value of Selected Option in a Select Box Using jQuery

How to Get the Value of Selected Option in a Select Box Using jQuery

Use the jQuery :selected Selector

You can use the jQuery :selected selector in combination with the val() method to find the selected option value in a select box or dropdown list.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery Get Selected Option Value</title>
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<script>
$(document).ready(function(){
    $("select.country").change(function(){
        var selectedCountry = $(this).children("option:selected").val();
        alert("You have selected the country - " + selectedCountry);
    });
});
</script>
</head>
<body>
    <form>
        <label>Select Country:</label>
        <select class="country">
            <option value="usa">United States</option>
            <option value="india">India</option>
            <option value="uk">United Kingdom</option>
        </select>
    </form>
</body>
</html>

How to get the current page url using jQuery

Use the syntax $(location).attr("href");

You can use the Location object and jQuery attr() method to get the URL of the current page.

Let's take a look at an example to understand how it actually works:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery Get Current Page URL</title>
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<script>
    $(document).ready(function(){
        $("button").click(function(){
            var pageURL = $(location).attr("href");
            alert(pageURL);
        });
    });
</script>
</head>
<body>
    <button type="button">Get URL</button>
</body>
</html>

How to check an element is visible or not using jQuery

Use the jQuery :visible Selector

You can use the jQuery :visible selector to check whether an element is visible in the layout or not. This selector will also select the elements with visibility: hidden; or opacity: 0;, because they preserve space in the layout even they are not visible to the eye.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery Test If an Element is Visible</title>
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<script>
    $(document).ready(function(){
        $("button").click(function(){
            // show hide paragraph on button click
            $("p").toggle("slow", function(){
                // check paragraph once toggle effect is completed
                if($("p").is(":visible")){
                    alert("The paragraph  is visible.");
                } else{
                    alert("The paragraph  is hidden.");
                }
            });
        });
    });
</script>
</head>
<body>
    <button type="button">Toggle Paragraph Display</button>
    <p style="display: none;">Lorem ipsum dolor sit amet adipi elit...</p>
</body>
</html>

How to remove white spaces from a string in jQuery

Use the jQuery $.trim() function

You can use the jQuery $.trim() function to remove all the spaces (including non-breaking spaces), newlines, and tabs from the beginning and end of the specified string.

However, the whitespaces in the middle of the string are preserved. The following example will show you how to remove leading and trailing whitespaces from a string of text.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Remove White Space from Strings</title>
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<script>
    $(document).ready(function(){
        var myStr = $(".original").text();
        var trimStr = $.trim(myStr);
        $(".trimmed").html(trimStr);
    });
</script>
</head>
<body>
    <h3>Original String</h3>
    <pre class="original">      Paragraph of text with       multiple    white   spaces before and after.       </pre>
    <br>
    <h3>Trimmed String</h3>
    <pre class="trimmed"></pre>
</body>
</html>

How to remove the attribute from an HTML element in jQuery

Use the jQuery removeAttr() methods

You can use the jQuery removeAttr() method to remove the attributes from an HTML element.

In the following example when you click the "Remove Link" button it will remove the href attribute from the link. Let's try it out and see how this method works:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery Removing Attribute from HTML Element</title>
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<script>
    $(document).ready(function() {
        $(".remove-attr").click(function(){           
            $("a").removeAttr("href");
        });
    });
</script>
</head>
<body>
    <button type="button" class="remove-attr">Remove Link</button>
    <a href="#">Demo Link</a>
</body>
</html>

How to add new elements to DOM in jQuery

Use the jQuery append() or prepend() method
You can add or insert elements to DOM using the jQuery append() or prepend() methods. The jQuery append() method insert content to end of matched elements, whereas the prepend() method insert content to the beginning of matched elements.

The following example will show you how to add new items to the end of an HTML ordered list easily using the jQuery append() method. Let's try it out and see how it works:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery Add Elements to DOM</title>
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<script>
    $(document).ready(function(){
        $("button").click(function(){
            $("ol").append("<li>list item</li>");
        });
    });
</script>
</head>
<body>
    <button>Add new list item</button>
    <ol>
        <li>list item</li>
        <li>list item</li>
        <li>list item</li>
    </ol>
</body>
</html>

How to add CSS properties to an element dynamically using jQuery

Use the jQuery css() method

You can use the jQuery css() method to add new CSS properties to an element or modify the existing properties values dynamically using jQuery.

<!DOCTYPE html>
<html lang="en">
<head>
<title>jQuery Add CSS Property Dynamically</title>
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<script>
    $(document).ready(function(){
        $("h1").css("color", "red");
        $("p").css({
            "background-color": "yellowgreen",
            "font-weight": "bold"
        });
    });
</script>
</head>
<body>
    <h1>This is a heading</h1>
    <p>This is a paragraph.</p>
</body>
</html>

How to call a function automatically after waiting for some time in jQuery

Use the jQuery delay() method

You can use the jQuery delay() method to call a function after waiting for some time. Simply pass an integer value to this function to set the time interval for the delay in milliseconds.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery Execute a Function after Certain Time</title>
<style>
    img{
        display: none;
    }
</style>
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<script>
function showImage(){
    $("img").fadeIn(500);
}
$(document).ready(function(){
    $(".show-image").click(function(){
        $(this).text('loading...').delay(1000).queue(function() {
            $(this).hide();
            showImage(); //calling showimage() function
            $(this).dequeue();
        });       
    });
});
</script>
</head>
<body>
    <button type="button" class="show-image">Show Image</button>
    <img src="../images/kites.jpg" alt="Flying Kites">
</body>
</html>

How to check if an element exists in jQuery

Use the jQuery .length Property

You can use the jQuery .length property to determine whether an element exists or not in case if you want to fire some event only if a particular element exists in DOM.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery Test If an Element Exists</title>
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<script>
$(document).ready(function(){
    $("button").click(function(){
        if($("#myDiv").length){
            alert("The element you're testing is present.");
        }
    });
});
</script>
</head>
<body>
    <div id="myDiv"></div>   
    <p>The quick brown fox jumps over the lazy dog</p>
    <button>Check Element</button>
</body>
</html>

Wednesday 29 May 2019

CRUD operation using entityframework and stored procedure - part1

 CRUD operation using entityframework and stored procedure - part1

  [VerifyUserSesssion]
        public ActionResult getCustomerProjectList(RequestParam objRequestParam)
        {
            WrapperCustomerProjectMas ReturnlistAll = new WrapperCustomerProjectMas();
            REGISTERMAS objREGISTERMAS = (REGISTERMAS)Session["UserSession"];
            List<CUSTOMERPROJECTMAS> list = db.GetCustomerProjectList(objREGISTERMAS.USERCD);
            ReturnlistAll.CustomerprojectMasList = list;

            var total = ReturnlistAll.CustomerprojectMasList.Select(p => p.CUSTOMERPROJECTMASCD).Count();
            var pageSize = objRequestParam.PageSize;
            var page = objRequestParam.PageIndex;
            var skip = pageSize * (page - 1);

            List<CUSTOMERPROJECTMAS> RegisterMasListPage = ReturnlistAll.CustomerprojectMasList.Skip(skip).Take(pageSize).ToList();
            Pager lpPager = new Pager(total, page, pageSize);

            ReturnlistAll.CustomerprojectMasList = RegisterMasListPage.OrderBy(x => x.CUSTOMERPROJECTMASCD).ToList();
            ReturnlistAll.Pager = lpPager;

            ViewBag.UserList = list;
            return Json(new { id = Convert.ToString(0), Data = ReturnlistAll }, JsonRequestBehavior.AllowGet);
        }

        [VerifyUserSesssion]
        [HttpPost]
        public ActionResult addEditCustomerProject(CUSTOMERPROJECTMAS request)
        {
            if (ModelState.IsValid)
            {
                //reqREGISTERMAS.PROJECTID = reqREGISTERMAS.PROJECTID.ToString
                int result = db.addEditCustomerProjectMas(request);
                return Json(new { id = Convert.ToString(result), msg = "Something went wrong, Please try again" }, JsonRequestBehavior.AllowGet);
            }
            else
            {
                List<string> errorList = new List<string>();
                foreach (ModelState modelState in ViewData.ModelState.Values)
                {
                    foreach (ModelError error in modelState.Errors)
                    {
                        errorList.Add(error.ErrorMessage);
                    }
                }
                return Json(new { id = Convert.ToString(0), msg = errorList }, JsonRequestBehavior.AllowGet);
            }

        }
               
               
               
                 public List<CUSTOMERPROJECTMAS> GetCustomerProjectList(int UserId)
        {
            List<SqlParameter> SqlParametersList = new List<SqlParameter>();
            SqlParametersList.Add(new SqlParameter("UserId", UserId.handleDBNull()));
            return new AppDataConetext().Database.SqlQuery<CUSTOMERPROJECTMAS>("spGetCustomerProjectList".getSql(SqlParametersList), SqlParametersList.Cast<object>().ToArray()).ToList();
        }
               
                public int addEditCustomerProjectMas(CUSTOMERPROJECTMAS request)
        {
            int Success = 0;
            List<SqlParameter> SqlParametersList = new List<SqlParameter>();
            SqlParametersList.Add(new SqlParameter("CUSTOMERPROJECTMASCD", request.CUSTOMERPROJECTMASCD.handleDBNull()));
            SqlParametersList.Add(new SqlParameter("CUSTOMERCD", request.CUSTOMERCD.handleDBNull()));
            SqlParametersList.Add(new SqlParameter("PROJECTCD", request.PROJECTCD.handleDBNull()));
            SqlParametersList.Add(new SqlParameter("RESPPERSON_CD", request.RESPPERSON_CD.handleDBNull()));
            SqlParametersList.Add(new SqlParameter("HOD_CD", request.HOD_CD.handleDBNull()));
            SqlParametersList.Add(new SqlParameter("MAXPROJECTLIMIT", request.MAXPROJECTLIMIT.handleDBNull()));
            SqlParametersList.Add(new SqlParameter("STATUS", request.STATUS.handleDBNull()));
            SqlParametersList.Add(new SqlParameter("CCMAILIDS", request.CCMAILIDS.handleDBNull()));
            SqlParametersList.Add(new SqlParameter("ENGINEER_CD", request.ENGINEER_CD.handleDBNull()));
            SqlParametersList.Add(new SqlParameter("BILLING", request.BILLING.handleDBNull()));
            if (request.CUSTOMERPROJECTMASCD != 0)
            {
                SqlParametersList.Add(new SqlParameter("FLAG", "UPDATE"));
            }
            else
            {
                SqlParametersList.Add(new SqlParameter("FLAG", "INSERT"));
            }

            SqlParameter loSuccess = new SqlParameter("RETURNVAL", Success);
            loSuccess.Direction = ParameterDirection.Output;
            SqlParametersList.Add(loSuccess);
            new AppDataConetext().Database.SqlQuery<object>("spCustomerProjectMas".getSql(SqlParametersList), SqlParametersList.Cast<object>().ToArray()).FirstOrDefault();
            Success = Convert.ToInt32(loSuccess.Value);
            return Success;
        }
               
               
               
               
               
                Text
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

 --USERCD    USERNM    DEPARTMENT    USERLEVEL    CUSTOMERCD    PROJECTID    EMAILID    PASSWORD    MOBILENO    STATUS    ENTRYDATE
CREATE PROCEDURE [dbo].[spCustomerProjectMas]     
@CUSTOMERPROJECTMASCD AS INT,
@CUSTOMERCD AS INT,
@PROJECTCD AS INT,    
@RESPPERSON_CD AS INT,
@HOD_CD VARCHAR(1000), 
@MAXPROJECTLIMIT AS INT,
@STATUS AS VARCHAR(10)=null, 
@CCMAILIDS VARCHAR(1000), 
@ENGINEER_CD  AS INT,
@BILLING AS VARCHAR(10)=null,
@FLAG VARCHAR(20),
@ReturnVal int output
AS      
BEGIN   
 DECLARE @MAXPROCCD AS INTEGER     
 DECLARE @MAXORD AS INTEGER  

 DECLARE @RandomTicketId AS INTEGER

 --DECLARE @ReturnVal int     
 BEGIN     

  IF @FLAG ='UPDATE' BEGIN 
  IF NOT EXISTS (SELECT CUSTOMERCD FROM [CUSTOMERPROJECTMAS] WHERE CUSTOMERCD = @CUSTOMERCD AND PROJECTCD=@PROJECTCD AND CUSTOMERPROJECTMASCD !=@CUSTOMERPROJECTMASCD)
    BEGIN
      UPDATE  [CUSTOMERPROJECTMAS] 
                SET    CUSTOMERCD=@CUSTOMERCD,                PROJECTCD=@PROJECTCD,                RESPPERSON_CD=@RESPPERSON_CD,
                    HOD_CD=@HOD_CD,                        MAXPROJECTLIMIT=@MAXPROJECTLIMIT,    [STATUS]=@STATUS,
                    CCMAILIDS=@CCMAILIDS,                ENGINEER_CD=@ENGINEER_CD,            BILLING=@BILLING
                WHERE
                    CUSTOMERPROJECTMASCD=@CUSTOMERPROJECTMASCD
           
     
           SET @ReturnVal = @CUSTOMERPROJECTMASCD; 
        --RETURN 
     END
    ELSE
    BEGIN
        SET @ReturnVal = -1 -- User Exist 
    END
  END 
  ELSE IF @FLAG ='INSERT' BEGIN     

  IF NOT EXISTS (SELECT CUSTOMERCD FROM [CUSTOMERPROJECTMAS] WHERE CUSTOMERCD = @CUSTOMERCD AND PROJECTCD=@PROJECTCD)
    BEGIN
        INSERT INTO [CUSTOMERPROJECTMAS]
                (
                    CUSTOMERCD,            PROJECTCD,                RESPPERSON_CD,        HOD_CD,            MAXPROJECTLIMIT,           
                    [STATUS],            CCMAILIDS,                ENGINEER_CD,        BILLING
                )
        VALUES
                (
                    @CUSTOMERCD,        @PROJECTCD,                @RESPPERSON_CD,        @HOD_CD,        @MAXPROJECTLIMIT,   
                    @STATUS,            @CCMAILIDS,                @ENGINEER_CD,        @BILLING       
                   
                )
     
       SET @ReturnVal = (SELECT SCOPE_IDENTITY());
     END
    ELSE
    BEGIN
        SET @ReturnVal = -1 -- User Exist 
    END
  END     
  ELSE IF @FLAG ='DELETE' BEGIN     
       SET @ReturnVal = 2 
         
  END     
  
   
    --select 500;
 --select @ReturnVal;
END
END


Text
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------


--exec [dbo].[spGetCustomerProjectList] 2    

CREATE PROC [dbo].[spGetCustomerProjectList]     
@UserCD AS INT
AS      
BEGIN   
      SELECT
        CP.*,
        U.USERNM RESPONSIBLEPERSON,
        --U1.USERNM HOD,
        C.PARTYNM PARTYNM,
        P.PROJECTNM PROJECTNM,
       
        (STUFF((SELECT CAST(', ' + USERNM AS VARCHAR(MAX))
         FROM USERMAS B
         WHERE  B.USERCD in (SELECT * FROM SplitData(CP.HOD_CD,','))
         FOR XML PATH ('')), 1, 2, '')) AS HOD,
       
         ISNULL(( SELECT SUM( ISNULL(CP_L.LICENCE,0)) from CUSTOMERPROJECT_LICENCE CP_L where CP_L.CUSTOMERPROJECTID=CP.CUSTOMERPROJECTMASCD ) , 0) LICENCECOUNT

       FROM CUSTOMERPROJECTMAS CP
      LEFT JOIN USERMAS U on U.USERCD=CP.RESPPERSON_CD
      --LEFT JOIN USERMAS U1 on U1.USERCD=CP.HOD_CD
      LEFT JOIN CUSTOMERMAS C on C.CUSTOMERCD=CP.CUSTOMERCD
      LEFT JOIN PROJECTMAS P on P.PROJECTCD=CP.PROJECTCD
     
END


public class AppDataConetext : DbContext
    {
        //public static string _DBHost = ConfigurationManager.AppSettings["_DBHost"];
        public static string Conn = "Data Source=IIPP;Initial Catalog=dbma5;Persist Security Info=True;User ID=sa;Password=sa123";
       
        public AppDataConetext()
        //: base("name=Conn")
        : base(Conn)
        {
        }
               
                public List<TicketMasModel> getTicketList(int UserId, int CustomerCD, int ENGINEERCD, string AllTikcetFlag, string Where, string OrderBy)
        {
            List<SqlParameter> SqlParametersList = new List<SqlParameter>();
            SqlParametersList.Add(new SqlParameter("UserId", UserId.handleDBNull()));
            SqlParametersList.Add(new SqlParameter("CUSTOMERCD", CustomerCD.handleDBNull()));
            SqlParametersList.Add(new SqlParameter("ENGINEERCD", ENGINEERCD.handleDBNull()));
            SqlParametersList.Add(new SqlParameter("ALLTICKET", AllTikcetFlag.handleDBNull()));
            SqlParametersList.Add(new SqlParameter("WHERE", Where.handleDBNull()));
            SqlParametersList.Add(new SqlParameter("ORDERBY", OrderBy.handleDBNull()));
            return new AppDataConetext().Database.SqlQuery<TicketMasModel>("spGetTicketListByUser".getSql(SqlParametersList), SqlParametersList.Cast<object>().ToArray()).ToList();
        }
                /*all other*/
        }


   public int ExecuteSqlCommand(string SQL)
        {
            try
            {
                List<SqlParameter> SqlParametersList = new List<SqlParameter>();
                return new AppDataConetext().Database.ExecuteSqlCommand(SQL);
            }
            catch (Exception ex)
            {
                CommonFunction.addLog(ex, "AppDataContext.cs - ExecuteSqlCommand - SQL:" + SQL);
            }
            return 0;

        }
        public DataTable ExecuteSqlSelectCommand(string sql)
        {
            DataTable dt = new DataTable();
            try
            {
                AppDataConetext obj = new AppDataConetext();
                using (SqlConnection con = new SqlConnection(Conn))
                {
                    using (SqlCommand cmd = new SqlCommand(sql, con))
                    {
                        cmd.CommandType = CommandType.Text;
                        con.Open();
                        SqlDataAdapter da = new SqlDataAdapter(cmd);
                        da.Fill(dt);
                    }
                }
                return dt;
            }
            catch (Exception ex)
            {
                CommonFunction.addLog(ex, "Gloabal.asax file - Application_Error");
            }
            return dt;
        }
               
                  public static void addLog(Exception ex, string Data)
        {
            try
            {
                string path = HttpContext.Current.Server.MapPath("~/ClientData/error.txt");
                REGISTERMAS objREGISTERMAS = (REGISTERMAS)HttpContext.Current.Session["UserSession"];
                string UserDetails = "-";
                if (objREGISTERMAS != null)
                {
                    UserDetails = "UserNM:" + objREGISTERMAS.USERNM + ", UserID:" + objREGISTERMAS.USERCD;
                }
                UserDetails += "  ,  IP Address:" + GetLocalIPAddress();
                if (!File.Exists(path))
                {
                    File.Create(path);
                    TextWriter tw = new StreamWriter(path);
                    tw.WriteLine(DateTime.Now.ToString());
                    tw.WriteLine("\n File Created...");
                    tw.WriteLine("\n  " + path + "\n");
                    tw.Close();
                }
                else if (File.Exists(path))
                {
                    using (var tw = new StreamWriter(path, true))
                    {
                        string ErrorLog = "";
                        string Url = HttpContext.Current.Request.Url.ToString();
                        string currentDateTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff");

                        ErrorLog += "------------------------------------------------------------------------------------------------------------------------------------ \n ";
                        ErrorLog += "\n\n 1. TRACE TIME    =>" + currentDateTime;
                        ErrorLog += "\n\n 2. Current URL   =>" + Url;
                        ErrorLog += "\n\n 3. Logged In User=>" + UserDetails;
                        ErrorLog += "\n\n 4. " + Data;
                        ErrorLog += "\n\n\n--------------------------------- ERROR - TRY CATCH  ------------------------------------------------------------------------------ \n   ";
                        ErrorLog += "\n\n 5. =><b>" + ex.Message + "</b>";
                        ErrorLog += "\n\n 6. =>" + ex.InnerException;
                        ErrorLog += "\n\n 7. =>" + ex.StackTrace;
                        //ErrorLog +="\n 7. =>" + ex.ToString();
                        ErrorLog += "------------------------------------------------------------------------------------------------------------------------------------ \n ";

                        tw.WriteLine(ErrorLog);
                        tw.Close();
                        string strMailBody = CommonFunction.ReadHtml("EmailHeaderFooter.html", "", "");

                        string greeting = "<p>Hi Developer, <br>Please check this error </p> <br><h5 style='color:red'>" + ex.Message + "</h5>";
                        strMailBody = strMailBody.Replace("[MailContent]", greeting + "" + ErrorLog.Replace("\n", "<br>"));
                        string ToMail = Convert.ToString(SETTING.KEY.DEVELOPER_EMAILID);
                        int retval = SendMail.sendMailWithAuthentication(null, ToMail, "", "", "CRM Error in " + Url + " at " + currentDateTime, strMailBody, "", null);
                    }
                }
            }
            catch (Exception)
            {
            }

        }

 public static class Helper
    {
        /// <summary>
        /// Handle the Database NULL Value for the Sql Value
        /// </summary>
        /// <param name="requestValue">object which may have DBNUll</param> 
        public static object handleDBNull(this object requestValue)
        {
            if (requestValue == null)
            {
                return DBNull.Value;
            }
            return requestValue;
        }
        public static object handleDBNullDate(this string requestValue)
        {
            if (string.IsNullOrEmpty(requestValue))
            {
                return SqlDateTime.Null;
            }
            return requestValue;
        }
        /// <summary>
        /// Generate SQL Statement from all it's parameter and procedure name
        /// </summary>
        /// <param name="spName">Database procedure name</param>
        /// <param name="requestParameters">List of Sql Parameters</param>
        public static string getSql(this string spName, List<SqlParameter> requestParameters = null)
        {
            string SpParameter = string.Empty;
            if (requestParameters != null)
            {
                for (int Index = 0; Index < requestParameters.Count; Index++)
                {
                    if (Index > 0)
                    {
                        SpParameter += ", @" + requestParameters[Index].ParameterName; ;
                    }
                    else
                    {
                        SpParameter += " @" + requestParameters[Index].ParameterName;
                    }
                    if (requestParameters[Index].Direction == System.Data.ParameterDirection.Output)
                    {
                        SpParameter += " OUT ";
                    }
                }
            }
            return "EXEC [" + spName + "]" + SpParameter;
        }
    }
       
       
         public class VerifyUserSesssion : ActionFilterAttribute
    {
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            if (HttpContext.Current.Session["UserSession"] == null)
            {
                LogInViewModel requestLogInViewModel = new LogInViewModel();

                if (!string.IsNullOrEmpty(CommonFunction.GetAuthCookie(HttpContext.Current.Request.Cookies["u"])))
                {
                    AppDataConetext db = new AppDataConetext();
                    requestLogInViewModel.Email = CommonFunction.Decrypt(CommonFunction.GetAuthCookie(HttpContext.Current.Request.Cookies["u"]), "Email");// cookie_u.Value;
                    requestLogInViewModel.Password = CommonFunction.Decrypt(CommonFunction.GetAuthCookie(HttpContext.Current.Request.Cookies["p"]), "Password");// cookie_p.Value;
                    REGISTERMAS objREGISTERMAS = db.ValidateUser(requestLogInViewModel);
                    if (objREGISTERMAS != null)
                    {
                        if (objREGISTERMAS.STATUS == "1")
                        {
                            HttpContext.Current.Session["UserSession"] = objREGISTERMAS;
                            //return RedirectToRoute("Default", new { action = "MyTickets2", controller = "TicketSystem" });
                        }
                    }
                }
            }

            if (HttpContext.Current.Session["UserSession"] == null && filterContext.RequestContext.HttpContext.Request.IsAjaxRequest())
            {
                HttpContext.Current.Response.StatusCode = 403;
                HttpContext.Current.Response.Write("Authentication Failed");
                HttpContext.Current.Response.End();
            }
            bool EnableUserLogin = Convert.ToBoolean(SETTING.KEY.ENABLE_USERLOGIN);
            if (!EnableUserLogin)
            {
                filterContext.Result = new RedirectToRouteResult("Default", new RouteValueDictionary(new { controller = "TicketSystem", action = "LogIn", returnUrl = HttpContext.Current.Request.RawUrl }));
            }
            if (HttpContext.Current.Session["UserSession"] == null)
            {

                filterContext.Result = new RedirectToRouteResult("Default", new RouteValueDictionary(new { controller = "TicketSystem", action = "LogIn", returnUrl = HttpContext.Current.Request.RawUrl }));
                //filterContext.Result = new RedirectToRouteResult ("crmLogin", new RouteValueDictionary(new { controller = "TicketSystem", action = "LogIn",Areas= "Crm", returnUrl = HttpContext.Current.Request.RawUrl }));
                //filterContext.Result = new RedirectResult("/crm", true);

            }
            base.OnActionExecuting(filterContext);
        }
    }


       
       
            SET @SQLQuerySELECT = ' WITH PAGED AS
        (SELECT
        row_number() OVER(  '+@ORDERBY+') AS RowNumber ,
                T.ORGTICKETID,   
               
                SET @SQLQuery = @SQLQuery + '
         )  SELECT *, (SELECT COUNT(*) FROM PAGED) AS TotalRecordCount ,'+ CONVERT(NVARCHAR(10), @PageSize) +' as PageSize
        FROM PAGED              
        WHERE
        PAGED.RowNumber BETWEEN (' + CONVERT(NVARCHAR(10), @PageIndex) + ' - 1) *
        ' + CONVERT(NVARCHAR(10), @PageSize) + ' + 1 AND
        ' + CONVERT(NVARCHAR(10), @PageIndex) + ' *
        ' + CONVERT(NVARCHAR(10), @PageSize) + ' ' 
               
               
                EXECUTE(@SQLQuerySELECT +' '+ @SQLQuerySELECT_ +' '+ @SQLQueryJOIN +' '+@SQLQuery)







Asp.net tutorials