Get Client Ip Kentico 9 - ip

I need to get the country of the customer who comes to the site.
I can use GeoIPHelper.GetCountryByIp("ip")to get Counry, but how can I get the ip address of the client that comes to the site?

Are you using Kentico EMS? If so then to get country of current contact:
var countryId = ContactManagementContext.CurrentContact.ContactCountryId;
var country = CoutryInfoProvider.GetCountryInfo(countryId);
Or
var currentLocation = GeoIPHelper.GetCurrentGeoLocation();
Which also contains country/state based on current request.

{%Ip%} in macro or var clientIp = CMS.Helpers.RequestContext.UserHostAddress
Or do you want to find out ip of existing customers?
That would be a sql query like
select Convert(xml,UserLastLogonInfo)
from COM_Customer Join CMS_User on CustomerUserID = UserID
it will give your xml like:
<info>
<agent></agent>
<ip></ip>
</info>

Looking at your code sample, I think you're in the code behind somewhere. This is possibly more of a general thing with ASP.NET. if that is the case, you can use HttpContext.Current.Request.UserHostAddress to get the IP of the current user.
There can be issues with this however if you're behind something like a load balancer. To combat that, you can try something like the following:
string userAddress = string.Empty;
if (HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"] != null)
{
userAddress = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"].ToString();
}
else if (HttpContext.Current.Request.UserHostAddress.Length != 0)
{
userAddress = HttpContext.Current.Request.UserHostAddress;
}
var country = GeoIPHelper.GetCountryByIp(userAddress);
CMS.Helpers.RequestContext also works (as Shof says) but again, make sure to cater for any load balancer issues. To be honest, I've always fallen back to just using the HttpContext method from pre-Kentico habit.

GeoLocation currentGeoLocation = GeoIPHelper.GetCurrentGeoLocation();
if (currentGeoLocation != null)
{
var countryAndState = ValidationHelper.GetString(currentGeoLocation.CountryName, "");
var ipCountryCode = ValidationHelper.GetString(currentGeoLocation.CountryCode, "");
var ipRegion = ValidationHelper.GetString(currentGeoLocation.RegionName, "");
var ipCity = ValidationHelper.GetString(currentGeoLocation.City, "");
}
or macro
{% AnalyticsContext.CurrentGeoLocation.Country.CountryName%}
{% AnalyticsContext.CurrentGeoLocation.State%}
{% AnalyticsContext.CurrentGeoLocation.City%}
{% AnalyticsContext.CurrentGeoLocation.Postalcode%}

Related

Show Ping Status in list in MVC5

I am Using Asp.net mvc5, I have table with fields like "id", and "server_IP" populated with n-numbers of server ip. And wants to display the status of each IP " success" or "timeout" depending upon ping.
I have used following;
Ping myPing = new Ping();
PingReply reply = myPing.Send("8.8.8.8", 1000);
if (reply != null)
{
ViewData["ip_stat"] = reply.Status;
}
I could not use this in my viewlist so that status of each servers can be shown as
Server Status
8.8.8.8 Success
192.168.10.10 timeout
192.168.100.1 sucess
REGARDS
ARUN SAHANI
Not sure if I have understood your question correctly, but going by the kind of output you are looking for and the way your are initializing the viewstate, I think you should concatenate the ip and the status while passing it into viewstate.
Something like this:
ViewData["ip_stat"] = reply.Address + " " + reply.Status;
Hope it helps.
Edited for the case where addresses are fetched from some table and needed to be passed to viewstate
// suppose this variable has the list of IP addresses from the table
var addresses = new List<string> {"8.8.8.8", "192.168.10.10", "192.168.10.8"}
var ipStatusDict = new Dictionary<string, string>();
//iterate over the list, fetch the status for each ip and add it within the dictionary
foreach(var ip in addresses)
{
var reply = new Ping().Send(ip, 1000);
if (reply != null)
{
ipStatusDict.Add(reply.Address, reply.Status);
}
}
ViewData["ip_stat"] = ipStatusDict;

Retrieve additional user properties from ActiveDirectoryMembershipProvider

The ActiveDirectoryMembershipProvider in ASP.NET returns users as instances of MembershipUser. This class only returns two of the properties defined for the given user in AD: email and username. I need to get access to additional properties, specifically "DisplayName", as I need to show full names in a dropdown in a web form.
The only way I can find to do this, is via a separate connection to AD, along the lines of what is described here: How can I convert from a SID to an account name in C#. This seems like a cumbersome and inefficient solution. I would like to do something like membershipProvider.GetUserProperty(username, propertyName), but that's not available.
Are there any nice solutions that people know of?
Based on feedback from my colleagues (thanks, Eirik!), #KennyZ's comment and lots of Googl'ing, I have found that this is the best/only way to do it. For reference, and other people seeing this question, here is some useful code for getting the AD settings out of web.config+connectionStrings.config, and using that data to query AD for a given user's Display Name:
var membershipSection = (MembershipSection)WebConfigurationManager.GetSection("system.web/membership");
var providerSettings = membershipSection.Providers["ActiveDirectoryMembershipProvider"];
var connectionStringName = providerSettings.Parameters["connectionStringName"];
var adUser = providerSettings.Parameters["connectionUsername"];
var adPassword = providerSettings.Parameters["connectionPassword"];
var adConnection = WebConfigurationManager.ConnectionStrings[connectionStringName].ConnectionString;
var adReference = new DirectoryEntry(adConnection, adUser, adPassword);
var search = new DirectorySearcher(adReference) {Filter = string.Format("(mail={0})", username)};
search.PropertiesToLoad.Add("displayName");
SearchResult result = search.FindOne();
if (result != null)
{
var resultCollection = result.Properties["displayName"];
if (resultCollection.Count > 0)
{
var displayName = resultCollection[0].ToString();
...
}
}
Note: This assumes that I am using userPrincipalName as the attributeMapUsername in web.config, as that maps to the user's email address.

Tridion 2009 SP1: Broker how to get Binary Url?

I am trying to retrieve the Binary Url of a multimedia component's file that is published as a dynamic Component Presentation.
I can see the Url in the Binaries table within the Broker database but I can't seem to get the binary url using either of the following bits of code:
using SQLBinaryMetaHome:
using (var sqlBinMetaHome = new Com.Tridion.Broker.Binaries.Meta.SQLBinaryMetaHome())
{
int componentItemId = int.Parse(queryStringId.Split('-')[1]);
var binaryMeta = sqlBinMetaHome.FindByPrimaryKey(new TCDURI(publicationId, 16, componentItemId));
if (binaryMeta != null)
{
VideoBinaryUrl = binaryMeta.GetURLPath();
}
else
{
Logger.Log.ErrorFormat("Failed ot load via SQL Binary Meta {0}", queryStringId);
}
}
Using Binary Meta factory:
using (var b = new BinaryMetaFactory())
{
var binaryMeta = b.GetMeta(queryStringId);
if (binaryMeta != null)
{
VideoBinaryUrl = binaryMeta.UrlPath;
}
else
{
Logger.Log.ErrorFormat("Failed to load binary meta {0}", queryStringId);
}
}
I can load the Component Meta data using the ComponentMetaFactory.
Any ideas on why I can't load the Binary Meta? Am I on the right track?
Rob
It looks like your first example is importing (auto-generated) methods from an internal DLL (Tridion.ContentDelivery.Interop.dll). Please don't use those and stick to the ones in the Tridion.ContentDelivery namespace (Tridion.ContentDelivery.dll).
You can find the official documentation for the Content Delivery .NET API in CHM format on SDL Tridion World (click the link, log in to the site and click the link again). From that documentation comes this example:
//create a new BinaryMetaFactory instance:
BinaryMetaFactory binaryMetaFactory = new BinaryMetaFactory();
//find the metadata for the specified binary
BinaryMeta binaryMeta = binaryMetaFactory.GetBinaryMeta("tcm:1-123");
//print the path to the output stream:
if(binaryMeta!=null) {
Response.Write("Path of the binary: " + binaryMeta.UrlPath);
}
//Dispose the BinaryMetaFactory
binaryMetaFactory.Dispose();
The factory class is Tridion.ContentDelivery.Meta.BinaryMetaFactory from Tridion.ContentDelivery.dll. I indeed also can't find a GetBinaryMeta method in that class, so it seems there is a mistake in the code sample. The most likely method that you should use is GetMeta.
Is there a reason you are not using a Binary Link to get a Link object to the specific Variant of the binary you want? Keep in mind that any DCP may render multiple variations of your multimedia component. From the Link object you can then get the URL to the binary.
Look for BinaryLink in the documentation for more details.
Try this:-
BinaryMeta binaryMeta = b.GetBinaryMeta(queryStringId);
if(binaryMeta != null) {
VideoBinaryUrl = binaryMeta.URLPath;
}
I did a SQL Profiler on the code and noticed that it was because I deployed my test app it wasn't calling the broker. Running the code within the actual Tridion Published site did hit the database but it was passing the value "[#def#]" for the variantId column.
I have now got it working with the following code:
IComponentMeta cm = cmf.GetMeta(queryStringId);
if (cm != null)
{
TcmId = queryStringId;
Title = cm.TryGetValue("title");
Summary = cm.TryGetValue("summary");
Product = cm.TryGetValue("product");
if (cm.SchemaId == StreamingContentSchemaId)
{
VideoId = cm.TryGetValue("video_url");
IsVimeo = true;
}
else if (cm.SchemaId == WebcastSchemaId)
{
using (var b = new BinaryMetaFactory())
{
var binaryMeta = b.GetMeta(queryStringId, "tcm:0-" + cm.OwningPublicationId + "-1");
if (binaryMeta != null)
{
VideoBinaryUrl = binaryMeta.UrlPath;
}
else
{
Logger.Log.ErrorFormat("Failed to load binary meta {0}", queryStringId);
}
}
}

ASP.Net MVC 3.0 C# How to find if a property Exists?

Hi i would like to check if a property exists?
This is my code
string abpath=null;
var hc= HttpContext.Current.Request.UrlReferrer;
if (hc.AbsolutePath !=null)
{
var _temp = HttpContext.Current.Request.UrlReferrer.AbsolutePath;
abpath = _temp.ToString();
}
I would like to Find out if AbsolutePath exists
can any one help me how to check.
right now it throws error as AbsolutePath doesn't exists to check
Thanks for your time
First you have to map the absolute path (url) to a local file system path. Then you can check whether the file exists:
var localPath = Server.MapPath(hc.AbsolutePath);
var exists = System.IO.File.Exists(localPath);
Update:
I guess I misunderstood the question. The problem is, that if your page/action/etc is called directly (e.g. by entering its URL in the browser), then there is no Referrer (previous page). So you have to first check Request.UrlReferrer for null:
if (hc != null && hc.AbsolutePath != null)
{
// ...
}
BTW: since AbsolutePath is already a string, there is no need to call ToString()on it. So you can simplify your code some more:
if (hc != null)
{
abpath = hc.AbsolutePath;
}
Check for url referrer first.
So try using code as below,
string abpath=null;
var hc= HttpContext.Current.Request.UrlReferrer;
if (hc !=null && !string.isNullOrEmpty(hc.AbsolutePath))
{
var _temp = HttpContext.Current.Request.UrlReferrer.AbsolutePath;
abpath = _temp.ToString();
}

Spoofing HTTP Referrer data using ASP.NET

Answers on here and various other sites are often full of warnings not to trust HTTP Referrer headers because they are 'so easily' spoofed or faked.
Before I go any further - no, I'm not up to no good - but I do want to run some referrer-dependant tests.
Whilst I don't doubt that the warnings about fake referrers are true, I can't really find much detailed info on how they can be manipulated. Even the Wikipedia article only talks about it in general terms.
I'm about to play with the RefControl addin for FireFox.
Programatically (in ASP.NET specifically) the UrlReferrer is a read-only property, so I don't see how I can fire off requests with fake referrer data if I can't set it? Do I really have to do it manually?
How would I use ASP.NET to send a request to my site with a user-supplied variable to populate the referrer header?
EDIT : As per my comment below, I ideally want to take an incoming request, manupulate the referrer data and then pass the request on to another page, intact. If I can make it appear intact by building a new one from scratch and copying the original properties, then that is fine too.
I don't know if this exactly what you want, but in general, you should be able to spoof the value of the UrlReferer property (even if it's read-only) in HttpContext.Current.Request by using a bit of reflection.
For example:
FieldInfo fi = HttpContext.Current.Request.GetType().GetField("_referrer", BindingFlags.NonPublic | BindingFlags.Instance);
string initialReferer = HttpContext.Current.Request.UrlReferrer.ToString();
if (fi != null)
fi.SetValue(HttpContext.Current.Request, new Uri("http://example.com"));
string fakedReferer = HttpContext.Current.Request.UrlReferrer.ToString();
On VS; these are the values before and after changing the UrlReferrer:
initialReferer
"http://localhost/Test/Default.aspx"
fakedReferer
"http://example.com/"
If you open the System.Web assembly using ILSpy you'll notice that the UrlReferrer property looks something like this:
public Uri UrlReferrer
{
get
{
if (this._referrer == null && this._wr != null)
{
string knownRequestHeader = this._wr.GetKnownRequestHeader(36);
if (!string.IsNullOrEmpty(knownRequestHeader))
{
try
{
if (knownRequestHeader.IndexOf("://", StringComparison.Ordinal) >= 0)
{
this._referrer = new Uri(knownRequestHeader);
}
else
{
this._referrer = new Uri(this.Url, knownRequestHeader);
}
}
catch (HttpException)
{
this._referrer = null;
}
}
}
return this._referrer;
}
}
This likely isn't going to get you what you want. But you can edit the Referror of an HttpWebRequest. I don't think there is a way of editing the referrer of your request in context.
using System.Net;
HttpWebRequest Req= (HttpWebRequest)System.Net.HttpWebRequest.Create("http://somewhere.com/");
Req.Referer = "http://www.fakesite.com";

Resources