How to get the users IP Address in C#.NET?

When you search this on your favourite search engine, (Google) you will get flooded by load of different way to get the end result. This is great in a sense as you know there are thousands of people with different answers, but then that is where the problem is at. There are so many single responses to how you can get the users IP Address in C#.NET, but not one that shows you everything. Therefore I will present to you below different methods to get the users IP and how I have implemented it in a project.

All the methods I found to be best are using the Request Server Variables. These are predetermined environment variables and request header information. This is why you can get IP address as it is part of the header information.

The standard server variable to use is ‘REMOTE_ADDR’, which is done as the following:


However if the user is behind a proxy server, then the above will return that IP Address and not the actual users. The server variable to get the users IP address from behind the proxy server is ‘HTTP_X_FORWARDED_FOR’ done as below:


Then you get that issue of not knowing if the user is behind a proxy or not, as the first example will return one or the other and the second example will only return a value if there is a proxy server. Therefore we need to find out if there is a proxy server or not. You can do this with the server variable ‘HTTP_VIA’, if this has a value then they must be using a proxy server and so you can get the correct IP as below:

If (HttpContext.Current.Request.ServerVariables[“HTTP_VIA”] != null) {
return HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];

return HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];

Or another method is to do it in reverse and check if the proxy method is not null first instead like:

string userIp = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];

if (string.IsNullOrEmpty(userIp)){
return HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];

return userIp;

This is the best method I found to get the users IP Address in ASP.NET C#, but if you think there is a better way then please comment below with your solution.

Kentico the mule of development

I have talked before about how Content Management Systems(CMS) are getting so good, that it means they are doing more of the work so you don’t have too. Instead of doing the donkey work, you can be improving the whole application and doing the most advance features. However over my time of working with such a CMS called Kentico I have found some pro’s and con’s of this mode of working, so I wanted to share my thoughts of if it is a favourable idea to be working on these CMS’.

Kentico’s power

First off an overview of what Kentico is, in case you have not heard of it. Kentico is a C#.NET Swiss army knife of a CMS as it can do Content Management, E-commerce, Online Marketing and basically most of the work for a developer.

Some of the features are:

Kentico uses the name ‘Page Types’ for its content templates. In these you describe the format of how this content should be held, like a database table. You tell it what the field is called in the database, the size, the data format and things like the caption the Content Editor sees. When the Content Editor then adds new content and chooses that Page Type, they are presented with a form with these fields to enter the content. What it then means for the developer, is they have a standard format of how to pull different content from the CMS and not just get a blob of data. (Find out more

As well as just getting well formatted content, you can use ‘Web Parts’. Web Parts are like functional modules that get used on a template. These can be things like a navigation bar that is on each page, but you can also have different types on each template. Also these can pull content from the database using the Page Type like a news feed or list of blog posts. (Find out more

However the Web Parts are added by the developer and are only a single instance of the Web Parts. What we really want is the Content Editor to be able to choose what pages have what modules and for this there are ‘Widgets’. These are instances of the Web Parts, which means you create a Web Part and then the Widget references it. When the Content Editor uses the Widget it takes a copy of the Web Part that it stores on the Page. The control it gives is for the Content Editor to decide what module shows where, when and how. These can get very complex to give more control to the Content Editor or the Developer can keep some control by limiting the functionality of the module. (Find out more

The other great content editor control is to build forms, yes full forms. With the CMS you can use a bit of a WYSIWYG to construct a form with various types of fields and then get them submitted to the database. These can also have customisation to send emails to the user or the administrator, create A/B split testing of forms and the editor can even customise the layout of the form. This will spare some hours building custom forms each time with the same validation, same submitting pattern and same design. (Find out more

You can read more about all the features in depth and download a demo from the Kentico website. []

Tell me why?

Other than just showing you the brochure, I wanted to explain what makes using a full customisable CMS like Kentico brings.

In my opinion DevOps is all about empowering the next person to do more with less work, for example an Operations Engineer could make it easier for a Developer to spin up development environment. This kind of this means the Operations Engineer can keep doing other work and the Developer can get on with their work faster. This is the same thing with Kentico and the Content Editors. The more generic and bespoke Web Parts you make, the more the Content Editor can do without the assistance of the Developer, which then leaves the Developer to get on with other work like improving the systems.

When you have a bespoke website that you need to do all the changes within the code, then the Developer needs to do all the leg work for even the smallest change. If the Content Editor wants a box moved to another location of the page, then that’s a boring task for the Developer. However with a CMS like Kentico, the Content Editor will be able to move this by themselves.

I would rather this kind of work pattern as for both Front End and Back End development, as I want to be working on the next great and latest thing, while also looking to improve my code and the testing. This work pattern removes them small tasks that interrupt your work, plus also if you work in Scrum like myself then it takes up your sprint points working in the more Developer heavy pattern.

As mentioned above its not just moving Widgets and custom Web Parts that make this CMS great. It is also the fact that the Content Editors can create their own forms. I remember having to built every simple form from scratch each time, but this now puts the work in their hand, but also in a simple way. I also say simple forms, but it is as simple as you the Developer wants to make it. As you can customise or custom build the Form Controls that build up the form and the Form Web Part that is the base of loading plus saving the form, then you can make them as complex as you want. If you want the form to be in different style, then build different Form Widgets. If you want multiple fields that result in a single field of content, like an Address, then build a custom Form Control. The ideas are only limited by you the Developer or the Content Editors ideas.

The downsides I have seen are where the Content Editors have a lot of great simple ideas. I have been given tasks of adding a new type of button or adding a new content area to a Widget. Although we are empowering them, we also still need to provide the tools to them, which aren’t always the most inventive ones. There is also a balance between empowering them and giving them the code. You could expose all the customisable features of the Web Part, like a button so the colour, size, wording, features but then it’s a huge amount of work for one button. This would then put them off using it, however the other way of closing it down can then put more tasks on you.

Another challenge is what you can customise and what you should. Kentico’s recommendation for when you are customising anything, is if it is default to Kentico then clone it and customise the clone. This is so if or when you need to upgrade the CMS, you haven’t broken anything that the upgrade will use, plus it could get over written when the upgrade is then place. Even though Kentico is full customisable, the method in which it performs some task might not be how you like and at best practice you need to leave them how they are.

Final thoughts?

Although there are downsides to using a CMS like Kentico, I think any method of using a CMS will have its downsides. I feel with this set up I am more looking at improving the code, myself and the product, rather than doing the same task each time.

What CMS do you use and do you think it helps you become a better developer, comment below?

Guide to the Style Guide

Let first start with what this post is not and that is a style guide for clothing, make up or hair. This is about Coding Style Guides, what they are, if you should have one and if so then what one. I will mainly be following it through with JavaScript, but the knowledge can be transferred to other languages as it is the principle that I am looking at.

What is a style guide?

A Style Guide is a set of rules for your code to follow. These rules start from as simple as putting a semicolon at the end of the lines, and only using single quotes around strings. However the rules can be expanded to describe how you should format your code, for example how to format a function, the file naming convention and how to set up error checking. In short it is a guide of rules and patterns for developers to follow to create a consistent and fluent code.

Style Guides and their practice have been about for many years, but I feel with more languages and standards being put in place they have become more prominent. One of the earliest writing is a book called The Elements of Programming Style, which talks about the coding rules from its time for Fortran and PL/I languages. Though the languages are more out of date, the principles are not and can still be taken into account for todays standards. Most tutorials and beginners guide to languages, will also have some kind of style guide in them, so you can learn from their patterns what to conform to.

These guides don’t have to just be words on a page as well. The guides are able to be built into your Continuous Integration Builds. This would mean when your application builds it can produce errors or warning about your code and how to fix them before you merge into the shared code base.  Better yet,  you can get extensions built into most all the common coding editors that will evaluate your code as you type or on save of the code. Therefore you don’t need to wait until the end point when you are checking in to find out your problems. This can save time and also drill in the practices to your mind, so soon you will be throwing out the styles as you go with no help.

Should you have one?

This is a simple question with a simple answer, yes. Why would you not have one of these in practice at your company or even in your personal workflow. To conform to a style guide is an easy task for anyone to get started as there are so many tools to test your code. However if you have a large code base and then you decide to get a guide in place then it could take sometime, but worth it. Think if you have all types of developers putting their own twist in the code base and then they need to read each other code. It would create a bit of a muddle as they would need to understand the previous developer patterns to understand the code. Worst thing would be, does that developer conform to the previous developer standard or put their own in. This would then create a hybrid that creates more hassle for the next developer.

As you can see the guides can benefit you a lot, but not just for other developers reading your code. When you are creating code you want to make sure it is readable by yourself as well. If you think about, that you might not come back to a peace of code for a long time, with a style guide in place and in practice, you would be able to read the code more easily. It also then gives you a standard of coding, so your not just spitting out some Frankenstein code that just about works, but instead you always have a consistent level of code produced. With consistence code and naming conventions it then also make life easier when your 30,000 lines down the bottom of the page and you need to remember how you call that method. The style guide that pushes you to have a pattern to your naming, will then give you the ability to know how the method will be named. Therefore you won’t need to hunt it down as you will either just know the name or at minimal know how to search for it.

The people it should also be benefitting is the other developers working on the same code and also the company that could be recruiting another developer. If the standard is in place then it doesn’t matter who walks up to your code, they will be able to read it easy and also be able to update the code easier. The other perks of following the guide are the same that will benefit the individual user like simpler to find files names, update code and keep consistency.

Which one?

Well 99% of the time I would say not to build your own, but there is that small 1% I would say yes. This 1% time I would say yes, is for if you are a big enough company to require your own style guide. As the guide is just for coding then there is not customer vision of this, therefore it is not vital that the style guide represents your company image. Saying that though, some companies may prefer to have there own rules to follow as it might fall inline with other style guide or other company procedures. Either way it should only really be done if they must have to.

The reason to still use a popular  open source one is because it is just that, open source. This would mean that when the ECMAScript gets updated or any other language versioned, the community will update the style guide to comply with the latest version. This can take some time if it is your own, to update to a new version and have meetings internally to decide what the update is. However if the open source owner or community do it, then you don’t have to.

This then also back up the point that if another developer is recruited, they may know the open source style guide and be able to pick up the code base easier. If the style guide managed by your company or yourself, then you have no chance of the developer understanding the guide first time.

If you do decide to be in the 99% section, then which guide do you go for? This is where the power of the internet comes in. As I mentioned at the beginning, I am focusing this on JavaScript, but it can be transferred to other languages. Therefore for the JavaScript world I would suggest Airbnb Style Guide, because from what I have read and researched it is the most used guide. Of course this doesn’t make it the right guide, but other than the majority of the developer community can’t be wrong, the guide also looks good. From me using it I can tell it is up to date, well maintained and well supported by other extensions like linters. This for me says it is a good choice to go for and so I would use the same method for looking at other style guides for other languages.

To find other guide I would suggest using a search engine to find a guide for your chosen language, or speaking of search engine, Google has a style guide for a lot of languages and it will of course be up to date. You can find it here on Git Hub.

Some Further Reading…

What if the worst happens?

I see a lot of companies rush, rush, rush and push, push, push to get things in fast. They want to deliver new features every second if they could. However this has big risk and future problems they keep coming. I always say Prepare for the Worst and Hope for the Best!

This I find is the best saying to use, whenever you think ‘should I just do this little thing or not’. If you ever look at a problem and think something could go wrong here then put in a worst case solver.

Some of the trip ups I have see have been to do with logging, which can either be to little or even to much. You can always do with logging to save you in the live environment. When issues start happening you need to diagnose what the issue is straight away, but you can’t get the details without some logging as to what is going on.

However you should only log the things that could fail, but of course shouldn’t be. An example is, I have created a method that actions dynamic changes on multiple elements, but if one element is removed I don’t need to know about it. I just need the method to continue running, so I could put a try catch round it and then let it go with no logging. This prepares for the worst and then lets the best happen. However If I have built a method that the application needs all elements to be present, then I want to log the error for reporting so it can be fixed as soon as it is seen.

There has been sometimes that someone has added masses of logging at every section, then the server starts throwing warnings up or just falls over. So your best is that the program works as you need, but your worst preparation is you have logging to review any errors. You then also have the best prepared with as much useful logging for review as you need and also the worst is you don’t put in unnecessary logging. There is always a balance between too much and too little that needs to be looked at.

Something logging and other attributes can do is take up memory. This can then build up and take down servers, as I have recently also found. I deployed a nice new OSB service and added one new log that would be fired each time someone submitted the form. This to me didn’t seem much as it was a small file, but then once it was live there was a report about the logging from the support team. Although it was a lot of logging that could build up over time, it was also not helped that the server was full 95%. This means it could fill up at any point.

If you are going to have a well organised and dynamic server, then there should be scripts run daily or monthly that clear up the files. This could either delete the logs older than X number of days or even just package them and send to another locations. It is super risky to be running a server at 95% full and expect nothing to tip it over the edge. Regular maintenance and checks should be carried out so that this is caught at the first site.

One that all developers should be using is a good old Try Catch. If you are not sure what one is, without being too patronizing, it looks like this in JavaScript for example:

try {
//Code attempted
//Exception caught

You should use these anywhere there could a potential break even if you want something to react to it or not. For example you would put one round a submission from a form. This would then catch if it failed and for what reason, then from this you could display a notice informing the user what to do next. You could also do it for example if you are dynamically loading content in a loop, you could put one round the code within the loop. If one of the calls to get content fails it could trip over the Try Catch, but then continue getting the rest of the content. The user then need not know that something went wrong and then you can either send an error message to support or just let it continue.

These can be really helpful to stop your application from breaking in unwanted ways like with server errors, but again you don’t want to over use them and you want to be sure they errors are being picked up.

Another method to get around the errors cropping up is putting default values. I stepped into this one when someone create a switch statement, but with no default case (C#) and the variable that was being set inside was set to null at the beginning. This was working fine for some time as the cases that were there met the demand, but further down the line the content editable variable that was being checked in the switch had changed. This meant that the variable being returned was null and breaking the application.

To get around this you should first try to make the check dynamic or dynamically changeable, so when a new value is added then the new result can also be generated. The other thing that should always be done with Switch statements or any other kind of statement that provides the option, is put a Default. Example:

Switch (Number){
Case 1:
//Do thing
Case 2:
//Do this
//Or else do this then

It just means that there is a result from the statement no matter what. At best, unlike this scenario, if you are setting a variable in the statement you should always return a valid result and then handle the result. For this instance an empty string could have been returned and all would have worked fine.

These are some of the ways developers can prepare for the worst and stop stupid mistakes. If you have seen any silly things happen that could be avoided then comment below with what, why and most importantly how to fix it.


MS Word special characters Regex

That pesky Microsoft! They have to be different and mess us developers around don’t they. Have you ever noticed that Microsoft Word’s symbols look a bit different or act a little odd? Well it’s because they are not the standard char characters. This can be a pain for Regex and other things. So how do you get them…

The reason they are so difficult is they use Windows-1252 character encoding set which are not represented in ASCII or ISO-8859-1. This is what just about everyone doesn’t do of course. These characters include:

  • … ellipsis
  • ‘smart’ “quotes”
  • en – dash and em — dash
  • dagger † and double dagger ‡

There are few more of course, but these are the most common few that come up. You can find more of Microsoft Word Windows-1252 character encoding here.


Symbol Encoding
single quotes and apostrophe \u2018\u2019\u201A
double quotes \u201C\u201D\u201E
ellipsis \u2026
dashes \u2013\u2014
circumflex \u02C6
open angle bracket \u2039
close angle bracket \u203A
spaces \u02DC\u00A0


Here is a pre-built method for JavaScript and C# to combat these.


JavaScript Clean String

var wordClean = function(text) {
var cleanStr = text;

// smart single quotes and apostrophe
cleanStr = cleanStr.replace(/[\u2018\u2019\u201A]/g, “\'”);

// smart double quotes
cleanStr = cleanStr.replace(/[\u201C\u201D\u201E]/g, “\””);

// ellipsis
cleanStr = cleanStr.replace(/\u2026/g, “…”);

// dashes
cleanStr = cleanStr.replace(/[\u2013\u2014]/g, “-“);

// circumflex
cleanStr = cleanStr.replace(/\u02C6/g, “^”);

// open angle bracket
cleanStr = cleanStr.replace(/\u2039/g, “<“);

// close angle bracket
cleanStr = cleanStr.replace(/\u203A/g, “>”);

// spaces
cleanStr = cleanStr.replace(/[\u02DC\u00A0]/g, ” “);

return cleanStr ;

C# Clean String

public string wordClean (string text){
var cleanStr  = text;

// smart single quotes and apostrophe
cleanStr  = Regex.Replace(s, “[\u2018\u2019\u201A]”, “‘”);

// smart double quotes
cleanStr  = Regex.Replace(s, “[\u201C\u201D\u201E]”, “\””);

// ellipsis
cleanStr  = Regex.Replace(s, “\u2026”, “…”);

// dashes
cleanStr  = Regex.Replace(s, “[\u2013\u2014]”, “-“);

// circumflex
cleanStr  = Regex.Replace(s, “\u02C6”, “^”);

// open angle bracket
cleanStr  = Regex.Replace(s, “\u2039”, “<“);

// close angle bracket
cleanStr  = Regex.Replace(s, “\u203A”, “>”);

// spaces
cleanStr  = Regex.Replace(s, “[\u02DC\u00A0]”, ” “);

return cleanStr ;

If you are doing some validation using Regex, here is also how you can check these characters.

JavaScript Regex

function containsWordChar(text) {
var contains;

switch (text) {

case (text.match(/^[\u2018\u2019\u201A]$/)):
contains += “single quotes and apostrophe, “;

case (text.match(/^[\u201C\u201D\u201E]$/)):
contains += “double quotes, “;

case (text.match(/^[\u2026]$/)):
contains += “ellipsis, “;

case (text.match(/^[\u2013\u2014]$/)):
contains += “dashes, “;

case (text.match(/^[\u02C6]$/)):
contains += “circumflex, “;

case (text.match(/^[\u2039]$/)):
contains += “open angle bracket, “;

case (text.match(/^[\u203A]$/)):
contains += “close angle bracket, “;

case (text.match(/^[\u02DC\u00A0]$/)):
contains += “spaces, “;

contains += “double quotes”;


return contains;

C# Regex (MVC)

[RegularExpression("^[\u2018\u2019\u201A\u201C\u201D\u201E\u2026\u2013\u2014\u02C6\u2039\u203A\u02DC\u00A0]+$", ErrorMessage = "Your content contain some Microsoft Word Windows-1252 character encoding.")]

C# Regex

Public string containsWordChar(text) {
String contains;

switch (text) {

case (text.IsMatch(@”^[\u2018\u2019\u201A]$”)):
contains += “single quotes and apostrophe, “;

case (text.IsMatch(@”^[\u201C\u201D\u201E]$”)):
contains += “double quotes, “;

case (text.IsMatch(@”^[\u2026]$”)):
contains += “ellipsis, “;

case (text.IsMatch(@”^[\u2013\u2014]$”)):
contains += “dashes, “;

case (text.IsMatch(@”^[\u02C6]$”)):
contains += “circumflex, “;

case (text.IsMatch(@”^[\u2039]$”)):
contains += “open angle bracket, “;

case (text.IsMatch(@”^[\u203A]$”)):
contains += “close angle bracket, “;

case (text.IsMatch(@”^[\u02DC\u00A0]$”)):
contains += “spaces, “;

contains += “double quotes”;


return contains;