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:

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

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:

HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];

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.

CSS Click Event

So you have click the link to find out, how on earth is there a CSS Click Event that I have not heard of? Well that’s because there is no Click Event directly, but we can replicate that event with CSS. Below will show you with a simple example how to action CSS on a click.

As I have said there is not real Click Event in CSS, but you can use the other tools you have to replicate that event. In CSS you can determine the stat of elements on the screen and so with that you can check the stat of a Checkbox. This is how we are going create the Click Event.

You can use the pseudo attribute ‘:checked’ to determine is the Checkbox is checked or not. If you use the pseudo then all CSS under it will only action when it is checked.

 

input{
    background-color:red;
}
input:checked{
    background-color:green;
}

 

Now that we know we can click on an Checkbox to activate CSS, we will need to expand its reach. If you are to click on a menu item of a button, you don’t want it to be a Checkbox. We get round this with the label element. With this element you can surround your items that will change. You can link the input and the label together so when you click on the label you are also clicking on the input.

 

<label for="chk" >

<input type="checkbox" id="chk" />

<span>

<!-- content -->

</span>

</label>

 

From this you can change the style depending on the checkbox state, but with CSS you can only target the children elements. This means you can’t target the ‘span’ because its not a child on the input that is having its state changed. What we can do is target the next element. We can do this by using the ‘+’. If you put this next to the input element then add the span in CSS the it will target the span. It affects the next element to the one on the left, please see the example below:

 

#chk:checked + span {

/* Checked Style Here */

}

 

Now you can put it all together and create a click event like I have in the Codepen below:

http://codepen.io/purerandom/full/mEyqmR/

Visual Studio Code Cookie Snippet

If you didn’t know, Microsoft release an editor called Visual Studio Code and if you didn’t know, Visual Studio Code can handle Snippets and extensions. These Snippets can be created by Visual Studio and by the coding community. These can be simple modules to help coding or full languages. I have found a use to generate a snippet of code that I always use and so I have made this into a Visual Studio Code Snippet. Read on to find out what and how to use it.

What is it?

The Snippet is called CookieJs and by the title you can guess it is about cookies in JavaScript. This snippet produces 3 methods for running cookies. One is to set a cookie, one is to get a cookie and finally a method to check if an cookie exists. These three methods can be produced separately, plus also it can be produced as a JavaScript object.

How do you get it?

If you download Visual Studio Code first of course and you can do the following

  1. Install Visual Studio Code 0.10.1 or higher
  2. Launch Code
  3. From the command palette Ctrl-Shift-P (Windows, Linux) or Cmd-Shift-P (OSX)
  4. Select Install Extension
  5. Type CookieJs
  6. Choose the extension
  7. Reload Visual Studio Code

 

How do you use it?

So like most snippets, it is easy to use. You simply have to type in one of the 4 keywords and they will produce the respective snippets of code.

 

'cookieobj' for full CookieJs object

'chkcookie' for Check Cookie Function

'getcookie' for Get Cookie Function

'setcookie' for Set Cookie Function

 

CookieJs

 

A little snag that kept getting me is to remember to have the language setting set to JavaScript. To change this you need to click the Language Indicator, which is down in the bottom right hand of the status bar. This will bring up the Command Palette for Select Language Mode. You can read more about the languages here on Visual Studio Code site on Languages.

 

Screen Shot 2016-04-27 at 20.18.15

You can get this snippet and more from this link here to my CookieJs. 

 

JQuery Validate for 3 field date

A difficult and challenging task I had been given is to use the JQuery validate.js to validate the date fields, but this was then split out into 3 fields. One for day, month and of course year, which sounds easy, but it was not. The issue comes that validate.js is built to validate one field on its own and we wanted to validate not just each field, but also as a whole date.

I researched the web and most developers suggested amending the JavaScript library file. However the version we had was minified and of course we had other teams using that copy, so using this method would affect others code. I thought about putting the validation for the whole date in with each of the fields, but this then produced the same validation each message for the whole date 3 times because it was doing it for each of the fields. There was a suggestion from developer to use a group method, but I couldn’t seem to get that working.

So I persisted to make my own method. This may not be the best, but I found it worked well and passed testing so it can’t be that bad. You can read more about the library of JQuery Validate here and learn the basics, which will make this all seem a bit easier.

First we need to validate each field on their own for example make sure the month is between 1 and 12. Instead of making a validation made for each field I made a universal method that all of them could use.

In the example below you can see in the ‘params’ parameter I passed in a array that has the minimal number and the maximum number. You would pass for example of month [1,12]. This is then validated on exit to check the ‘value’ of the field, stored in ‘dateValue’, is between or equal to the range.

$.validator.addMethod("vailddatefield",

function (value, element, params) {

var dateValue = parseInt(value, 10);
var Min = parseInt(params[0], 10);
var Max = parseInt(params[1], 10);
return this.optional(element) || (dateValue >= Min && dateValue <= Max );

},"Please enter a valid age"

);

You can then attach this to the field like so:

//Month validation
$(".month").rules("add", {

vailddatefield: [1,12],
messages: {
vailddatefield:  'Please enter a month value between 1 and 12'
}

});

The issue then comes when you want to validate these all together. If you was to enter the validation for the whole date in the method above then when an error happened it would produce the message once for each field with the same text. This then means we need a single field to evaluate if the full date is valid and then validate against that.

If you add the below snippet into the previous method, you can then pass the class or IDs for each of the date fields. These can then be concatenated together to make a full date, then put into a hidden field. This now holds our full date string in good format ready for validating.

//validate full date
var day = $(params[2]);
var month = $(params[3]);
var year = $(params[4]);
var fullDate= $(params[5]);

$(fullDate).val($(day).val() + '/' + month.val() + '/' + year.val());

This however still doesn’t solve how we are going to validate it. To fire the validation by the library as normal, you need to give focus to the field then leave it, which is impossible because it is hidden. So we use some magic… If you put the below statement in, it forces the JavaScript to validate that field. This then runs its attached validation from the library. If you enter this into the previous method as well, so no matter which fields they start or finish in, it will validate the full date in the end. You will also only get only one message to appear if the field is invalid.

$(fullDate).valid()

Something I also did was stop it validating until all the fields are complete, as you don’t want to say their date is invalid before they even get chance to fill it out, so I changed the above to be the below. This then checks that each field has it minimal length of value before it validates the whole date.

if ((dayBirth.val().length >= 1) && (monthBirth.val().length >= 1) && (yearBirth.val().length > 3)) {

$(fullBirth).valid()          

 }

You can now see the whole code for the validation method. This will validate each field on its own, while also validating the whole date. You will need to add your own method for validating the full date, but if you read up on the library this should be easy.

/// Check Valid date
$.validator.addMethod("vailddatefield",

function (value, element, params) {

var dateValue = parseInt(value, 10);

//Get max and min dates
var Min = parseInt(params[0], 10);
var Max= parseInt(params[1], 10);

//validate full date
var day = $(params[2]);
var month = $(params[3]);
var year = $(params[4]);
var fullDate= $(params[5]);

//enter full date
$(fullDate).val($(day).val() + '/' + month.val() + '/' + year.val());

//Validate full date
if ((dayBirth.val().length >= 1) && (monthBirth.val().length >= 1) && (yearBirth.val().length > 3)) {

$(fullBirth).valid();

}

return this.optional(element) || (dateValue >= Min && dateValue <= Max);

},"Please enter a valid age"

);

Below here you can then see the example of calling the new methods for Month and for the full date. You can always also add more validation methods.

//Month required
$(".validate-month").rules("add", {

vailddatefield: [1,12,'.day','.month','.year','.fulldate'],
messages: {

vailddatefield:  'Please enter a month between 1 and 12'

}

});

//full date
$(".validate-date").rules("add", {

vailddate: '',
messages: {

vailddate:  'Please enter valid date'

}

});

Any thoughts and other methods people have seen can be shared in the comments section below.

ARIA Control JavaScript Library

This is a library to automatically inject the standard for screen readers mark-up ARIA. ARIA is Accessible Rich Internet Applications which is a way to make websites and applications more accessible to people with disabilities.

This libraries purpose is to automatically inject the necessary tags and commands to the users mark-up, so that it meets the standards as much as possible. There are also commands for the users to inject the methods on to specific parts if the library does not get them automatically. Also the automatic functionality can be turned off if only partly needed.

Download the library on GitHub 

View the examples on CodePen

Here are some helpful links about ARIA to help understand the tags and their values.

 

ARIA Control Library V1 Method Breakdown

Hidden (has auto)

This detects all the elements that are ‘display:none’ and/or ‘visibility:hidden’. It will then add the ARIA ‘aria-hidden’ and give it a role of ‘presentation’. This makes the element hidden from screen readers. There is also a method to make the element un hidden if the state changes.

Hidden Message (has auto)

This method uses the given class in the options to make the element display off the page. This means that the screen reader can see the message and read it out, but sighted users won’t be able to see the message. This is useful if you want to give extra information only to the users using a screen reader.

Notifications

This sets the attributes for ‘aria-atomic’, ‘role’ and ‘aria-live’. These are the attributes best served as a notification.

Alert (has auto)

This is for error messages and other alerts to the user. This will use the notification method above with the settings as ‘aria-atomic: true’, ‘role: alert’ and ‘aria-live: rude’. This can be automatically run with a set class.

Warning (has auto)

This is for warning messages and other none critical alerts to the user. This will use the notification method above with the settings as ‘aria-atomic: true’, ‘role: alert’ and ‘aria-live: assertive’. This can be automatically run with a set class.

Message (has auto)

This is for any message that is not critical like a success message. This will use the notification method above with the settings as ‘aria-atomic: true’, ‘role: alert’ and ‘aria-live: polite’. This can be automatically run with a set class.

Required (has auto)

Any element, usually inputs, that has the attribute ‘required’ on them will have the ARIA tag ‘aria-required’ added to the element. This can also be done manually by passing the class.

Popup (has auto)

With this method you need to set up the popup classes for the control and the popup. It is mainly aimed at the tooltip example, e.g. if you click in a field and then a tooltip shows. The method will give the control the aria tags to show it has a popup and the tooltip the tags to show what controls it. You can also pass the role type, but by default it is ‘tooltip’.

Show and Hide Popup

These are more helper methods to the above. When the popup shows or hides you can call these method to update the elements settings.

Checked Elements (has auto)

Both Checkboxes and Radio buttons will automatically have the check item injected with the ARIA ‘aria-checked’. This marks if the element is checked or not, for which the change event is also added to all of the elements so if it becomes checked or unchecked then it is updated.

Disabled (has auto)

Any disabled element will have the ‘aria-disabled’ tag added to it.

Selected Option (has auto)

This will make all the options in a select element ‘aria-selected: false’ then find the selected option to set it to true. It also adds the event change to detect when the selected has changed and updates them.

Max and Min (has auto)

This will mainly be for inputs with a max or min value. It finds if they have a value then puts them in their relative tags, either ‘aria-valuemin’ or ‘aria-valuemax’.

Navigation (only has auto)

A complex one, but easy to set up. With all the correct settings this can add the tags to show up to screen readers as a navigation. It will also tag the links as menu items and the sub menu as well as being a popup. It uses the hover event to detect when the sub menu is being shown.

Button (has auto)

This will detect the all button types and add its role as ‘button’

 

ARIA Control Library V1 Options Breakdown

autoDetect (default = true)

This determines if to automatically tag the elements or to only allow manual running.

alertClass (default = .acAlert)

Used for the auto detection for Alert Notifications.

warningClass (default = .acWarning)

Used for the auto detection for Warning Notifications.

msgClass (default = .acMsg)

Used for the auto detection for Message Notifications.

popupClass (default = .acTooltip)

The class of the popup or, as the example was, the tooltip.

popupCtrlClass (default = .acTooltipCtrl)

The element that triggers the popup or tooltip to show.

popupType (default = tooltip)

The role of the popup.

hiddenMsgClass (default = .acHiddenMsg)

The class of any hidden messages that don’t show to slighted users.

navClass (default = .acNav)

The navigation containers class.

navParentClass (default = .acSubNav)

The top level links class.

navSubNavClass (default = .acSubMenu)

The sub menu class.