Thursday, July 25, 2019

Parse XML with namespace based on xslt

    There is a xml file (sample.xml) which contains a self-defined namespace. I want to retrieve <w:r><w:t> value and that <w:r> should not contain child <w:pict> inside it. So, as per my below XML Document i want to generate following output:
<paragraph>This is the text that i need to retrieve...</paragraph>
    
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<?xml-stylesheet type="text/xsl" href="sample.xsl"?>
<w:document xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">
<w:body>
    <w:p> <!-- Current Node -->
        <w:r>
            <w:t>
                 This is the
            </w:t>
        </w:r>
        <w:r>
            <w:pict>
                <w:p>
                    <w:r>
                        <w:t>
                            I dont need this
                        </w:t>
                    </w:r>
                </w:p>
            </w:pict>
        </w:r>
        <w:r>
            <w:pict>
                <w:p>
                    <w:r>
                        <w:t>
                            I dont need this too
                        </w:t>
                    </w:r>
                </w:p>
            </w:pict>
        </w:r>
        <w:r>
            <w:t>
                 text that i need to retrieve...
            </w:t>
        </w:r>
    </w:p>
</w:body>
</w:document>
        
 The relative xslt file (sample.xsl) as below:

<?xml version="1.0" encoding="ISO-8859-1"?>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">
<xsl:template match="/">
  <html>
    <body>
      <table border="1"><td>
        <![CDATA[<paragraph>]]>
          <xsl:for-each select="//w:r[not(ancestor::w:pict)]">
            <xsl:value-of select="w:t"/>
          </xsl:for-each>
        <![CDATA[</paragraph>]]></td>
      </table>
    </body>
  </html>
</xsl:template>

</xsl:stylesheet>

Check and release the used port

1 Click Start->Run->cmd or press key Win+R to call the command line window.

2 Input command netstat -aon|findstr "8080" and press Enter key to check the PID of the process that using the port. e.g. 2623

3 Input command tasklist|findstr "2623" and press Enter key to check the relative process name. e.g. javaw.exe

4 Input command taskkill /f /t /im javaw.exe and press Enter key to kill the relative process.

Fetch data from another DB server (sql server)

way 1:
exec   sp_addlinkedserver     'srv_lnk','','SQLOLEDB','cnshdnfeng1'   
exec   sp_addlinkedsrvlogin   'srv_lnk','false',null,'sa','sa'  
go

select * from   srv_lnk.SunSystemsData.dbo.ANL_DIR
exec   sp_dropserver   'srv_lnk','droplogins'

way 2:
sp_configure 'show advanced options', 1;
GO
RECONFIGURE;
GO
sp_configure 'Ad Hoc Distributed Queries', 1;
GO
RECONFIGURE;
GO
select * from openrowset('SQLOLEDB','cnshdnfeng1';'sa';'sa', SunSystemsData.dbo.ANL_DIR)

Summary for synchronization in .NET

The following tables summarize the .NET tools available for coordinating or synchronizing the actions of threads:

1 Simple Blocking Methods
    
ConstructPurpose
SleepBlocks for a given time period
JoinWaits for another thread to finish

2 Locking Constructs
ConstructPurposeCross Process?Speed
LockEnsures just one thread can access a resource, or section of code.NoFast
MutexEnsures just one thread can access a resource, or section of code. Can be used to prevent multiple instances of an application from starting.YesModerate
SemaphoreEnsures not more than a pecified number of therads can access a resource, or section of code.YesModerate

(Synchronization Context are also provided, for automatic locking)
3 Signaling Constructs
ConstructPurposeCross Process?Speed
EventWaitHandleAllows a thread to wait until it receives a signal from another therad.YesModerate
Wait & PulseAllows a thread to wait until a custom blocking condition is met.NoModerate
4 Non-Blocking Synchronization Constructs
ConstructPurposeCross Process?Speed
InterlockedTo perform simple non-blocking atomic operations.Yes (Assuming shared memory)Very fast
volatileTo allow safe non-blocking access to individual fields outside of a lock.Yes (Assuming shared memory)Very fast

Identify process mode and check .NET process

1 Identify the mode of process:

1.1 Identify the mode of one process:
dumpbin /headers cv210.dll

1.2 Identify the modes of all processes on the current computer:

using System;
using System.Diagnostics;
using System.Runtime.InteropServices;

namespace WinProcessModeChecker {
    internal class Program {
        private static void Main() {
            if (Is64OsVersion()) {
                PrintProcessMode();
            } else {
                Console.WriteLine("Your OS version is not 64 bit!");
            }
                
            Console.ReadLine();
        }

        private static void PrintProcessMode() {
            foreach (var process in Process.GetProcesses()) {
                var isWow64Process = IsWow64Process(process);

                if (isWow64Process == null) {
                    Console.WriteLine(process.ProcessName + " is denied to access");
                } else if (isWow64Process == true) {
                    Console.WriteLine(process.ProcessName + " is 32-bit (wow mode)");
                } else {
                    Console.WriteLine(process.ProcessName + " is 64-bit");
                }
            }
        }

        /// <summary>
        /// Identify whether the OS version is 64 bit
        /// </summary>
        /// <returns></returns>
        private static bool Is64OsVersion() {
            if ((Environment.OSVersion.Version.Major > 5)
                || ((Environment.OSVersion.Version.Major == 5) && (Environment.OSVersion.Version.Minor >= 1))) {
                return true;
            }

            return false;
        }

        /// <summary>
        /// Identify whether the process is running in wow 64 mode 
        /// </summary>
        /// <remarks>
        /// WOW64 is the x86 emulator that allows 32-bit Windows-based applications to run seamlessly on 64-bit Windows
        /// </remarks>
        /// <param name="process"></param>
        /// <returns></returns>
        private static bool? IsWow64Process(Process process) {
            IntPtr processHandle;
            bool retVal;

            try {
                processHandle = Process.GetProcessById(process.Id).Handle;
            } catch {
                return null; // access is denied to the process
            }

            return NativeMethods.IsWow64Process(processHandle, out retVal) && retVal;
        }
    }

    internal static class NativeMethods {
        [DllImport("kernel32.dll", SetLastError = true, CallingConvention = CallingConvention.Winapi)]
        [return : MarshalAs(UnmanagedType.Bool)]
        internal static extern bool IsWow64Process([In] IntPtr process, [Out] out bool wow64Process);
    }
}

2 Chech .Net process:

2.1 The .NET application requires mscoree.dll So can use the below code:

  foreach (var process in Process.GetProcesses())
        {
            if (process.Modules.OfType<ProcessModule>().Any(m => m.ModuleName == "mscoree.dll"))
            {
                Console.WriteLine("{0} is a .NET process", process.ProcessName);
            }
        }
2.2 Process Explorer mark .NET applications by yellow color by default. 

Common schema clause

-- Add UDDT: AU_EdiDateOffsetHoursType
IF NOT EXISTS (SELECT 1 FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id 
   WHERE st.name = N'AU_EdiDateOffsetHoursType' AND ss.name = N'dbo')
   CREATE TYPE [dbo].[AU_EdiDateOffsetHoursType] FROM smallint NULL
GO

--Create Table: AU_co_contract_line_mst
IF OBJECT_ID(N'[dbo].[AU_co_contract_line_mst]', N'U') IS NULL
CREATE TABLE [dbo].[AU_co_contract_line_mst](
      [site_ref] [dbo].[SiteType] NOT NULL
         CONSTRAINT [DF_AU_co_contract_line_mst_site_ref] DEFAULT (RTRIM(CONVERT([nvarchar](8),context_info(),0)))
    , [contract_id] [dbo].[AU_ContractIDType] NOT NULL
    , [co_num] [dbo].[CoNumType] NOT NULL 
    , [cust_item] [dbo].[CustItemType] NULL
    , [CreatedBy] [dbo].[UsernameType] NOT NULL
        CONSTRAINT [DF_AU_co_contract_line_mst_CreatedBy]  DEFAULT (SUSER_SNAME())
    , [UpdatedBy] [dbo].[UsernameType] NOT NULL 
        CONSTRAINT [DF_AU_co_contract_line_mst_UpdatedBy]  DEFAULT (SUSER_SNAME())
    , [CreateDate] [dbo].[CurrentDateType] NOT NULL 
        CONSTRAINT [DF_AU_co_contract_line_mst_CreateDate]  DEFAULT (GETDATE())
    , [RecordDate] [dbo].[CurrentDateType] NOT NULL 
        CONSTRAINT [DF_AU_co_contract_line_mst_RecordDate]  DEFAULT (GETDATE())
    , [RowPointer] [dbo].[RowPointerType] NOT NULL 
        CONSTRAINT [DF_AU_co_contract_line_mst_RowPointer]  DEFAULT (NEWID())
    , [NoteExistsFlag] [dbo].[FlagNyType] NOT NULL 
        CONSTRAINT [DF_AU_co_contract_line_mst_NoteExistsFlag]  DEFAULT ((0)) 
        CONSTRAINT [CK_AU_co_contract_line_mst_NoteExistsFlag] CHECK ([NoteExistsFlag] IN (0,1))
    , [InWorkflow] [dbo].[FlagNyType] NOT NULL 
        CONSTRAINT [DF_AU_co_contract_line_mst_InWorkflow]  DEFAULT ((0))
        CONSTRAINT [CK_AU_co_contract_line_mst_InWorkflow] CHECK ([InWorkflow] IN (0,1))
    , CONSTRAINT [PK_AU_co_contract_line_mst] PRIMARY KEY CLUSTERED 
       (
           [contract_id] ASC,
           [co_num] ASC,
           [co_line] ASC,
           [site_ref]
       )
    , CONSTRAINT [IX_AU_co_contract_line_mst_RowPointer] UNIQUE NONCLUSTERED 
      ( 
         [RowPointer]
        ,[site_ref]
      )
   )   
GO

-- Add column with constraints
IF OBJECTPROPERTY(OBJECT_ID(N'[dbo].[so_parms]'), N'IsUserTable') = 1
   AND NOT EXISTS (SELECT 1 FROM [sys].[columns]
      WHERE [object_id] = OBJECT_ID(N'[dbo].[so_parms]')
      AND [name] = N'stat_code')
   ALTER TABLE [dbo].[so_parms] ADD
      [stat_code] [dbo].[FSStatCodeType] NOT NULL
         CONSTRAINT [DF_so_parms_stat_code]  DEFAULT (1)
         CONSTRAINT [CK_so_parms_stat_code] CHECK ([pick_list_printed] IN (0, 1))
         CONSTRAINT [FK_so_parms_stat_code] FOREIGN KEY ([stat_code]) 
            REFERENCES [dbo].[fs_stat_code]([stat_code]) NOT FOR REPLICATION
GO

IF COL_LENGTH('dbo.CRMMobileDeviceIdo', 'IsReadOnly')  IS NULL
   ALTER TABLE [dbo].[CRMMobileDeviceIdo] ADD [IsReadOnly] [dbo].[ListYesNoType] NOT NULL DEFAULT 0;
GO

-- Add FK between AU_co_contract_line_prc_mst and AU_co_contract_line_mst
IF OBJECTPROPERTY(OBJECT_ID(N'[dbo].[AU_co_contract_line_prc_mst]'), N'IsUserTable') = 1
   AND NOT EXISTS (SELECT 1 FROM [sys].[objects]
   WHERE [OBJECT_ID] = OBJECT_ID(N'FK_AU_co_contract_line_prc_mst_contract_id_co_num_co_line_site_ref'))
   ALTER TABLE [dbo].[AU_co_contract_line_prc_mst] WITH NOCHECK 
   ADD CONSTRAINT [FK_AU_co_contract_line_prc_mst_contract_id_co_num_co_line_site_ref]
   FOREIGN KEY (
           [contract_id],
           [co_num],
           [co_line],
           [site_ref]
   ) REFERENCES [dbo].[AU_co_contract_line_mst](
           [contract_id],
           [co_num],
           [co_line],
           [site_ref]
   ) NOT FOR REPLICATION
GO

-- Add Check Constraint
IF  EXISTS (SELECT 1 FROM sys.check_constraints WHERE object_id = OBJECT_ID(N'[dbo].[CK_arpmtd_type]') AND parent_object_id = OBJECT_ID(N'[dbo].[arpmtd]'))
ALTER TABLE [dbo].[arpmtd] DROP CONSTRAINT [CK_arpmtd_type]
GO
ALTER TABLE [dbo].[arpmtd] WITH CHECK ADD  CONSTRAINT [CK_arpmtd_type] CHECK  (([type]='S' OR ([type]='D' OR ([type]='A' OR ([type]='W' OR [type]='C')))))
GO
ALTER TABLE [dbo].[arpmtd] CHECK CONSTRAINT [CK_arpmtd_type]
GO

-- Remove existed FK
IF EXISTS (SELECT 1 
           FROM sys.foreign_keys 
           WHERE OBJECT_ID = OBJECT_ID(N'fs_parmsFk57')
           AND   parent_OBJECT_ID = OBJECT_ID(N'[dbo].[fs_parms]')
)
BEGIN
   ALTER TABLE [dbo].[fs_parms] DROP CONSTRAINT [fs_parmsFk57]
END
GO

-- Remove Existed column
IF EXISTS (SELECT 1 FROM  sys.columns c 
           INNER JOIN  sys.objects t ON (c.[OBJECT_ID] = t.[OBJECT_ID])
           WHERE t.[OBJECT_ID] = OBJECT_ID(N'[dbo].[fs_parms]')
           AND   c.[name] = N'parts_sro_template')
BEGIN 
   ALTER TABLE [dbo].[fs_parms] DROP COLUMN parts_sro_template
END
GO

-- Create Stored Procedure
SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

IF EXISTS (SELECT 1 FROM sysobjects WHERE id = object_id(N'MilestoneOperationCheckSp') 
AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
   DROP PROCEDURE MilestoneOperationCheckSp
GO

CREATE PROCEDURE MilestoneOperationCheckSp (  
   @PSroNum            FSSRONumType
 , @Infobar            Infobar      = NULL OUTPUT
) AS  
  
DECLARE 
   @Severity INT  

SET @Severity = 0

RETURN @Severity 

-- Create Function
SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

IF EXISTS (SELECT 1 FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[SarbCalSp]') AND OBJECTPROPERTY(id, N'IsScalarFunction') = 1)
   DROP FUNCTION [dbo].[SarbCalSp]
GO

CREATE FUNCTION dbo.SarbCalSp (
  @PFutureDate DateType
, @PNewDate    DateType
)
RETURNS SMALLINT
AS
BEGIN
   RETURN (month(@PNewDate) - month(@PFutureDate)) + (year(@PNewDate) - year(@PFutureDate)) * 12
END

-- Create Trigger
SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[UserNamesAppDel]') AND OBJECTPROPERTY(id, N'IsTrigger') = 1)
DROP TRIGGER [dbo].[UserNamesAppDel]
GO

CREATE TRIGGER dbo.UserNamesAppDel
ON UserNames
FOR DELETE
AS
-- Skip trigger operations as required.
IF dbo.SkipBaseTrigger() = 1
   RETURN
DECLARE sssFSUsernamesDelCrs CURSOR LOCAL STATIC
FOR SELECT 
  dd.RowPointer
, dd.username
FROM deleted AS dd

OPEN sssFSUsernamesDelCrs

WHILE @Severity = 0
BEGIN -- cursor loop
   FETCH sssFSUsernamesDelCrs INTO
     @RowPointer
   , @Username

   IF @@FETCH_STATUS = -1
      BREAK
END -- End of cursor loop

CLOSE sssFSUsernamesDelCrs
DEALLOCATE sssFSUsernamesDelCrs

IF @Severity = 0
BEGIN
  DELETE user_local
  FROM
    deleted dd
   ,user_local ul
  WHERE ul.UserId = dd.UserId

  SELECT @Severity = @@ERROR
END
/* return error result */
IF @Severity <> 0
BEGIN
    EXEC RaiseErrorSp @Infobar, @Severity, 3
 
    EXEC @Severity = RollbackTransactionSp
       @Severity
 
    IF @Severity != 0
    BEGIN
       ROLLBACK TRANSACTION
       RETURN
    END
END

Common Used Batch Commands

Create file folder:
md "E:\My documents\Newfolder1"

Search specific file:
dir d:\ e:\ /s /b | find "x.x"

Create an empty file:
cd. > a.txt
cd. Indicates that the current directory is changed to the current directory, that is, it is not changed; And this command has no output
> Indicates that the command output is written to a file. Followed by a.txt, it means to write to a.txt.
In this case, the command will not have output, so an empty file with no content is created.

copy nul a.txt
Nul represents an empty device. Conceptually, it is invisible and exists in each directory. It can be regarded as a special "file" with no content; Generally, the output can be written to nul to mask the output. For example, pause > nul, the execution effect of this command is to pause, and "please press any key to continue..." will not be displayed.
This example shows that an empty device is copied to a.txt, and an empty file without content is also created.

type nul > 1.txt
This example shows that the contents of an empty device are displayed and written to a.txt

fsutil file createnew a2.txt 1
An empty file was created using fsutil.

echo a 2 > a.txt
"2" indicates the handle of error output. In this case, there is no error output, so an empty file without content is created.
In fact, the default is to redirect handle 1, that is, the standard output handle. For example, CD. > a.txt is actually CD. 1 > a.txt.
Similarly, handles 3 to 9 can also be used. In this case, they are undefined handles and will not have output, such as echo a 3>a.txt

Create a non-empty file
echo a > a.txt
The most commonly used command is echo. This example means that the letter A and carriage return line feed are overwritten and output to a.txt (if the original content of a.txt is overwritten), if you add content, you can use >>. For example, echo b >> a.txt means that B and carriage return line feed are appended to the end of the file.

View file:
type "ApplicationDB\Stored Procedures\Rpt_CfgAttrSp.sp" 

Append data to existed file:
COPY filename+CON
TYPE CON>>filename
After input press key F6 or Ctrl+Z

Delete file:
rd /s /q %windir%\temp & md %windir%\temp
del /f /s /q %systemdrive%\*.tmp

Delete file whose name contains space:
for /r "C:\Test" %v in (*.txt) do del "%v"

Copy files:
copy d:\test.txt+d:\abc.txt d:\test\test.txt
type a.txt > b.txt
copy a.txt b.txt
fsutil file createnew d:\a.txt 1

Copy from another computer:
xcopy \\cnshdbqin1\resource D:\res /s /c

Copy from another computer with user and password:
net use \\10.86.26.167\fs1 P@ssword123 /user:shareuser
xcopy \\10.86.26.167\fs1\grampian.csv D:\res /s /c
net use \\10.86.26.167\fs1 /delete

Multi-threaded file copy:
robocopy d:\work e:\back /s /j /xf *.tmp *.bak

Open the program:
start d:\TheWorld\TheWorld.EXE "e:\My documents\I_have_a_page.htm"

Open website:
@echo off
path=%path%; C:\Program Files\Internet Explorer\iexplore.exe
start iexplore http://cnshvwmg902ap01/WSWebClient/WSWebForm.aspx

Open folder:
@echo off
start "" "\\cnshwfps2\Departments\R&D"

Receive the value from command line:
set /p a=
echo Your input is: %a%

Check local port:
netstat -aon | find "80"
tasklist | findstr "3096"

Search local string:
findstr /S /N "Option" C:\vss_root\ \(-name \*.txt -o -name \*.vb -o -name \*.sql \)

Change password of :
Remote Computer: Ctrl+Alt+End
Local Computer:  Ctrl+Alt+Del

Remote desktop connect command:
mstsc /v: USCOVWCS10DB /console

Minmun all windows except current:
win+Home

Shift window between different screens:
Press key WIN+SHIFT+LEFT | RIGHT

Run a program as an administrator
Press key CTRL+SHIFT and Click the exe file

Close the process of remote computer:
tasklist /S cnshdbqin2 /U infor\bqin /P Winter_01
 |FIND /i "taskmgr" && (echo OK || echo error) && taskkill /S cnshdbqin2 /U info
r\bqin /P Winter_01 /im taskmgr.exe

Wait for some time:
ping 1.1.1.1 -n 1 -w 30000
timeout /t 10

Show the control set:
rundll32.exe shell32.dll,Control_RunDLL

Fix IE:
regsvr32 Shdocvw.dll
regsvr32 Oleaut32.dll 
regsvr32 Actxprxy.dll 
regsvr32 Mshtml.dll 
regsvr32 Urlmon.dll 
regsvr32 browseui.dll 

Get file from UNC path with authentication

1 Use batch command 'net use'
net use \\10.86.26.167\fs1 P@ssword123 /user:shareuser
xcopy \\10.86.26.167\fs1\grampian.csv D:\res /s /c
net use \\10.86.26.167\fs1 /delete

Note: Also can use batch command in programing (VB.net)
    Dim application As New Diagnostics.ProcessStartInfo("cmd.exe") With
        {.RedirectStandardInput = True, .UseShellExecute = False, .CreateNoWindow = True}
    Dim process As New Diagnostics.Process
    process = process.Start(application)
    Dim command As String = "net use \\54.200.250.186\Test1 P@ssword123 /user:shareuser" _
         & vbCrLf & "exit"
    process.StandardInput.WriteLine(command)
    process.WaitForExit()
    process.Close()

2 Use NetworkCredential
NetworkCredential myCred = new NetworkCredential("shareuser", "P@ssword123");
            string url = @"\\10.86.26.167\fs1\grampian.csv";
            WebRequest myWebRequest = WebRequest.Create(url);
            CredentialCache theNetCache = new CredentialCache();
            theNetCache.Add(new Uri(url), "Basic", myCred);
            myWebRequest.Credentials = theNetCache;
            FileWebResponse response = (FileWebResponse)myWebRequest.GetResponse();
            Stream stream = response.GetResponseStream();
            StreamReader reader = new StreamReader(stream);
            string strLine = reader.ReadLine();
            while (strLine != null)
            {
                Console.WriteLine(strLine);
                strLine = reader.ReadLine();
            }

3 Use WNetUseConnection in Mpr.dll
3.1 Define a Help class PinvokeWindowsNetworking
namespace TestApplication
{
    using System;
    using System.Collections.Generic;
    using System.Runtime.InteropServices ;
    using System.Linq;
    using System.Text;

    /// <summary>
    /// TODO: Update summary.
    /// </summary>
    public class PinvokeWindowsNetworking
    {
        #region Consts
        const int RESOURCE_CONNECTED = 0x00000001;
        const int RESOURCE_GLOBALNET = 0x00000002;
        const int RESOURCE_REMEMBERED = 0x00000003;

        const int RESOURCETYPE_ANY = 0x00000000;
        const int RESOURCETYPE_DISK = 0x00000001;
        const int RESOURCETYPE_PRINT = 0x00000002;

        const int RESOURCEDISPLAYTYPE_GENERIC = 0x00000000;
        const int RESOURCEDISPLAYTYPE_DOMAIN = 0x00000001;
        const int RESOURCEDISPLAYTYPE_SERVER = 0x00000002;
        const int RESOURCEDISPLAYTYPE_SHARE = 0x00000003;
        const int RESOURCEDISPLAYTYPE_FILE = 0x00000004;
        const int RESOURCEDISPLAYTYPE_GROUP = 0x00000005;

        const int RESOURCEUSAGE_CONNECTABLE = 0x00000001;
        const int RESOURCEUSAGE_CONTAINER = 0x00000002;


        const int CONNECT_INTERACTIVE = 0x00000008;
        const int CONNECT_PROMPT = 0x00000010;
        const int CONNECT_REDIRECT = 0x00000080;
        const int CONNECT_UPDATE_PROFILE = 0x00000001;
        const int CONNECT_COMMANDLINE = 0x00000800;
        const int CONNECT_CMD_SAVECRED = 0x00001000;

        const int CONNECT_LOCALDRIVE = 0x00000100;
        #endregion

        #region Errors
        const int NO_ERROR = 0;

        const int ERROR_ACCESS_DENIED = 5;
        const int ERROR_ALREADY_ASSIGNED = 85;
        const int ERROR_BAD_DEVICE = 1200;
        const int ERROR_BAD_NET_NAME = 67;
        const int ERROR_BAD_PROVIDER = 1204;
        const int ERROR_CANCELLED = 1223;
        const int ERROR_EXTENDED_ERROR = 1208;
        const int ERROR_INVALID_ADDRESS = 487;
        const int ERROR_INVALID_PARAMETER = 87;
        const int ERROR_INVALID_PASSWORD = 1216;
        const int ERROR_MORE_DATA = 234;
        const int ERROR_NO_MORE_ITEMS = 259;
        const int ERROR_NO_NET_OR_BAD_PATH = 1203;
        const int ERROR_NO_NETWORK = 1222;

        const int ERROR_BAD_PROFILE = 1206;
        const int ERROR_CANNOT_OPEN_PROFILE = 1205;
        const int ERROR_DEVICE_IN_USE = 2404;
        const int ERROR_NOT_CONNECTED = 2250;
        const int ERROR_OPEN_FILES = 2401;

        private struct ErrorClass
        {
            public int num;
            public string message;
            public ErrorClass(int num, string message)
            {
                this.num = num;
                this.message = message;
            }
        }


        // Created with excel formula:
        // ="new ErrorClass("&A1&", """&PROPER(SUBSTITUTE(MID(A1,7,LEN(A1)-6), "_", " "))&"""), "
        private static ErrorClass[] ERROR_LIST = new ErrorClass[] {
new ErrorClass(ERROR_ACCESS_DENIED, "Error: Access Denied"), 
new ErrorClass(ERROR_ALREADY_ASSIGNED, "Error: Already Assigned"), 
new ErrorClass(ERROR_BAD_DEVICE, "Error: Bad Device"), 
new ErrorClass(ERROR_BAD_NET_NAME, "Error: Bad Net Name"), 
new ErrorClass(ERROR_BAD_PROVIDER, "Error: Bad Provider"), 
new ErrorClass(ERROR_CANCELLED, "Error: Cancelled"), 
new ErrorClass(ERROR_EXTENDED_ERROR, "Error: Extended Error"), 
new ErrorClass(ERROR_INVALID_ADDRESS, "Error: Invalid Address"), 
new ErrorClass(ERROR_INVALID_PARAMETER, "Error: Invalid Parameter"), 
new ErrorClass(ERROR_INVALID_PASSWORD, "Error: Invalid Password"), 
new ErrorClass(ERROR_MORE_DATA, "Error: More Data"), 
new ErrorClass(ERROR_NO_MORE_ITEMS, "Error: No More Items"), 
new ErrorClass(ERROR_NO_NET_OR_BAD_PATH, "Error: No Net Or Bad Path"), 
new ErrorClass(ERROR_NO_NETWORK, "Error: No Network"), 
new ErrorClass(ERROR_BAD_PROFILE, "Error: Bad Profile"), 
new ErrorClass(ERROR_CANNOT_OPEN_PROFILE, "Error: Cannot Open Profile"), 
new ErrorClass(ERROR_DEVICE_IN_USE, "Error: Device In Use"), 
new ErrorClass(ERROR_EXTENDED_ERROR, "Error: Extended Error"), 
new ErrorClass(ERROR_NOT_CONNECTED, "Error: Not Connected"), 
new ErrorClass(ERROR_OPEN_FILES, "Error: Open Files"), 
};

        private static string getErrorForNumber(int errNum)
        {
            foreach (ErrorClass er in ERROR_LIST)
            {
                if (er.num == errNum) return er.message;
            }
            return "Error: Unknown, " + errNum;
        }
        #endregion

        [DllImport("Mpr.dll")]
        private static extern int WNetUseConnection(
            IntPtr hwndOwner,
            NETRESOURCE lpNetResource,
            string lpPassword,
            string lpUserID,
            int dwFlags,
            string lpAccessName,
            string lpBufferSize,
            string lpResult
            );

        [DllImport("Mpr.dll")]
        private static extern int WNetCancelConnection2(
            string lpName,
            int dwFlags,
            bool fForce
            );

        [StructLayout(LayoutKind.Sequential)]
        private class NETRESOURCE
        {
            public int dwScope = 0;
            public int dwType = 0;
            public int dwDisplayType = 0;
            public int dwUsage = 0;
            public string lpLocalName = "";
            public string lpRemoteName = "";
            public string lpComment = "";
            public string lpProvider = "";
        }


        public static string connectToRemote(string remoteUNC, string username, string password)
        {
            return connectToRemote(remoteUNC, username, password, false);
        }

        public static string connectToRemote(string remoteUNC, string username, string password, bool promptUser)
        {
            NETRESOURCE nr = new NETRESOURCE();
            nr.dwType = RESOURCETYPE_DISK;
            nr.lpRemoteName = remoteUNC;
            // nr.lpLocalName = "F:";

            int ret;
            if (promptUser)
                ret = WNetUseConnection(IntPtr.Zero, nr, "", "", CONNECT_INTERACTIVE | CONNECT_PROMPT, null, null, null);
            else
                ret = WNetUseConnection(IntPtr.Zero, nr, password, username, 0, null, null, null);

            if (ret == NO_ERROR) return null;
            return getErrorForNumber(ret);
        }

        public static string disconnectRemote(string remoteUNC)
        {
            int ret = WNetCancelConnection2(remoteUNC, CONNECT_UPDATE_PROFILE, false);
            if (ret == NO_ERROR) return null;
            return getErrorForNumber(ret);
        }
    }
}

3.2 Call above class PinvokeWindowsNetworking
            string r = PinvokeWindowsNetworking.connectToRemote(@"\\10.86.26.167\fs1", @"shareuser", @"P@ssword123");
            Console.WriteLine(r);

            File.Copy(@"\\10.86.26.167\fs1\grampian.csv", @"D:\res\grampian.csv");