Get List of all possible NullReferenceException in visual studio

Today, we are working on to have list of code where there would be chances of NullReferenceException.

I have come across a tools which highlights the possible null reference code while actually coding it. But couldn’t find an easy way to list out such code for already existing files.

After googling for couple of hours, I find a way to get this list.

  • Download the ReSharper https://www.jetbrains.com/resharper/download/
    It is an awesome plugin for Visual Studio. If you don’t have a licence, it is free for 30 days trial.
  • After installing, select ReSHARPER –> Inspect –> Code Issues in Solution from the Visual Studio Tool bar.
  • Once the inspection is finished. You can see Code issues in Inspection Results pane.
  • This will show many type of issues. Search for “possible system.nullreferenceException” and you will get the list of all possible System.NullReferenceException as shown in figure below
    Possible NullReferenceException

 

You can also export the search result as html or xml or text.

Happy Coding 🙂

Advertisements

5 years of Professional life

5 years5 years ago, a day came when you entered to a professional life from very energetic college/student life. From that day, no one was your teacher. Your failures have taught you and makes you mature day by day.

There are no friends in your team. They are your colleagues in other clear words they are your competitors – It’s a bitter truth accept it as early as you can. You might have a friend from different team and probably having same designation.

Some of you got promoted to senior level. But if you not, and you think you have done enough efforts for that and someone else promoted, don’t worry, your company is not smart enough to recognize your efforts. You must continue with your efforts because it is like Blessing in disguise (Something good that isn’t recognized at first).

Let’s start from beginning. Before joining a company, clear your mindset that in which role or in which domain you want to build your carrier. Break up your future plan into small duration plans (like in next 3/6 month, I must learn this or I must achieve this). You must have clear vision that at what position you want to see yourself or what you want to achieve in next 5 or 10 years. And your every plan should be your step towards it.

Once you reached to your 5 years of experience take a breath and look back. Look back for the mistakes which will not be allowed in next phase. Look back for the others. Have you guide/help your juniors/colleagues or you help yourself only? Have you shared your success with others? Have you shared your problems/errors/solutions with others via blog or forum or on shared platforms? Have you ever accepted your failure and not blamed others? If yes, man, you are a true professional with a golden heart of human.and if no, try these, you feel a unique kind of happiness.

Share your experience with your colleagues and juniors so that they don’t need to face the same difficulties which you faced. There are many new challenges.Team Work

WE / TEAM should be first before I. “It’s not my success, It’s TEAM’s success.” It is a TEAM which enables you to face any situation. It is a TEAM which encourage you to stand in front of any obstacles. Luckily, in every job, I got the leaders who always believe in Team work. When I was a trainee, I have read this on the desk of one of my mentors, Kiran.

      Together

      Each

      Achieves

      More

So, after 5 years, what is next? I have set a milestone for every year, Have you? Set yearly milestones for your professional journey. And after achieving each milestone, analyze your journey and keep walking. Don’t forget your personal/family life. It is as important as your professional life. Enjoy the journey. Enjoy your failures because you learn something new from your each failure. Best of luck for your future journey.


Multilingual URL Sitecore

Sitecore supports different language versions. It will be very easy to have a hindi, chinese, french or dutch version of an item in Sitecore. But how exciting to have a url to be multilingual.!!

We can have it with a very simple configuration modification…

In a linkManager section of a web.config file change the value useDisplayName to true in  sitecore providers setting. Keep the other settings as it is. Your code may look like following:

<linkManager defaultProvider=”sitecore”>
<providers>
<clear />
<add name=”sitecore” type=”Sitecore.Links.LinkProvider, Sitecore.Kernel” addAspxExtension=”true” alwaysIncludeServerUrl=”false” encodeNames=”true” languageEmbedding=”always” languageLocation=”filePath” shortenUrls=”true” useDisplayName=”true” />
</providers>
</linkManager>

This will show the displayname of an item in its url. Each item has display name property in its Standard fields. You must have item’s name/title in its DisplayName field for every language version to display url as multi-lingual.

—————————————————————————————————————————

To avoid manual update of DispalyName you can write handler on item:save event in web.config file:

<event name="item:saved">
   .
   .
   .
   .
   <handler type="My.Logic.UpdateDisplayName, My.Logic" method="UpdateItemDisplayName"></handler>
   </event>

Now, we need to define a class UpdateDisplayName having UpdateItemDisplayName method. Your class and this methods will look like following:


public class UpdateDisplayName
{
/// <summary>
/// Change the display name of an item as per its Page Heading
/// </summary>
/// <param name="sender"></param>
/// <param name="args"></param>
public void UpdateItemDisplayName(object sender, EventArgs args)
{
Assert.ArgumentNotNull(sender, "sender");
Assert.ArgumentNotNull(args, "args");
Item item = Event.ExtractParameter(args, 0) as Item;
if (item != null)
{
Database database = Factory.GetDatabase(new ItemUri(item).DatabaseName);
this.ChangeDisplayName(database, item, item.Language);

}
}

protected void ChangeDisplayName(Database database, Item item, Sitecore.Globalization.Language lang)
{
Item langitem = database.GetItem(item.ID, lang);
if (langitem != null)
{
if (langitem.Fields[“Title”] != null)
{
String pageHeading = langitem.Fields[“Title”].Value;
if (!String.IsNullOrEmpty(pageHeading))
{
using (new Sitecore.SecurityModel.SecurityDisabler())
{
try
{
langitem.Editing.BeginEdit();
string nm = pageHeading.Trim().Replace(” “, “-“);
langitem.Appearance.DisplayName = nm.Replace(“&”, “-and-“).Replace(” “, “-“).Replace(“–“, “-“).Replace(“–“, “-“).Replace(“?”, “”).Replace(“,”, “”).Replace(“/”, “”).Replace(“\\”, “”).Replace(“‘”, “”).Replace(“(“, “-“).Replace(“)”, “-“).Replace(“!”, “”).Replace(“;”, “”).Replace(“+”, “”).Replace(“~”, “-“).Replace(“@”, “-“).Replace(“$”, “-“).Replace(“:”, “-“).Replace(“%”, “-“).Replace(“\””, “”).Replace(“‘”, “”).Replace(““”, “”).Replace(“””, “”);
}
catch (Exception ex)
{
Log.Error(ex.Message, ex);
}
finally
{
langitem.Editing.EndEdit();
}
}
}
}
}
}
}

So whenever you will save the item, the text of its Title field (which needs to be created manually) will be copied it to the DisplayName field…

But what about already created items? Do we need to write manually?

The answer is “No”. Following is a code, which you need to execute one time to have a text in DisplayName field of an item. Here, we have a list of templates id on which we will update the display name of its items. You can create a button and write following code on its button click.


protected void btn_submit_onClick(object sender, EventArgs e)
{
String includedtemplates = "{templateid1},{templateid2},{templateid3}" ;

Item Home = Helper.GetHomeItem();
foreach(Item itm in Home.Axes.GetDescendants())
{
if (includedtemplates.Contains(itm.TemplateID.ToString()))
{
foreach (Sitecore.Globalization.Language lng in itm.Languages)
{
ChangeDisplayName(itm, lng);
//one label lblLog, which lists the items whose DisplayName is changed.
lblLog.Text += itm.Name + “:” + lng.Name + “:” + itm.DisplayName + “:Done <br/>”;
}
ChangeDisplayName(itm, LanguageManager.DefaultLanguage);
}
}
}

public void ChangeDisplayName(Item itm,Sitecore.Globalization.Language lng)
{
Item langitem = Sitecore.Context.Database.GetItem(itm.ID, lng);
String pageHeading = langitem.Fields[“Title”].Value;
if (!String.IsNullOrEmpty(pageHeading))
{
using (new Sitecore.SecurityModel.SecurityDisabler())
{
try
{
langitem.Editing.BeginEdit();
string nm = pageHeading.Trim();
if (nm.Contains(““”))
{
if (nm.Contains(“\””))
{
nm.Replace(“\””, “”);
}
}
langitem.Appearance.DisplayName = nm.Replace(” & “, “-and-“).Replace(“&”, “-and-“).Replace(” “, “-“).Replace(“–“, “-“).Replace(“–“, “-“).Replace(“?”, “”).Replace(“,”, “”).Replace(“/”, “”).Replace(“\\”, “”).Replace(“‘”, “”).Replace(“(“, “-“).Replace(“)”, “-“).Replace(“!”, “”).Replace(“;”, “”).Replace(“+”, “”).Replace(“~”, “-“).Replace(“@”, “-“).Replace(“$”, “-“).Replace(“:”, “-“).Replace(“%”, “-“).Replace(“‘”, “”).Replace(“\””, “”).Replace(““”, “”).Replace(“””, “”);
}
catch (Exception ex)
{
}
finally
{
langitem.Editing.EndEdit();
}
}
}
}

That’s it. Check your existing items. It will have a text of their Title field in its DisplayName field.

—————————————————————

Yes.. Finally, we have a chinese url for a china version, french url for a french version of an item of a Sitecore website.

Happy Coding 🙂


Validate text expression without RegularExpressionValidator server side

Hi,

To validate the text expression without using regular expression validator on your code behind (i.e. on server side- .cs), use following code:

bool validText= System.Text.RegularExpressions.Regex.IsMatch(“Your Text”, “Your Expression”)

for example, I need to validate value of Email Address text box of the submission form:

bool validEmailId=System.Text.RegularExpressions.Regex.IsMatch(txt_emailid.Text,

\\w+([-+.’]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*);

That’s it..

Enjoy Coding 🙂


Get last/latest value of Auto Increment column SQL Server

Hi,

Auto increment column is easy to use but it is very difficult to get the last value when some of the rows are deleted. For example, you have 125 rows in your table, having APPID as autoincrement field. Now, you deleted 25 records of it. Now, you need to insert a new row (obviously the APPID of this new row will be 126), but with insertion you need the new APPID number too. Following is the solution (following command will return current auto increment’s field value):

SELECT IDENT_CURRENT(‘your-table-name‘); // here this will return 125 (though you have deleted those 25 rows).

adding 1 to the result will return the next row’s AutoIncrement column’s value.

you can also use SELECT @@IDENTITY or SELECT SCOPE_IDENTITY(). But if you want to get latest value of auto increment column’s value from perticular table SELECT IDENT_CURRENT(‘tablename’) is good option.


Track Search functionality / Site Search in Google Analytic

Hi,

Google Analytic provides you the functionality to track the search in your site. It is not compulsory to use Google’s search engine.

Here, it is assumed that you have entered the GA code script in your page on which you have the search box.

Follow the below steps to enable Google Analytic to track the search:

  1. Log in to the Google Analytic Application & Select the appropriate site from appropriate account.
  2. Click on the Admin option available in right-upper corner
  3. Click on the profile available
  4. Click on the Profile Setting tab.
  5. In Site Search Setting,

5.1  Site search Tracking: select Do track Site Search

5.2  Query parameter: this is very important part. You need to pass the query parameters, which you have used for search url. For example, if your site is http://www.abc.com and after search if you append the query string parameter searchkey=xyz then your url will be http://www.abc.com?searchkey=xyz. So, you need to enter searchkey here.

Track Search GA

you can add upto 5 query string parameters separated by comma.

Strip query parameters out of URL : Select whether or not you want Google Analytics to strip the query parameter from your URL. Keep it unchecked.
Note that this strips only the parameters you provided, and not any other parameters in the same URL. This has the same functionality as excluding URL Query Parameters in your Main Profile: if you strip the query parameters from your Site Search Profile, you don’t have to exclude them again from your Main Profile.

6.  Select whether or not you use categories, such as drop-down menus to refine a site search. Keep it unchecked.
If you select No, you are finished. Click Save Changes.
If you select Yes:

  • In the Category Parameter field, enter the letters that designate an internal query category such as ‘cat, qc,’.
  • Select whether or not you want Google Analytics to strip the category parameters from your URL.
    Note that this strips only the parameters you provided, and not any other parameters in the same URL. This has the same functionality as excluding URL Query Parameters in your Main Profile: if you strip the category parameters from your Site Search Profile, you don’t have to exclude them again from your Main Profile.

7. Click on apply button.

You are done. But keep patience as GA may track search terms after 6 hours. (This is not the case always. You may find the search term from the next moment).

Enjoy 🙂 For more help regarding this issue, visit
http://support.google.com/analytics/bin/answer.py?hl=en&answer=1012264&topic=1031951&ctx=topic


Disable future or past dates in ajax Calendar Extender Asp.net

For this no extra javascript function is needed.

You just need to use the StartDate or EndDate property to enable only future dates or past dates respectively.

in aspx page you can set this property using inline tag. You can also assing this in back-end .cs or .vb code

StartDate=”<%# System.DateTime.Now %>”  in .aspx or CalendarExtender1.StartDate=System.DateTime.Now in back-end .cs or .vb file

That’s it.

If you are not able to access StartDate or EndDate properties. Please check your AjaxControlToolkit version. You can download the kit from here.

Happy Coding 🙂