Solved

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

Posted on 2008-09-30
14
661 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
  • 6
  • 5
  • 3
14 Comments
 
LVL 83

Expert Comment

by:CodeCruiser
Comment Utility
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
Comment Utility
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
Comment Utility
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
 
LVL 83

Expert Comment

by:CodeCruiser
Comment Utility
Yes i would say.
0
 
LVL 3

Author Comment

by:utlonghornjulie
Comment Utility
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
Comment Utility
I would suggest that, just for debugging purposes, test this with a public share rather than $ share.
0
 
LVL 3

Author Comment

by:utlonghornjulie
Comment Utility
I do not have any public shares on the server. All the drives are shared $.
0
Maximize Your Threat Intelligence Reporting

Reporting is one of the most important and least talked about aspects of a world-class threat intelligence program. Here’s how to do it right.

 
LVL 83

Expert Comment

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

Author Comment

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

Expert Comment

by:CodeCruiser
Comment Utility
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
Comment Utility
I have done that, and it is still not working.
0
 
LVL 11

Accepted Solution

by:
AkisC earned 500 total points
Comment Utility
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
Comment Utility
what should i enter for <domainname>?
0
 
LVL 11

Expert Comment

by:AkisC
Comment Utility
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

Find Ransomware Secrets With All-Source Analysis

Ransomware has become a major concern for organizations; its prevalence has grown due to past successes achieved by threat actors. While each ransomware variant is different, we’ve seen some common tactics and trends used among the authors of the malware.

Join & Write a Comment

This article explains how to create and use a custom WaterMark textbox class.  The custom WaterMark textbox class allows you to set the WaterMark Background Color and WaterMark text at design time.   IMAGE OF WATERMARKS STEPS Create VB …
Microsoft Reports are based on a report definition, which is an XML file that describes data and layout for the report, with a different extension. You can create a client-side report definition language (*.rdlc) file with Visual Studio, and build g…
Illustrator's Shape Builder tool will let you combine shapes visually and interactively. This video shows the Mac version, but the tool works the same way in Windows. To follow along with this video, you can draw your own shapes or download the file…
You have products, that come in variants and want to set different prices for them? Watch this micro tutorial that describes how to configure prices for Magento super attributes. Assigning simple products to configurable: We assigned simple products…

771 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

Need Help in Real-Time?

Connect with top rated Experts

13 Experts available now in Live!

Get 1:1 Help Now