Still celebrating National IT Professionals Day with 3 months of free Premium Membership. Use Code ITDAY17

x
?
Solved

XCopy working on my localhost, but not working on test environment

Posted on 2008-09-30
14
Medium Priority
?
685 Views
Last Modified: 2012-05-05
This is the code I am using to XCopy a folder's contents from one server to a folder on a second server. The XCopy works fine if I am testing on my localhost. My localhost is located on the destination server. But when I try and run the application on our test environment, the XCopy does not work. Instead, it gives the following error:

Server Error in '/' Application.
--------------------------------------------------------------------------------

Process must exit before requested information can be determined.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.InvalidOperationException: Process must exit before requested information can be determined.

Source Error:


Line 271:
Line 272:        'or the wait time you want
Line 273:        Dim ExitCode As Integer = XCopyProcess.ExitCode
Line 274:        Dim XCopySuccessful As Boolean = True
Line 275:
 

Source File: D:\Inetpub\Test_IEnergy\NewProspectBatchLoadTDSP.aspx.vb    Line: 273

Stack Trace:


[InvalidOperationException: Process must exit before requested information can be determined.]
   System.Diagnostics.Process.EnsureState(State state) +864
   System.Diagnostics.Process.get_ExitCode() +21
   NewProspectBatchLoadTDSP.ProcessXCopy() in D:\Inetpub\Test_IEnergy\NewProspectBatchLoadTDSP.aspx.vb:273
   NewProspectBatchLoadTDSP.LoadTDSPDataButton_Click(Object sender, EventArgs e) in D:\Inetpub\Test_IEnergy\NewProspectBatchLoadTDSP.aspx.vb:214
   System.Web.UI.WebControls.Button.OnClick(EventArgs e) +114
   System.Web.UI.WebControls.Button.RaisePostBackEvent(String eventArgument) +141
   System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument) +32
   System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +3215

 
This is caused by the XCopy not finishing. Can someone please tell me why it is working on my localhost (which is on the destination server), but it is not working on the test environment????
The test environment I am running from is on Internet Explorer, on my machine at work, which runs Windows XP. The code itself is running on the destination server. Please help!!!
Public Function ProcessXCopy() As Boolean
        'Dim XCopyArguments As String = "\\<sourceServerIPAddress>\E$\Input \\<destinationServerIPAddress>\D$\Input"
        Dim XCopyProcess As New System.Diagnostics.Process()
        Dim XCopyStartInfo As New System.Diagnostics.ProcessStartInfo()
 
        XCopyStartInfo.FileName = "cmd.exe"
 
        'do not write error output to standard stream
        XCopyStartInfo.RedirectStandardError = False
        'do not write output to Process.StandardOutput Stream
        XCopyStartInfo.RedirectStandardOutput = False
        'do not read input from Process.StandardInput (i/e; the keyboard)
        XCopyStartInfo.RedirectStandardInput = False
 
        XCopyStartInfo.UseShellExecute = False
        'Dont show a command window
        XCopyStartInfo.CreateNoWindow = True
 
        'XCopyStartInfo.Arguments = "XCOPY " & XCopyArguments
 
        XCopyStartInfo.Arguments = "XCOPY \\<sourceServerIPAddress>\E$\Input \\<destinationServerIPAddress>\D$\Input"
 
 
        XCopyProcess.EnableRaisingEvents = True
        'XCopyProcess.StartInfo.RedirectStandardOutput = True
        XCopyProcess.StartInfo = XCopyStartInfo
 
        'start cmd.exe & the XCOPY process
        XCopyProcess.Start()
 
        'set the wait period for exiting the process
        XCopyProcess.WaitForExit(15000)
 
 
 
        'While Not XCopyProcess.HasExited
 
 
        'End While
 
        'or the wait time you want
        Dim ExitCode As Integer = XCopyProcess.ExitCode
        Dim XCopySuccessful As Boolean = True
 
        'Now we need to see if the process was successful
        If ExitCode > 0 And Not XCopyProcess.HasExited Then
            XCopyProcess.Kill()
            XCopySuccessful = False
        End If
 
        'now clean up after ourselves
        XCopyProcess.Dispose()
        XCopyStartInfo = Nothing
        Return XCopySuccessful
    End Function

Open in new window

0
Comment
Question by:utlonghornjulie
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 6
  • 5
  • 3
14 Comments
 
LVL 83

Expert Comment

by:CodeCruiser
ID: 22612389
I can see that you are using the e$ and d$ folders. Is there any difference if you share the folders instead?
0
 
LVL 11

Expert Comment

by:AkisC
ID: 22612505
Probably you face a problem with user rights
D$ are shares for administrators
Try using a user with administrator rigths and use imrepsonation to xcopy your files

 Dim myDomainName As String = "", thisUserName As String = "", thisPassword As String = ""
'/////thisUserName As String = "", thisPassword As String = "" must have admin rights

'///USAGE
        Dim imp As New RunAs_Impersonator
        Try
            imp.ImpersonateStart(myDomainName, thisUserName, thisPassword) 'creates new context using token for user
            '//Add code to run as UserName here
            'everything between ImpersonateStart and ImpersonateStop will be run as the impersonated user
            imp.ImpersonateStop()
        Catch ex As Exception 'make sure impersonation is stopped whether code succeeds or not
            imp.ImpersonateStop()
            MsgBox(ex.Message)
        End Try
Imports System
Imports System.Runtime.InteropServices
Imports System.Security.Principal
Imports System.Security.Permissions
Imports Microsoft.VisualBasic
<Assembly: SecurityPermissionAttribute(SecurityAction.RequestMinimum, UnmanagedCode:=True), _
 Assembly: PermissionSetAttribute(SecurityAction.RequestMinimum, Name:="FullTrust")> 
 
Public Class RunAs_Impersonator
#Region "Private Variables and Enum Constants"
    Private tokenHandle As New IntPtr(0)
    Private dupeTokenHandle As New IntPtr(0)
    Private impersonatedUser As WindowsImpersonationContext
#End Region
#Region "Properties"
 
#End Region
#Region "Public Methods"
    Public Declare Auto Function CloseHandle Lib "kernel32.dll" (ByVal handle As IntPtr) As Boolean
 
    Public Declare Auto Function DuplicateToken Lib "advapi32.dll" (ByVal ExistingTokenHandle As IntPtr, _
      ByVal SECURITY_IMPERSONATION_LEVEL As Integer, _
      ByRef DuplicateTokenHandle As IntPtr) As Boolean
 
    ' Test harness.
    ' If you incorporate this code into a DLL, be sure to demand FullTrust.
    <PermissionSetAttribute(SecurityAction.Demand, Name:="FullTrust")> _
    Public Sub ImpersonateStart(ByVal Domain As String, ByVal userName As String, ByVal Password As String)
        Try
            tokenHandle = IntPtr.Zero
            ' Call LogonUser to obtain a handle to an access token.
            Dim returnValue As Boolean = LogonUser(userName, Domain, Password, 2, 0, tokenHandle)
 
            'check if logon successful
            If returnValue = False Then
                Dim ret As Integer = Marshal.GetLastWin32Error()
                Console.WriteLine("LogonUser failed with error code : {0}", ret)
                Throw New System.ComponentModel.Win32Exception(ret)
                Exit Sub
            End If
 
            'Logon succeeded
 
            ' Use the token handle returned by LogonUser.
            Dim newId As New WindowsIdentity(tokenHandle)
            impersonatedUser = newId.Impersonate()
        Catch ex As Exception
            Throw ex
            Exit Sub
        End Try
        MsgBox("running as " & impersonatedUser.ToString & " -- " & WindowsIdentity.GetCurrent.Name)
    End Sub
    <PermissionSetAttribute(SecurityAction.Demand, Name:="FullTrust")> _
    Public Sub ImpersonateStop()
        ' Stop impersonating the user.
        impersonatedUser.Undo()
 
        ' Free the tokens.
        If Not System.IntPtr.op_Equality(tokenHandle, IntPtr.Zero) Then
            CloseHandle(tokenHandle)
        End If
        MsgBox("running as " & Environment.UserName)
    End Sub
#End Region
#Region "Private Methods"
    Private Declare Auto Function LogonUser Lib "advapi32.dll" (ByVal lpszUsername As [String], _
     ByVal lpszDomain As [String], ByVal lpszPassword As [String], _
     ByVal dwLogonType As Integer, ByVal dwLogonProvider As Integer, _
     ByRef phToken As IntPtr) As Boolean
 
    <DllImport("kernel32.dll")> _
    Public Shared Function FormatMessage(ByVal dwFlags As Integer, ByRef lpSource As IntPtr, _
     ByVal dwMessageId As Integer, ByVal dwLanguageId As Integer, ByRef lpBuffer As [String], _
     ByVal nSize As Integer, ByRef Arguments As IntPtr) As Integer
    End Function
#End Region
End Class

Open in new window

0
 
LVL 3

Author Comment

by:utlonghornjulie
ID: 22614804
Ok I added the code to impersonate. But it is still not working and it is still timing out. Do I need to add <identity impersonate="true" /> to my web.config file?
Public Function ProcessXCopy() As Boolean
        Dim XCopyProcess As New System.Diagnostics.Process()
        Dim XCopyStartInfo As New System.Diagnostics.ProcessStartInfo()
        Dim ExitCode As Integer
        Dim XCopySuccessful As Boolean
        Dim myDomainName As String = "<domainname>", thisUserName As String = "<username>", thisPassword As String = "<password>"
        '/////thisUserName As String = "", thisPassword As String = "" must have admin rights
 
        '///USAGE
        Dim imp As New RunAs_Impersonator
        Try
            imp.ImpersonateStart(myDomainName, thisUserName, thisPassword) 'creates new context using token for user
            '//Add code to run as UserName here 
            'everything between ImpersonateStart and ImpersonateStop will be run as the impersonated user
            XCopyStartInfo.FileName = "cmd.exe"
 
            'do not write error output to standard stream
            XCopyStartInfo.RedirectStandardError = False
            'do not write output to Process.StandardOutput Stream
            XCopyStartInfo.RedirectStandardOutput = False
            'do not read input from Process.StandardInput (i/e; the keyboard)
            XCopyStartInfo.RedirectStandardInput = False
 
            XCopyStartInfo.UseShellExecute = False
            'Dont show a command window
            XCopyStartInfo.CreateNoWindow = True
 
           
 
            XCopyStartInfo.Arguments = "XCOPY \\<sourceIPAddress>\E$\Input \\<destinationIPAddress>\D$\Input"
 
 
            XCopyProcess.EnableRaisingEvents = True
            'XCopyProcess.StartInfo.RedirectStandardOutput = True
            XCopyProcess.StartInfo = XCopyStartInfo
 
            'start cmd.exe & the XCOPY process
            XCopyProcess.Start()
 
            'set the wait period for exiting the process
            XCopyProcess.WaitForExit(15000)
 
 
 
            While Not XCopyProcess.HasExited
                System.Threading.Thread.Sleep(500) 'Wait 500 ms 
            End While
 
            'or the wait time you want
            ExitCode = XCopyProcess.ExitCode
            XCopySuccessful = True
 
            'Now we need to see if the process was successful
            If ExitCode > 0 And Not XCopyProcess.HasExited Then
                XCopyProcess.Kill()
                XCopySuccessful = False
            End If
 
            imp.ImpersonateStop()
        Catch ex As Exception 'make sure impersonation is stopped whether code succeeds or not
            imp.ImpersonateStop()
            'MsgBox(ex.Message)
            Response.Write("<script language = 'jscript'>")
            Response.Write("alert('" & ex.Message & "')")
            Response.Write("</script>")
        End Try
 
 
        'now clean up after ourselves
        XCopyProcess.Dispose()
        XCopyStartInfo = Nothing
        Return XCopySuccessful
    End Function

Open in new window

0
What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

 
LVL 83

Expert Comment

by:CodeCruiser
ID: 22614828
Yes i would say.
0
 
LVL 3

Author Comment

by:utlonghornjulie
ID: 22615149
I added it, and it is still not working. The domain name that I am passing into the class is the IP address of the server correct?
0
 
LVL 83

Expert Comment

by:CodeCruiser
ID: 22615178
I would suggest that, just for debugging purposes, test this with a public share rather than $ share.
0
 
LVL 3

Author Comment

by:utlonghornjulie
ID: 22615883
I do not have any public shares on the server. All the drives are shared $.
0
 
LVL 83

Expert Comment

by:CodeCruiser
ID: 22616077
Can you not make one for testing? Try making one on another machine or your own computer.
0
 
LVL 3

Author Comment

by:utlonghornjulie
ID: 22616089
I do not know how to make a new drive on the server.
0
 
LVL 83

Expert Comment

by:CodeCruiser
ID: 22616158
Dont make a new drive. Right click on a folder and select Sharing. Then enable the sharing and confirm the name of the share and use that name.
0
 
LVL 3

Author Comment

by:utlonghornjulie
ID: 22635292
I have done that, and it is still not working.
0
 
LVL 11

Accepted Solution

by:
AkisC earned 2000 total points
ID: 22638616
The IUSER_<<machine name>> must have next of full rights to the $ share.
-but- $ share are only for administrators. So imersonation is your only solution.

Is this line used as you have posted it?
Dim myDomainName As String = "<domainname>", thisUserName As String = "<username>", thisPassword As String = "<password>"
-Or-
You replace the <> values with existing ones?
I'd suggest that String = "<username>" shoud be String = "administrator"

Finally, your web server should have execute rights
0
 
LVL 3

Author Comment

by:utlonghornjulie
ID: 22681208
what should i enter for <domainname>?
0
 
LVL 11

Expert Comment

by:AkisC
ID: 22687327
If you have active directory installed on your network then you should enter the active directory domain name
If you are working on a workgroup enter the work group name
0

Featured Post

Free Tool: Subnet Calculator

The subnet calculator helps you design networks by taking an IP address and network mask and returning information such as network, broadcast address, and host range.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Well, all of us have seen the multiple EXCEL.EXE's in task manager that won't die even if you call the .close, .dispose methods. Try this method to kill any excels in memory. You can copy the kill function to create a check function and replace the …
Introduction As chip makers focus on adding processor cores over increasing clock speed, developers need to utilize the features of modern CPUs.  One of the ways we can do this is by implementing parallel algorithms in our software.   One recent…
Video by: ITPro.TV
In this episode Don builds upon the troubleshooting techniques by demonstrating how to properly monitor a vSphere deployment to detect problems before they occur. He begins the show using tools found within the vSphere suite as ends the show demonst…
Have you created a query with information for a calendar? ... and then, abra-cadabra, the calendar is done?! I am going to show you how to make that happen. Visualize your data!  ... really see it To use the code to create a calendar from a q…

671 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question