How to set Bootstrap navbar as Active for ASP.NET Site Master


Hmm.. It’s May 1st, 2016 and John Snow finally breathes again!!

Coming back to reality, I have faced a small problem earlier today with Bootstrap. I have a small ASP.NET web site, which uses a Master page (Site.Master). And I have added a Navbar in the master page so that it can be utilized from every pages that will be using the Site.Master.

Here is how my Navbar section looks in the Site.Master Page:

<div id="navbar" class="navbar navbar-fixed-top">
<div class="navbar-inner">
<div class="container">
<a class="brand" href="~/">My Demo Site</a>
<a class="btn btn-navbar" data-toggle="collapse" data-target=".nav-collapse">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</a>
<div class="nav-collapse collapse">
<ul class="nav navbar-nav">
	<li><a href="~/">Home</a></li>
	<li><a href="~/DemoPage1.aspx">Demo 1</a></li>
	<li><a href="~/DemoPage2.aspx">Demo 2</a></li>
	<li><a href="~/DemoPage3.aspx">Demo 3</a></li>
</ul>
</div>
</div>
</div>
</div>
....

Very Basic.. Ha!

And now, I want to set the Nav class as Active for the pages I visit. As an example, if I go to Demo 1 page, then the Demo 1 Nav should get the active class turned on, For Demo 2, Demo 2 page should be active..

i.e. I want to set the class as ‘active’ to my navbar depending on the page I am on, dynamically.

After checking many useful postings through Google, I have found the following one as workable in my case:

$(document).ready(function () {
            var pageName = window.location.pathname;
            var newPageName = pageName;

            if (pageName.indexOf('/') == 0) {
                newPageName = pageName.substring(1, pageName.length);

                $.each($('#navbar').find('li'), function () {
                    var hrefVal = $(this).find('a').attr('href');

                    if (hrefVal.indexOf(newPageName) >= 0) {
                        $(this).addClass('active').siblings().removeClass('active');
                    }

                });
            }
        });

I have added this code in my Site.Master page and it worked like a Charm!! Kudos to Harry Potter 🙂

Advertisements

Escape simple SQL queries in C# for Sql Server


Hellow,

Guess you are also stuck while writing a Query with C#.NET to insert a SQL Query to one of your tables, like I was few days ago! Or, you are trying to write a SQL Query in C#.NET which will insert a row in your table and you want to fix the issues with Single Quote character which is breaking your current code. If yes, then you are at the right place, since, I have also faced similar problems few days back and after little bit researching I found a useful way which can make your life also easier.

Here is the way you were doing it earlier:

  1. You wrote a Query string and passing variables to it using String.Format method
  2. Then this query string is being passed to a SQL Command object
  3. After that you are setting the connection and executing the query

string queryString = string.Format(@”INSERT INTO MYTABLE(COL1, COL2)
VALUES(‘{0}’, ‘{1}’)”,
valueForCol1, valueForCol2);

using(SqlConnection conn = new SqlConnection(connectionString)){

try
{

using(SqlCommand insertCommand = new SqlCommand())
{

insertCommand.CommandType = CommandType.Text;
insertCommand.CommandText = queryString;
insertCommand.Connection = conn;

if(conn.State != ConnectionState.Open) conn.Open();

int numberOfAffectedRows = insertCommand.ExecuteNonQuery();

}

}
catch(Exception)
{
throw;
}
finally
{
if(null != conn && conn.State != ConnectionState.Closed)
conn.Close();
}

}

So, above example is one such instance which you might have been doing in your code and whenever the values for COL1 or COL2 contains a single Quote (‘), the query is failing. This is because single quote character is one of the reserved characters for SQL.

In order to bypass this problem, you can either run a String Replace() to escape the single quote character by another single quote, i.e.

string myNewString = myOldString.Replace(“‘”, “””);

But, this is not a perfect way of handling SQL queries since there are issues with SQL Injection. So, the better way is to parametrize the query.

Example:

string queryString = @”INSERT INTO MYTABLE(COL1, COL2)
VALUES(@colParam1, @colParam2)”;

SqlCommand insertCommand = new SqlCommand();

insertCommand.CommandType = CommandType.Text;
insertCommand.CommandText = queryString;

insertCommand.Parameters.AddWithValue(“@colParam1”, valueForCol1);
insertCommand.Parameters.AddWithValue(“@colParam2”, valueForCol2);

using(SqlConnection conn = new SqlConnection(connectionString)){

try{

insertCommand.Connection = conn;

if(conn.State != ConnectionState.Open) conn.Open();

int numberOfAffectedRows = insertCommand.ExecuteNonQuery();

}
catch(Exception)
{
throw;
}
finally
{
if(null != conn && conn.State != ConnectionState.Closed)
conn.Close();
}

}

Note: I know you can find a way to dispose the SqlCommand object safely before moving out of the scope.

So, you have your fix now. You can use this method where we declare parameters in a SQL Command and then add values to those parameters before execution.

Hope this post will help you!!