.NET Tutorials, Forums, Interview Questions And Answers
Welcome :Guest
Sign In
Win Surprise Gifts!!!

Top 5 Contributors of the Month
Gaurav Pal
Post New Web Links

Writing to log file on first pageload (!ispostback). thread safe

Posted By:      Posted Date: October 27, 2010    Points: 0   Category :ASP.Net

Based on this piece of code, I want to do exactly like this demonstration.  However, correct me if I'm wrong but if two or more users somehow simultaneously access the web page at the same precise nanosecond in time, then wouldn't we have a race condition?  So is this piece of code valid?  How would I correct this to make it thread safe???

If you like to support this site, feel free to make a donation to support improvements.

Thank you!
Monetize Your Blog

How to track visitors to your site in ASP.NET & C#
Code to log the IP address & DNS name for visitors to each page
Posted on 4/3/2007 1:52:07 PM in #ASP.NET
[lnkImage] [lnkImage] [lnkImage] [lnkImage] [lnkImage] [lnkImage] [lnkImage] [lnkImage] [lnkImage] [lnkImage] [lnkImage] [lnkImage]   ASP.NET Social Bar? Get A Free one here!

Once you have published a site in ASP.NET, you'd like to know who are your visitors. One way is to check your event log on the host server. Another option is to write your own code. You'd basically like to log the IP address, and DNS name for the visitor, and it would be nice to know which page they are visiting.

To log the ip address using ASP.NET, you can call:


Another usefull variable is


View Complete Post

More Related Resource Links

file upload in chunks or not buffering in memory before writing to disk?


What are the options for handling file uploads to reduce the memory footprint?  Is there a way to upload in chunks?  Is there a way to stream upload directly to disk instead of loading entire file in server memory?


.NET Column: Safe Thread Synchronization


By far, the most common use of thread synchronization is to ensure mutually exclusive access to a shared resource by multiple threads. In the Win32® API, the CRITICAL_SECTION structure and associated functions offers the fastest and most efficient way to synchronize threads for mutually exclusive access when the threads are all running in a single process.

Jeffrey Richter

MSDN Magazine January 2003

Writing to a text file



I have the following  subroutine in an asp.net application class. The subroutine writes data to a text file upon application login.   My question is that if this function was called at the same time by two different  users would it cause any kind of error. Is there a need for a try catch?

 Public Shared Sub writeToLogFile(ByVal UserName  As String)
        Dim strLogMessage As String = String.Empty
        Dim strLogFile As String = System.Web.HttpContext.Current.Server.MapPath("~/Log.txt") Dim swLog As StreamWriter
        strLogMessage = DateTime.Now.ToShortDateString().ToString()  " ==> " & UserName

        If Not File.Exists(strLogFile) Then
            swLog = New StreamWriter(strLogFile)
            swLog = File.AppendText(strLogFile)
        End If


Writing the windows forms data to an HTML file

I have a windows forms application ready now i need to transfer data from the windows forms to the web and to do this i need to write an HTML file that contains the form data, i mean the data contained in the form should be written to an HTML file to be submitted and this HTML file should be generated on the local PC. I have the code for the HTML file but how can i write this HTML file with the data values contained in my windows forms. Please give your suggestions. Best Regards, Syed

ThreadPool with lock isn't thread safe

Hello, I'm having some problems with my code which apparently isn't thread safe at all. The problem is that it doesn't crash often, but of course it does when in production! I have twisted my mind around the problem for a month or so now, and I need some help in sorting out the problem. Well, the problem is that it isn't thread safe, and the collection (_subscribers) is modified while looping. The error says that it crashes in the method: SendRoundSettings. Here's part of the code (which I guess contains the error, as the other methods are pretty much identical): [ServiceBehavior(ConcurrencyMode = ConcurrencyMode.Multiple)] public class DuplexService : IDuplexService { private readonly object _syncRoot = new object(); private static Subscribers _subscribers = new Subscribers(); private static RoundSettings _currentRoundSettings = new RoundSettings() {CompetitionId = 1, NumberOfAthletesInRound = 0, Round = 0, SortDirection = SortDirection.ByStartNumber}; public void SendJudgeScore(CompetitionJudgeAthleteJump judgeScore) { ThreadPool.QueueUserWorkItem(state => { Subscribers clonedSubscribers = CloneSubscribers(); Console.WriteLine("Sending judgeScore to {0} client(s)", clonedSubscribers.Count(x => x.CompetitionId == judgeScore.CompetitionId));

javascript pageLoad() & client side isPostBack property?

Hello and thanks for your help in advance. I have some javascript code that I have placed in the pageLoad() function like this:function pageLoad() { var x = 5; }But I only want this to happen on the first time the page loads... Is there an isPostBack property on the client site?

C# Thread Safe Class events

Right now I have created a custom base class that has numerous events.  These events have non-standard signatures and are fired from a thread I have that is basically just a while loop checking variables against older ones for telling when something has changed. As far as I know this is the best way to go about doing this is to just make a void on another thread in a while (true) loop, in the loop just doing ifs... than doing a thread sleep.  I make sure the thread is a background thread that way it'll exit propertly when the consumer exits.  If anyone knows a beter way of going about this than stop reading here. :) If not that onto my real question... I have events that are fired from this loop on the thread I created, now they're attatched on the consumer app and no matter what I do I can't seem to get these events to be thread-safe so that I don't have to use the Control.Invoke method for each event. If anyone knows anything that'll help me out it'll be much appreciated. Thanks,Chad

Writing connection string in web.config file by code or dynamically

I want to write connection string in web.config file of my application by code. If anyone know the way or code just help me..NET,C#,SQL SERVER

writing xml data to a string instead of a file

Hi   I have a code that generate xml file from a database table and write the data in a xml file that is created by the program itself  // create xml file and xml writer XmlTextWriter xmlwrtr = new XmlTextWriter("c:\\SitemapTEST2.xml", null); I would like to write the xml data as a string and pass it to a datasource connection , how is this possible? something like this  this.ExplorerBarDataSource.Data = @"<?xml version='1.0' encoding='UTF-8'?> <countries> <country name='United States'> <state name='Alabama'> <city name='Montgomery' pubulation='22,000'/> <city name='Birmingham'/> <city name='Tuscaloosa'/> <city name='Huntsville'/> </state> </country> </countries>";     thanks    

Writing to excel file - The field is too small to accept the amount of



I am writing to excel file using jet driver. If the length of value exceeds 255 characters i get the below error.

'The field is too small to accept the amount of data you attempted to add.  Try inserting or pasting less data'

Please could you provide a solution to how can i add values with length greater than 255. Excel file is 97-2003 format.

System.Data.OleDb.OleDbCommand command = new System.Data.OleDb.OleDbCommand();
 System.Data.OleDb.OleDbConnection connection =
          new System.Data.OleDb.OleDbConnection(
              "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + destinationFilePath + ";Extended Properties=Excel 8.0;");
command.CommandText = "Insert into [sheet1$] (col1, col2) values ('1', 'TEXT Message greater than 255 characters')

Writing to a csv file


Once again I have trawled the web for a WPF (VB) example of writing to a CSV file. I have found several in C# and Forms VB and managed to work out reading from CSV. However, the writing version I have come up with adds a blank line after each actual line. Also the first cell written to the CSV file contains some wierd characters just before the genuine content. (i.e. #?!Name1 instead of just Name1); I have shown the code below.

  Sub writeCSVData()
    If File.Exists("resources\csvData.csv") Then
      MsgBox("resources\csvData.csv doesn't exist")
    End If
    MyFileName = "resources\csvData.csv"

    myCSVWriter = My.Computer.FileSystem.OpenTextFileWriter(MyFileName, True)

    For y = 0 To 14
      myNewLine = ""

Are non-static objects thread-safe in a static-method?


I am using javascript and ajax to call server side mothod.  The pagemethod can only be static function in teh server side.  But i know static methods are not thread safe across simultaneous sessions.  However, what if the static method is modifying a non-static object?

for example:

public partial class default : system.web.ui.page

Hero Superman; // create an object called superman of class hero for all user sessions independently

public static int(newpowers)


Superman.powers = newpowers;  // Is this thread safe?  Will each user not accidentally get written by another user's power values?


web service thread-safe?



I am using a COPY web service. Is the function that uploads a document, COPYINTOITEMS, a thread-safe? If not, what is a good way to do a similar thing?

I am thinking to create one copy object and all incoming requests(thread) share this object to invoke CopyIntoItems function.

Thank you.

Is Dispatcher.BeginInvoke really NOT thread safe, while the old System.Windows.Forms.Control.BeginIn




System.Windows.Forms.Control.BeginInvoke is documented as thread safe (in fact, BeginInvoke , EndInvoke , Invoke , InvokeRequired , and CreateGraphics are).



But in WPF, Dispatcher.BeginInvoke is not documented as thread safe. Which would appear to me as a regression (and not really convenient, to be honest).

Was it only forgotten in MSDN documentation, or should I really use external locking to prevent the dispatcher to get lost in its messages and priorities?



Thanks. ;)

Writing File in Oracle to Secured Directory on NAS Server


I have a stored procedure that creates a comma delimited file. I can easily write to a directory on the database server, but I would like to write the file to a mapped network directory on a NAS server. The issue, at least conceptually (sorry for being a novice here), is that I have no way of accessing or embedding the necessary username/password to write to the specified directory.

Based on initial research, it looks like the oracle account is the one writing the file. Would that mean that the oracle account would have to have the appropriate privileges to the NAS directory? Who would that oracle user be? The niku account user being used to execute the proc?

Kind of lost here. Would like to send directly to the NAS to avoid an SFTP to another environment.

ASP.NetWindows Application  .NET Framework  C#  VB.Net  ADO.Net  
Sql Server  SharePoint  Silverlight  Others  All   

Hall of Fame    Twitter   Terms of Service    Privacy Policy    Contact Us    Archives   Tell A Friend