how to Output page hits to a text document - asp.net

I have an HTML home page. I want to be able to output to a text document on the server every time a person views the page.
I want to out put the IP addrs, Page and Date/Time anyone know an easy way of doing this?
If it has to be done other than html i would prefer to use ASP.

First, rename the page to have .aspx extension and add code behind file as well.
Second, add this method to the code behind:
private void WriteLog()
{
string currentFileName = Path.GetFileNameWithoutExtension(Request.FilePath);
string logFileName = string.Format("{0}_{1}.log.txt", currentFileName, DateTime.Now.ToString("ddMMyyyy"));
string logFilePath = Server.MapPath(logFileName);
string IP = Request.ServerVariables["REMOTE_ADDR"];
string logMessage = string.Format("[{0}] [IP: {1}] [Page: {2}]", DateTime.Now.ToString("dd/MM/yyyy HH:mm:ss"), IP, Request.FilePath);
File.AppendAllLines(logFilePath, new string[] { logMessage });
}
And finally just call the above method from within the Page_Load event e.g.
protected void Page_Load(object sender, EventArgs e)
{
WriteLog();
}
This will create text file with the same name as the .aspx (in the same location) plus the current date to avoid clogging the same file with millions of lines, and append one line for each hit.
Edit: this is .NET 4.0 code so you'll have to define this as the target framework in both Visual Studio in case you're using it, and in the IIS configuration. The web.config should be updated by the Studio and in case you're not using it, here are the extra lines:
<system.web>
<httpRuntime requestValidationMode="2.0" />
<compilation debug="true" targetFramework="4.0" />
</system.web>

As #Alp said PHP would be the way to go:
$_SERVER['REMOTE_ADDR']; //gives you the visitor's IP address
basename($_SERVER["SCRIPT_NAME"]); //gives you the page name
date(); // gives you the current date
Then it would just be a case of running a little script that writes those to a file on each page.
Might be worth looking at Google Analytics - it gives lot's of useful stats about visitors (not 100% you can get individual IP addresses, can anyone clarify this?)
Edit:
ASP.NET
Request.ServerVariables["REMOTE_ADDR"]; // ip
Request.ServerVariables["HTTP_REFERER"]; // page

You can use PHP for that if your server supports it.

You can use an existing log framework like Log4Net.

Related

ASP - How to run a query on all connection strings listed in web.config

I have several connection strings defined in web.config, e.g.
<add
name="exampleConnStr"
connectionString="Driver=ODBCDriver;server=blah;"
providerName="Systerm.Data.Odbc"
/>
I'm drowning in MSDN documentation (which doesn't seem very good quality if I'm honest). What I'm trying to do is execute the same query against all of the databases defined within the web.config from an ASP page.
Can anyone show an example or provide search criteria likely to give me a hint?
Thanks
From what I can tell this is a very straight forward task. You will need to use the System.Configuration namespace for this.
using System.Configuration;
string conString;
for (int i = 0; i < ConfigurationManager.ConnectionStrings.Count; i++)
{
conString = ConfigurationManager.ConnectionStrings[i].ConnectionString;
// No point to the conString variable, just showing how to access the connectionstring.
}

Create HTTP POST method in ASP.NET which accepts CGI variables

I have an ASP.NET (.NET v4) web application running on IIS 7.5. I have a 3rd party which wants to pass information to my system. They support passing this information using HTTP POST, the information they provide is:
"This method simply calls a script on your server and passes each
field as a CGI variable. When you have received the data your server
should return a '1' on a line by itself to indicate success. Anything
else will generate an error on our server which will be investigated.
To set up this delivery method we need a URL to post to. We can use
HTTP or HTTPS."
My web application currently implements many WCF services but as I don't know what the variables passed in will be I cannot define a specific contract. Can I create a normal aspx page which they can post to and then read each of the parameters passed and do the appropriate processing.
If I do this how do I send back a line containing '1'?
Do I need to do anything else to make this HTTP POST compatible.
The last time I had to tackle a similar situation, i did it using a standard ASPX page, and it all worked quite well.
In my case the output was XML, so I had to make sure that I changed the output mime type to match "text/xml" in my case.. "text/plain" I would guess in yours..
Anyway, C# sharp code below, and make sure that your ASPX file has ONLY the very top line in, that is:
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="register.aspx.cs" Inherits="myservices.register" ContentType="text/xml" %>
and nothing else, no carriage returns or anything.
Then do all your work in the code behind:
protected void Page_Load(object sender, EventArgs e)
{
Response.Clear();
Response.ContentType = "text/plain";
//Get your CGI variables here... you will have to get them to tell you what to expect
string myparam = (string)Request.QueryString["myparam"];
//do what ever you need here with your variables
Response.Write("1");
Response.End();
}// End page load handler
If you need to follow the one with a carriage return, then i believe you can use the carriage return property in the system.environment object, but I've not got doc's to hand to look it up. That should however get you started.
The MOST important thing to remember is to make sure NOTHING is output from the aspx, not even a carriage return.
I've previously written an article on my Blog about how to use this method for producing phone directories for Cisco-IP phones if you want to read it. You can find it here: http://shawtyds.wordpress.com/2009/09/26/cisco-ip-phone-directories-using-c/

URL Encoding being lost before processing - ASP.net

I am building a web-store that uses URL encoding extensively.
I have a list of Departments & Categories in my database which I use to generate the links. These are, of course, URL encoded before they are sent.
Some Typical Links are...
/MySite/Store/Countertop+Equipment/Can+Openers.aspx
/MySite/Store/Dinnerware.aspx
/MySite/Store/Kitchen/Pastry%2f+Decorating.aspx
In my HTTPHandler I call app.Request.Path to obtain the current path. The string returned by this call is no longer URL encoded which is making it impossible for me to parse correctly.
Once the URL encoding is lost
/MySite/Store/Kitchen/Pastry%2f+Decorating.aspx becomes
/MySite/Store/Kitchen/Pastry/Decorating.aspx.
This is obviously breaking the method that converts the URL to a QueryString.
Anyone know how to fix this?
Here is the core of my HTTPHandler
public void Init(System.Web.HttpApplication app)
{
app.BeginRequest += new EventHandler(Application_BeginRequest);
}
private void Application_BeginRequest(object sender, EventArgs e)
{
System.Web.HttpApplication app = (System.Web.HttpApplication)sender;
string realUrl = GetRealUrl(app.Request.Path);
if (!String.IsNullOrEmpty(realUrl))
app.Context.RewritePath(realUrl, false);
}
I really appreciate your help!
You cannot use Request.Url (including Url..PathAndQuery, AbsolutePath etc) as its OriginalString is already decoded.
So there is no point to use Request.Url at all and you can try to play with following:
Request.AppRelativeCurrentExecutionFilePath
Request.CurrentExecutionFilePath
Or in a worst-case scenario you'll need to parse the Url:
[Test]
public void RewriteProoveOfConcept() {
var path = #"/MySite/Store/Kitchen/Pastry%2f+Decorating.aspx";
var res = Regex.Replace(path, #"/(.+)/(.+)/(.+)/(.+)\.aspx", #"/$1/YourPage.aspx?category1=$2&category2=$3&category3=$4");
Assert.AreEqual(#"/MySite/YourPage.aspx?category1=Store&category2=Kitchen&category3=Pastry%2f+Decorating", res);
}
This shows how you can get the URL:
/MySite/YourPage.aspx?category1=Store&category2=Kitchen&category3=Pastry%2f+Decorating
from:
/MySite/Store/Kitchen/Pastry%2f+Decorating.aspx
Additionally consider using Routing instead of UrlRewrite.
Cheers,
Dmitriy.
Try the AbsolutePath or PathAndQuery properties on the Request object. Both of them should maintain the url encoding.
You can UrlEncode the URL before parsing it. Or better yet, keep URL's non-encoded in database. You don't even need to encode them if you use HyperLink control.
It turns out that the issue is occurring in IIS before .Net even gets its hands on the request. It appears that this is a dead end.
An additional word of warning is that my IIS test server (XP) was rejecting requests containing encoded amperstands as a security risk and could not be persuaded to cooperate with anything short of a registry edit. Not sure if this goes for all versions, but even if a server variable can be retrieved this seems like another good reason to use a different tactic.
Here is the follow-up question with the accepted solution-
ASP.Net URL Encoding

Resource file for a Custom ASP.net control (.ascx) InvalidOperationException

I have a control containing some text which I want to get from a resx file, I thought I could just create a file called ControlName.ascx.resx but that doesn't seem to be working.
I'm using
label1.InnerText = (string)GetLocalResourceObject("default");
To get the value from the resource file but it keeps throwing up an InvalidOperation Exception.
Am I right about how resx files work or does it only work for Pages?
I have the same code working on an aspx page.
When you call GetLocalResourceObject from within a user control, you are actually calling TemplateControl.GetLocalResourceObject, which will look in the wrong place for the resource file. You need to call HttpContext.GetLocalResourceObject instead.
protected string HttpContextGetLocalResourceObjectAsString(string message)
{
string path = HttpContext.Current.Request.Path;
return (HttpContext.GetLocalResourceObject(path, message) as string);
}
Now you can do
label1.InnerText = HttpContextGetLocalResourceObjectAsString("default");
Per the documentation:
Gets a page-level resource
http://msdn.microsoft.com/en-us/library/system.web.httpcontext.getlocalresourceobject.aspx
Edit- added
It may be less work to just add the string to the web.config and grab it from there.
<configuration>
<appSettings>
<add key="LoggingSystemId" value="B2F085A9-6EC1-4CBF-AF8B-B17BFA75AD81"/>
<appSettings>
...
referenced as follows:
logger.SystemId = System.Configuration.ConfigurationManager.AppSettings["LoggingSystemId"];
Of course, you'll need a reference to the System.Configuration dll.
A year or so later, but i think this is what you're after?
var resource = HttpContext.GetLocalResourceObject(TemplateControl.AppRelativeVirtualPath, termType.ToString());
Mark answer if that's the one!

How do you globally set the date format in ASP.NET?

How do you globally set the date format in ASP.NET?
My local machine and servers have Regional Settings set to "English (New Zealand)".
When I format a date with dd/MM/yyyy I expect to see 19/11/2008 for today for example.
Until recently, that is what I did in fact get from both my local machine and the servers.
Just recently, for some mysterious reason, our local machines have changed ever so slightly. Despite still be set to "English (New Zealand)", the date delimter has changed from / to -! The same change has not occurred on the servers which still show "English (New Zealand)" and the / for the date delimter.
So now for my local machine, for the format dd/MM/yyyy I get 19-11-2008 instead of 19/11/2008.
This is a little disconcerting.
The only way around it that I can see so far is to escape the slashes and set the format to dd\/MM\/yyyy. It seems to work, but it doesn't seem to be the ideal solution.
Can anyone please help?
NOTE: This is for an intranet application and I do not care about true globalisation. I just want to fix the date format and not have it change on me.
You can change the current thread culture in your Global.asax file, and override the date format for example:
using System.Globalization;
using System.Threading;
//...
protected void Application_BeginRequest(Object sender, EventArgs e)
{
CultureInfo newCulture = (CultureInfo) System.Threading.Thread.CurrentThread.CurrentCulture.Clone();
newCulture.DateTimeFormat.ShortDatePattern = "dd-MMM-yyyy";
newCulture.DateTimeFormat.DateSeparator = "-";
Thread.CurrentThread.CurrentCulture = newCulture;
}
In web.config, set tag as per the following documentation
<system.web>
<globalization culture="en-NZ" uiCulture="en-NZ"/>
</system.web>
A good way is configure the Web.Config, the date format appear in all components of a aspx
<system.web>
<globalization uiCulture="en" culture="en-NZ" />
</system.web>
You can set your culture without manipulation:
using System.Globalization;
using System.Threading;
//...
protected void Application_BeginRequest(Object sender, EventArgs e)
{
Thread.CurrentThread.CurrentCulture = Thread.CurrentThread.CurrentUICulture = new CultureInfo("en-NZ");
}
It is an old post, but I thought it might be useful to mention it here, my problem was something like what the OP has asked, but the solution was that the culture was changed in the IIS, not from control panel.
IIS has it is own culture selection, which by default will follow the local computer culture. But for some reason, it was changed to a different culture, and I started getting those weird date formats.
You can look for more answers here.
For format strings, the format character / does not actually resolve to the literal "/" as you would expect. Instead, it resolves to the current date time separator as configured in your regional settings. Try changing the DateTimeFormatInfo.DateSeparator property.
For more information, see: http://msdn.microsoft.com/en-us/library/8kb3ddd4.aspx

Resources