Clipper On Line • Ver Tópico - Mapear Drive de Rede perdido

Mapear Drive de Rede perdido

Aqui você poderá oferecer suas Contribuições, Dicas e Tutoriais (Texto ou Vídeo) que sejam de interesse de todos.

Moderador: Moderadores

 

Mapear Drive de Rede perdido

Mensagempor asimoes » 23 Abr 2016 11:18

Pessoal,

Tenho um cliente onde uma máquina com windows 7 32 por algum motivo não identificado perde a conexão com drive de rede de uma pasta compartilhada no servidor.

Fiz duas soluções que resolveram o problema, desde que o servidor ou máquina que compartilha a pasta não esteja desligada ou apresente qualquer outro problema, tipo compartilhamento desfeito.

Supondo que o drive de rede seja o F: é a pasta compartilhada, demonstrando a minha situação real:

cIpAddServer := Hwg_GetIni( 'CONFIGURACAO', 'Addres' ,'', hb_DirBase()+"CONFIG"+hb_PS()+"CONFIG.INI" )

Solução 1:
IF !hb_DirExists("F:") // Testa se o diretório não existe:
   NetRedir( "f:", "\\&cIpAddServer.\Sistema ASAPREV" ) //tenta mapear
   lDrive:=hb_DirExists("F:")
ENDIF

Solução 2:
IF !hb_DirExists("F:") // Testa se o diretório não existe:
   Execute("net", "use f: \\&cIpAddServer.\Sistema ASAPREV /persistent:yes") //tenta mapear
   lDrive:=hb_DirExists("F:")
ENDIF

FUNCTION Execute(cProgram, cParameter, lEspera)
LOCAL oShell, lOk := .T., nStyle
   lEspera := hb_DefaultValue(lEspera, .T.)
   TRY
      oShell := Win_OleCreateObject( "WScript.Shell" )
   CATCH
      TRY
         oShell := Win_OleCreateObject( "WScript.Shell" )
      CATCH
         lOk := .F.
      END
   END
   IF lOk
      TRY
         /*
         intWindowStyle
         Description
         0  Hides the window and activates another window.
         1  Activates and displays a window. If the window is minimized or maximized, the system restores it to its original size and position. An application should specify this flag when displaying the window for the first time.
         2  Activates the window and displays it as a minimized window.
         3  Activates the window and displays it as a maximized window.
         4  Displays a window in its most recent size and position. The active window remains active.
         5  Activates the window and displays it in its current size and position.
         6  Minimizes the specified window and activates the next top-level window in the Z order.
         7  Displays the window as a minimized window. The active window remains active.
         8  Displays the window in its current state. The active window remains active.
         9  Activates and displays the window. If the window is minimized or maximized, the system restores it to its original size and position. An application should specify this flag when restoring a minimized window.
         10 Sets the show-state based on the state of the program that started the application.
         */
         nStyle := 0
         oShell:Run(cProgram +" "+cParameter, nStyle, lEspera)
      CATCH
         hwg_MsgStop("Erro executando "+cProgram, "Erro")
         lOk := .F.
      END
      oShell := Nil
   ENDIF
RETURN lOk
►Harbour 3.x | Minigui xx-x | HwGui◄
Pense nas possibilidades abstraia as dificuldades.
Não corrigir nossas falhas é o mesmo que cometer novos erros.
A imaginação é mais importante que o conhecimento. (Albert Einstein)
Avatar de usuário

asimoes
Colaborador

Colaborador
 
Mensagens: 4919
Data de registro: 26 Abr 2007 16:48
Cidade/Estado: RIO DE JANEIRO-RJ
Curtiu: 341 vezes
Mens.Curtidas: 258 vezes

Mapear Drive de Rede perdido

Mensagempor asimoes » 26 Abr 2016 15:45

Uma pequena correção:

Se não informar o /yes a janela oculta não mostra que o windows espera uma confirmação sim ou não ou (yes ou no) então acrescentar /yes ao comando.
Execute("net", "use f: \\&cIpAddServer.\Sistema ASAPREV /persistent:yes /yes")
►Harbour 3.x | Minigui xx-x | HwGui◄
Pense nas possibilidades abstraia as dificuldades.
Não corrigir nossas falhas é o mesmo que cometer novos erros.
A imaginação é mais importante que o conhecimento. (Albert Einstein)
Avatar de usuário

asimoes
Colaborador

Colaborador
 
Mensagens: 4919
Data de registro: 26 Abr 2007 16:48
Cidade/Estado: RIO DE JANEIRO-RJ
Curtiu: 341 vezes
Mens.Curtidas: 258 vezes

Mapear Drive de Rede perdido

Mensagempor janio » 26 Abr 2016 16:19

aSimoes,

Vc fez duas soluções! Qual vc adotou?

Janio
fui...
e-mail:janioaguiar@yahoo.com.br
msn: janio_aguiar@hotmail.com
xHarbour1.2.1/Harbour3.2 + wvg + hwgui + Mediator + MySql
Avatar de usuário

janio
Colaborador

Colaborador
 
Mensagens: 1835
Data de registro: 06 Jul 2004 07:43
Cidade/Estado: UBAJARA - CE
Curtiu: 8 vezes
Mens.Curtidas: 68 vezes

Mapear Drive de Rede perdido

Mensagempor asimoes » 26 Abr 2016 16:44

Janio,

Eu tento primeiro netredir se falhar, tento o net use

Eu sei que o netredir retorna .T. (sucesso) .F. (falha) mas eu prefiro testar o drive logo em seguida.

Eu faço assim:

IF !hb_DirExists("F:")
   NetRedir( "f:", "\\&cIpAddServer.\Sistema ASAPREV" )
   IF !hb_DirExists("F:") //Última tentativa, se o windows não estiver de sacanagem!
      Execute("net", "use f: \\&cIpAddServer.\Sistema ASAPREV /persistent:yes /yes")
      IF  !hb_DirExists("F:")
          hwg_MsgStop("Falha acessando a rede, entre em contato com o helpdesk", "Erro")
          RETURN .F.
      ENDIF
   ENDIF
ENDIF
►Harbour 3.x | Minigui xx-x | HwGui◄
Pense nas possibilidades abstraia as dificuldades.
Não corrigir nossas falhas é o mesmo que cometer novos erros.
A imaginação é mais importante que o conhecimento. (Albert Einstein)
Avatar de usuário

asimoes
Colaborador

Colaborador
 
Mensagens: 4919
Data de registro: 26 Abr 2007 16:48
Cidade/Estado: RIO DE JANEIRO-RJ
Curtiu: 341 vezes
Mens.Curtidas: 258 vezes

Mapear Drive de Rede perdido

Mensagempor JoséQuintas » 26 Abr 2016 17:07

O mapeamento no Windows é um detalhezinho chato.
Precisa mapear, indicar pra lembrar da senha, e precisa digitar a senha quando cria o mapeamento.

Se a senha já estiver digitada, ao fazer o mapeamento não pede senha, e ela não fica salva, e depois o mapeamento é perdido.
Se tiver a opção: conectar como outro usuário, talvez ajude.

Aí fixa o problema no próprio Windows.
José M. C. Quintas
Harbour 3.2, mingw, gtwvg, multithread, dbfcdx, ADO+MySql, PNotepad
"The world is full of kings and queens, who blind our eyes and steal our dreams Its Heaven and Hell"

https://github.com/JoseQuintas/
Avatar de usuário

JoséQuintas
Membro Master

Membro Master
 
Mensagens: 18013
Data de registro: 26 Fev 2007 11:59
Cidade/Estado: São Paulo-SP
Curtiu: 15 vezes
Mens.Curtidas: 1206 vezes

Mapear Drive de Rede perdido

Mensagempor asimoes » 26 Abr 2016 17:08

►Harbour 3.x | Minigui xx-x | HwGui◄
Pense nas possibilidades abstraia as dificuldades.
Não corrigir nossas falhas é o mesmo que cometer novos erros.
A imaginação é mais importante que o conhecimento. (Albert Einstein)
Avatar de usuário

asimoes
Colaborador

Colaborador
 
Mensagens: 4919
Data de registro: 26 Abr 2007 16:48
Cidade/Estado: RIO DE JANEIRO-RJ
Curtiu: 341 vezes
Mens.Curtidas: 258 vezes

Mapear Drive de Rede perdido

Mensagempor rochinha » 27 Abr 2016 12:51

Amiguinhos,

Eu também enfrentei alguns probleminhas com o Windows tempos atrás relacionados a perda do mapeamento. Estas perdas de mapeamento se devem a dois fatores, o primeiro é que o Windows ao detectar a inexistência do vinculo o elimina automaticamente para não deixar a máquina lenta e a segunda é que estas informações ficam salvas no registro e se a máquina reinicia por erro, bluescreen ou queda de força o Windows reinicia rodando com o snapshot do registro num momento anterior ao da alteração.

Em meu sistema eu me habituei a deixá-lo ou no servidor ou em todas as máquinas.

- Quando no servidor o único problema é a perda do atalho que abre o sistema que some quando o mapeamento desaparece e o usuário inadvertidamente escolhe SIM para a pergunta EXCLUIR ATALHO sem olhá-la.
- Quando no terminal eu apenas aponto o mapeamento no servidor onde estão os dados centralizando o mesmo e descentralizando o sistema. Neste caso checo o mapeamento através de:
   if "\\" $ cPath
      cUNCPath  := ""
      cPathRede := VerifyINI( "REDE", "Caminho", "", cPath+"nfw.ini" ) // Salva o caminho em .INI
      if empty( cPathRede )
         if MsgYesNo( "O caminho de rede "+cpath+" sera fixado neste momento."+CRLF+;
                      "Escolha uma letra e passe a executar o sistema atraves dela."+CRLF+CRLF+;
                      "O sistema sera fechado. Acesse atraves da letra criada." )
            WNetConnect()
         endif
         cUNCPath := GetDrvMapLetter( cPath ) // ? GetDrvMapLetter( "\\Iasminmrocha-pc\C" )
      endif
      // ? cPath, GetDrvMapLetter( cPath )
      lChDir( cUNCPath )
      if empty( cUNCPath )
         MsgInfo( "Mapeamento nao concretizado. Fechando aplicativo." )
         quit
      endif
      // ? "letra: "+cUNCPath,curdir(),curdrive()
   endif


Como os problemas com perda de mapeamento foram sanados, parei de usar a critica acima. Mas de-repente precisei usá-la e notei que algumas funções não estavam me retornando o que eu queria, portanto no tópico http://www.pctoledo.com.br/forum/viewtopic.php?f=4&t=17006&start=0&hilit=net+use chegamos a uma conclusão criando algumas funções.

Fica a dica.
OPS! LINK QUEBRADO? Veja ESTE TOPICO antes e caso não encontre ENVIE seu email com link do tópico para fivolution@hotmail.com. Agradecido.

@braços : ? )

A justiça divina tarda mas não falha, enquanto que a justiça dos homens falha porque tarda.
Avatar de usuário

rochinha
Membro Master

Membro Master
 
Mensagens: 4538
Data de registro: 18 Ago 2003 20:43
Cidade/Estado: São Paulo - Brasil
Curtiu: 800 vezes
Mens.Curtidas: 242 vezes

Mapear Drive de Rede perdido

Mensagempor asimoes » 28 Abr 2016 18:40

Rochinha fiz uma pequena modificação na sua função:

Veja que até o objeto WScript.Network pode mapear uma uma unidade de rede:
com objNetwork:MapNetworkDrive("h:", strLocalDrive)

FUNCTION GetDrvMapLetter( strLocalDrive ) // UNC path
LOCAL aGetDrvMapLetter := {}
LOCAL objNetwork
LOCAL objDrives
LOCAL i
    objNetwork := Win_OleCreateObject("WScript.Network")
    Try
       objNetwork:MapNetworkDrive("h:", strLocalDrive)
    End
    objDrives   := objNetwork:EnumNetworkDrives()
    IF objDrives:Count > 0
        FOR I:=0 TO objDrives:Count -1 STEP 2
            aAdd( aGetDrvMapLetter, {objDrives:Item(i), objDrives:Item(i+1)} )
        NEXT 
    ENDIF
RETURN aGetDrvMapLetter
►Harbour 3.x | Minigui xx-x | HwGui◄
Pense nas possibilidades abstraia as dificuldades.
Não corrigir nossas falhas é o mesmo que cometer novos erros.
A imaginação é mais importante que o conhecimento. (Albert Einstein)
Avatar de usuário

asimoes
Colaborador

Colaborador
 
Mensagens: 4919
Data de registro: 26 Abr 2007 16:48
Cidade/Estado: RIO DE JANEIRO-RJ
Curtiu: 341 vezes
Mens.Curtidas: 258 vezes

Mapear Drive de Rede perdido

Mensagempor asimoes » 28 Abr 2016 19:08

Olá Pessoal,

2 funções legais:

MapNetworkDrive => para mapear uma unidade de rede
MapNetworkDrive("F:", "\\servidor-pc\boletos")
FUNCTION MapNetworkDrive( cDrive, strLocalDrive ) 
LOCAL objNetwork, lOk:=.T.

    hb_Default(@cDrive, "F:")
   
    objNetwork := Win_OleCreateObject("WScript.Network")

    Try
       objNetwork:MapNetworkDrive(cDrive, strLocalDrive)
    Catch
       lOk:=.F.
    End
 
RETURN lOk

RemoveNetworkDrive => para remover uma unidade mapeada de rede
RemoveNetworkDrive("F:")
FUNCTION RemoveNetworkDrive( cDrive ) 
LOCAL objNetwork, lOk:=.T.

    hb_Default(@cDrive, "F:")
   
    objNetwork := Win_OleCreateObject("WScript.Network")

    Try
       objNetwork:RemoveNetworkDrive(cDrive, .T., .T.)
    Catch
       lOk:=.F.
    End

RETURN lOk
►Harbour 3.x | Minigui xx-x | HwGui◄
Pense nas possibilidades abstraia as dificuldades.
Não corrigir nossas falhas é o mesmo que cometer novos erros.
A imaginação é mais importante que o conhecimento. (Albert Einstein)
Avatar de usuário

asimoes
Colaborador

Colaborador
 
Mensagens: 4919
Data de registro: 26 Abr 2007 16:48
Cidade/Estado: RIO DE JANEIRO-RJ
Curtiu: 341 vezes
Mens.Curtidas: 258 vezes

Mapear Drive de Rede perdido

Mensagempor rubens » 07 Fev 2017 22:16

Rochinha,

Essa função Verifyini() é sua?

tem como postar o código dela?

Obrigado
Rubens
P.S. Já encontrei.. obrigado...
"Eu e minha casa servimos ao Senhor e você ???"
Avatar de usuário

rubens
Colaborador

Colaborador
 
Mensagens: 1518
Data de registro: 16 Ago 2003 09:05
Cidade/Estado: Nova Xavantina - MT
Curtiu: 77 vezes
Mens.Curtidas: 104 vezes

Mapear Drive de Rede perdido

Mensagempor rochinha » 08 Fev 2017 00:59

Amiguinhos,

rubens
Ás vezes andando pelas ruas da cidade esbarro em crianças com a minha cara, mas não tenho certeza se são meus.

bom a função usa uma classe do Fivewin TIni mas creio que os amigos já postaram aqui outras maneiras de ler e graar estes arquivos.

Mas só para você entender:
function VerifyINI( _section_, _entry_, _var_, _inifile_, _grava_ )
   oIni := TIni():New( _inifile_ )
   if _grava_ = .t.
      oIni:Set( _section_, _entry_, _var_ )
   endif
   return oIni:Get( _section_, _entry_, _var_, _var_ )


Voce pode fazer uso da INIFILES.PRG encontrada no MRBoleto e HarbourBoleto

Classe TIni.prg
#include "FiveWin.ch"
#include "DLL.ch"

//----------------------------------------------------------------------------//

CLASS TIni

   DATA   cIniFile, lAutoSet

   METHOD New( cIniFile ) CONSTRUCTOR

   METHOD Get( cSection, cEntry, uDefault, uVar )

   METHOD Set( cSection, cEntry, uValue )

   METHOD Sections()

   METHOD DelSection( cSection ) INLINE DelIniSection( cSection, ::cIniFile )

   METHOD DelEntry( cSection, cEntry ) INLINE ;
                       DelIniEntry( cSection, cEntry, ::cIniFile )

ENDCLASS

//----------------------------------------------------------------------------//

METHOD New( cIniFile ) CLASS TIni

   DEFAULT cIniFile := ""

   if ! Empty( cIniFile ) .and. At( ".", cIniFile ) == 0
      cIniFile += ".ini"
   endif

   ::cIniFile = cIniFile
   ::lAutoSet = .t.

return Self

//----------------------------------------------------------------------------//

METHOD Get( cSection, cEntry, uDefault, uVar ) CLASS TIni

   local cType := ValType( If( uDefault != nil, uDefault, uVar ) )

   if Empty( ::cIniFile )
      if cType == "N"
         uVar = GetProfInt( cSection, cEntry, uDefault )
      else
         uVar = GetProfString( cSection, cEntry, cValToChar( uDefault ) )
      endif
   else
      if cType == "N"
         uVar = GetPvProfInt( cSection, cEntry, uDefault, ::cIniFile )
      else
         uVar = GetPvProfString( cSection, cEntry, cValToChar( uDefault ),;
                                 ::cIniFile )
      endif
   endif

   do case
      case cType == "D"
           uVar = CToD( uVar )

      case cType == "L"
           uVar = ( Upper( uVar ) == ".T." )
   endcase

   if uVar == uDefault .and. ::lAutoSet
      ::Set( cSection, cEntry, uDefault)
   endif

return uVar

//----------------------------------------------------------------------------//

METHOD Set( cSection, cEntry, uValue ) CLASS TIni

   if Empty( ::cIniFile )
      WriteProfString( cSection, cEntry, cValToChar( uValue ) )
   else
      WritePProString( cSection, cEntry, cValToChar( uValue ), ::cIniFile )
   endif

return nil

//----------------------------------------------------------------------------//

METHOD Sections() CLASS TIni

   local cBuffer := Space( 4096 ), p, aSec:={}

   // cBuffer := Left( cBuffer, GetPvPrfSe( @cBuffer, 4095, ::cIniFile ) )

   p = GetPvPrfSe( @cBuffer, 4095, ::cIniFile )
   cBuffer = Left( cBuffer, p )

   while ( p := At( Chr( 0 ), cBuffer ) ) > 1
      AAdd( aSec, Left( cBuffer, p - 1 ) )
      cBuffer = SubStr( cBuffer, p + 1 )
   enddo

return aSec

//----------------------------------------------------------------------------//

DLL32 FUNCTION GetPvPrfSe(cBuffer AS LPSTR, nSize AS DWORD, cIni AS LPSTR) AS DWORD PASCAL ;
               FROM "GetPrivateProfileSectionNamesA" LIB "Kernel32.dll"


DLL.CH
// Copyright FiveTech 1993-03

#ifndef _DLL_CH
#define _DLL_CH

#ifndef _C_TYPES
   #define _C_TYPES
   #define VOID     0
   #define BYTE     1
   #define CHAR     2
   #define WORD     3

#ifdef __CLIPPER__
   #define _INT     4         // conflicts with Clipper Int()
#else
   #define _INT     7
#endif

   #define BOOL     5
   #define HDC      6
   #define LONG     7
   #define STRING   8
   #define LPSTR    9
   #define PTR     10
   #define _DOUBLE 11         // conflicts with BORDER DOUBLE
   #define DWORD   12
#endif

#translate NOREF([@]<x>) => <x>

#ifndef __HARBOUR__
  #ifndef __XPP__
     #ifndef __CLIPPER__
        #ifndef __C3__
           #define __CLIPPER__
        #endif
     #endif
  #endif
#endif

#ifndef __CLIPPER__
   #translate DLL32 => DLL
#endif

//----------------------------------------------------------------------------//

#xcommand DLL [<static:STATIC>] FUNCTION <FuncName>( [ <uParam1> AS <type1> ] ;
                                                     [, <uParamN> AS <typeN> ] ) ;
             AS <return> [<pascal:PASCAL>] [ FROM <SymName> ] LIB <*DllName*> ;
       => ;
          [<static>] function <FuncName>( [NOREF(<uParam1>)] [,NOREF(<uParamN>)] ) ;;
             local hDLL := If( ValType( <DllName> ) == "N", <DllName>, LoadLibrary( <(DllName)> ) ) ;;
             local uResult ;;
             local cFarProc ;;
             if Abs( hDLL ) > 32 ;;
                cFarProc = GetProcAddress( hDLL,;
                If( [ Empty( <SymName> ) == ] .t., <(FuncName)>, <SymName> ),;
                [<.pascal.>], <return> [,<type1>] [,<typeN>] ) ;;
                uResult = CallDLL( cFarProc [,<uParam1>] [,<uParamN>] ) ;;
                If( ValType( <DllName> ) == "N",, FreeLibrary( hDLL ) ) ;;
             else ;;
                MsgAlert( "Error code: " + LTrim( Str( hDLL ) ) + " loading " + ;
                If( ValType( <DllName> ) == "C", <DllName>, Str( <DllName> ) ) ) ;;
             end ;;
          return uResult

//----------------------------------------------------------------------------//

#xcommand DLL32 [<static:STATIC>] FUNCTION <FuncName>( [ <uParam1> AS <type1> ] ;
                                                      [, <uParamN> AS <typeN> ] ) ;
             AS <return> [<pascal:PASCAL>] [ FROM <SymName> ] LIB <*DllName*> ;
       => ;
          [<static>] function <FuncName>( [NOREF(<uParam1>)] [,NOREF(<uParamN>)] ) ;;
             local hDLL := If( ValType( <DllName> ) == "N", <DllName>, LoadLib32( <(DllName)> ) ) ;;
             local uResult ;;
             local cFarProc ;;
             if Abs( hDLL ) <= 32 ;;
                MsgAlert( "Error code: " + LTrim( Str( hDLL ) ) + " loading " + <DllName> ) ;;
             else ;;
                cFarProc = GetProc32( hDLL,;
                If( [ Empty( <SymName> ) == ] .t., <(FuncName)>, <SymName> ),;
                [<.pascal.>], <return> [,<type1>] [,<typeN>] ) ;;
                uResult = CallDLL32( cFarProc [,<uParam1>] [,<uParamN>] ) ;;
                If( ValType( <DllName> ) == "N",, FreeLib32( hDLL ) ) ;;
             end ;;
          return uResult

#endif

//----------------------------------------------------------------------------//


Os códigos acima fazem parte do pacote da Fivewin 6.22 Free.
OPS! LINK QUEBRADO? Veja ESTE TOPICO antes e caso não encontre ENVIE seu email com link do tópico para fivolution@hotmail.com. Agradecido.

@braços : ? )

A justiça divina tarda mas não falha, enquanto que a justiça dos homens falha porque tarda.
Avatar de usuário

rochinha
Membro Master

Membro Master
 
Mensagens: 4538
Data de registro: 18 Ago 2003 20:43
Cidade/Estado: São Paulo - Brasil
Curtiu: 800 vezes
Mens.Curtidas: 242 vezes

Mapear Drive de Rede perdido

Mensagempor rubens » 08 Fev 2017 07:03

Bom dia...

Então Rochinha, cheguei no código do VerifyIni() aqui mesmo no Fórum...
Mas esbarrou na questão Fivewin...
Daí pesquisei e achei um vídeo do Daniel Crocciari ensinando ler e salvar no ini, na minigui... bem facinho...

o código ficou assim:

cCaminho := LerIni( 'REDE','Caminho','PdvData.Ini')
...

Function LerINI( cSection, cEntry, cFileIni )
Local cVar := ''
Begin Ini File cFileIni
   Get cVar Section cSection Entry cEntry
End Ini
* Para Salvar
* Set Section cSection Entry cEntry to cVar
Return cVar


Já no harbour não funcionou... deu erro no Begin ini, que acho ser da Minigui... não tive tempo de ir atrás ainda... embora... com a migração para a Minigui, não vai me fazer falta no harbour nesse momento.

Rubens
"Eu e minha casa servimos ao Senhor e você ???"
Avatar de usuário

rubens
Colaborador

Colaborador
 
Mensagens: 1518
Data de registro: 16 Ago 2003 09:05
Cidade/Estado: Nova Xavantina - MT
Curtiu: 77 vezes
Mens.Curtidas: 104 vezes

Mapear Drive de Rede perdido

Mensagempor rochinha » 08 Fev 2017 15:03

Amiguinhos,

rubens
Deve estar faltando alguma procedure, classe ou função.

Veja a INIFILES.PRG contida no HarbourBoleto
//
// $Id: inifiles.prg,v 1.1 2007/08/02 00:51:33 masturm Exp $
//
#define CRLF (Chr(13) + Chr(10))

function TIniFile()
   static oClass

   if oClass == nil
      oClass := HBClass():New( 'TINIFILE' ) // starts a new class definition

      oClass:AddData( 'FileName' )           // define this class objects datas
      oClass:AddData( 'Contents' )

      oClass:AddMethod( 'New',  @New() )  // define this class objects methods
      oClass:AddMethod( 'ReadString', @ReadString() )
      oClass:AddMethod( 'WriteString', @WriteString() )
      oClass:AddMethod( 'ReadNumber', @ReadNumber() )
      oClass:AddMethod( 'WriteNumber', @WriteNumber() )
      oClass:AddMethod( 'ReadDate', @ReadDate() )
      oClass:AddMethod( 'WriteDate', @WriteDate() )
      oClass:AddMethod( 'ReadBool', @ReadBool() )
      oClass:AddMethod( 'WriteBool', @WriteBool() )
      oClass:AddMethod( 'ReadSection', @ReadSection() )
      oClass:AddMethod( 'ReadSections', @ReadSections() )
      oClass:AddMethod( 'DeleteKey', @DeleteKey() )
      oClass:AddMethod( 'EraseSection', @EraseSection() )
      oClass:AddMethod( 'UpdateFile', @UpdateFile() )

      oClass:Create()                     // builds this class
   endif
return oClass:Instance()                  // builds an object of this class

static function New(cFileName)
   local Self := QSelf()
   local Done, hFile, cFile, cLine, cIdent, nPos
   local CurrArray

   if empty(cFileName)
      // raise an error?
      outerr('No filename passed to TIniFile():New()')
      return nil

   else
      ::FileName := cFilename
      ::Contents := {}
      CurrArray := ::Contents

      if File(cFileName)
         hFile := fopen(cFilename, 0)

      else
         hFile := fcreate(cFilename)
      endif

      cLine := ''
      Done := .f.
      while !Done
         cFile := space(256)
         Done := (fread(hFile, @cFile, 256) <= 0)

         cFile := strtran(cFile, chr(10), '') // so we can just search for CHR(13)

         // prepend last read
         cFile := cLine + cFile
         while !empty(cFile)
            if (nPos := at(chr(13), cFile)) > 0
               cLine := left(cFile, nPos - 1)
               cFile := substr(cFile, nPos + 1)

               if !empty(cLine)
                  if Left(cLine, 1) == '[' // new section
                     if (nPos := At(']', cLine)) > 1
                        cLine := substr(cLine, 2, nPos - 2);

                     else
                        cLine := substr(cLine, 2)
                     endif

                     AAdd(::Contents, { cLine, { /* this will be CurrArray */ } } )
                     CurrArray := ::Contents[Len(::Contents)][2]

                  elseif Left(cLine, 1) == ';' // preserve comments
                     AAdd( CurrArray, { NIL, cLine } )

                  else
                     if (nPos := At('=', cLine)) > 0
                        cIdent := Left(cLine, nPos - 1)
                        cLine := SubStr(cLine, nPos + 1)

                        AAdd( CurrArray, { cIdent, cLine } )

                     else
                        AAdd( CurrArray, { cLine, '' } )
                     endif
                  endif
                  cLine := '' // to stop prepend later on
               endif

            else
               cLine := cFile
               cFile := ''
            endif
         end
      end

      fclose(hFile)
   endif
return Self

static function ReadString(cSection, cIdent, cDefault)
   local Self := QSelf()
   local cResult := cDefault
   local i, j, cFind

   if Empty(cSection)
      cFind := lower(cIdent)
      j := AScan( ::Contents, {|x| valtype(x[1]) == 'C' .and. lower(x[1]) == cFind .and. ValType(x[2]) == 'C'} )

      if j > 0
          cResult := ::Contents[j][2]
      endif

   else
      cFind := lower(cSection)
      i := AScan( ::Contents, {|x| valtype(x[1]) == 'C' .and. lower(x[1]) == cFind} )

      if i > 0
         cFind := lower(cIdent)
         j := AScan( ::Contents[i][2], {|x| valtype(x[1]) == 'C' .and. lower(x[1]) == cFind} )

         if j > 0
            cResult := ::Contents[i][2][j][2]
         endif
      endif
   endif
return cResult

static procedure WriteString(cSection, cIdent, cString)
   local Self := QSelf()
   local i, j, cFind

   if Empty(cIdent)
      outerr('Must specify an identifier')

   elseif Empty(cSection)
      cFind := lower(cIdent)
      j := AScan( ::Contents, {|x| valtype(x[1]) == 'C' .and. lower(x[1]) == cFind .and. ValType(x[2]) == 'C'} )

      if j > 0
         ::Contents[j][2] := cString

      else
         AAdd(::Contents, nil)
         AIns(::Contents, 1)
         ::Contents[1] := {cIdent, cString}
      endif

   else
      cFind := lower(cSection)
      if (i := AScan( ::Contents, {|x| valtype(x[1]) == 'C' .and. lower(x[1]) == cFind .and. ValType(x[2]) == 'A'})) > 0
         cFind := lower(cIdent)
         j := AScan( ::Contents[i][2], {|x| valtype(x[1]) == 'C' .and. lower(x[1]) == cFind} )

         if j > 0
            ::Contents[i][2][j][2] := cString

         else
            AAdd( ::Contents[i][2], {cIdent, cString} )
         endif

      else
         AAdd( ::Contents, {cSection, {{cIdent, cString}}} )
      endif
   endif
return

static function ReadNumber(cSection, cIdent, nDefault)
   local Self := QSelf()
return Val( ::ReadString(cSection, cIdent, str(nDefault)) )

static procedure WriteNumber(cSection, cIdent, nNumber)
   local Self := QSelf()

   ::WriteString( cSection, cIdent, alltrim(str(nNumber)) )
return

static function ReadDate(cSection, cIdent, dDefault)
   local Self := QSelf()
return SToD( ::ReadString(cSection, cIdent, DToS(dDefault)) )

static procedure WriteDate(cSection, cIdent, dDate)
   local Self := QSelf()

   ::WriteString( cSection, cIdent, DToS(dDate) )
return

static function ReadBool(cSection, cIdent, lDefault)
   local Self := QSelf()
   local cDefault := Iif( lDefault, '.t.', '.f.' )

return ::ReadString(cSection, cIdent, cDefault) == '.t.'

static procedure WriteBool(cSection, cIdent, lBool)
   local Self := QSelf()

   ::WriteString( cSection, cIdent, Iif(lBool, '.t.', '.f.') )
return

static procedure DeleteKey(cSection, cIdent)
   local Self := QSelf()
   local i, j

   cSection := lower(cSection)
   i := AScan( ::Contents, {|x| valtype(x[1]) == 'C' .and. lower(x[1]) == cSection} )
   
   if i > 0
      cIdent := lower(cIdent)
      j := AScan( ::Contents[i][2], {|x| valtype(x[1]) == 'C' .and. lower(x[1]) == cIdent} )

      ADel( ::Contents[i][2], j )
      ASize( ::Contents[i][2], Len(::Contents[i][2]) - 1 )
   endif
return

static procedure EraseSection(cSection)
   local Self := QSelf()
   local i

   if Empty(cSection)
      while (i := AScan( ::Contents, {|x| valtype(x[1]) == 'C' .and. ValType(x[2]) == 'C'})) > 0
         ADel( ::Contents, i )
         ASize( ::Contents, len(::Contents) - 1 )
      end

   else
      cSection := lower(cSection)
      if (i := AScan( ::Contents, {|x| valtype(x[1]) == 'C' .and. lower(x[1]) == cSection .and. ValType(x[2]) == 'A'})) > 0
         ADel( ::Contents, i )
         ASize( ::Contents, Len(::Contents) - 1 )
      endif
   endif
return

static function ReadSection(cSection)
   local Self := QSelf()
   local i, j, aSection := {}

   if Empty(cSection)
      for i := 1 to len(::Contents)
         if valtype(::Contents[i][1]) == 'C' .and. valtype(::Contents[i][2]) == 'C'
            aadd(aSection, ::Contents[i][1])
         endif
      next

   else
      cSection := lower(cSection)
      if (i := AScan( ::Contents, {|x| valtype(x[1]) == 'C' .and. x[1] == cSection .and. ValType(x[2]) == 'A'})) > 0

         for j := 1 to Len(::Contents[i][2])

            if ::Contents[i][2][j][1] <> NIL
               AAdd(aSection, ::Contents[i][2][j][1])
            endif
         next
      endif
   endif
return aSection

static function ReadSections()
   local Self := QSelf()
   local i, aSections := {}

   for i := 1 to Len(::Contents)

      if ValType(::Contents[i][2]) == 'A'
         AAdd(aSections, ::Contents[i][1])
      endif
   next
return aSections

static procedure UpdateFile()
   local Self := QSelf()
   local i, j, hFile

   hFile := fcreate(::Filename)

   for i := 1 to Len(::Contents)
      if ::Contents[i][1] == NIL
         fwrite(hFile, ::Contents[i][2] + Chr(13) + Chr(10))

      elseif ValType(::Contents[i][2]) == 'A'
         fwrite(hFile, '[' + ::Contents[i][1] + ']' + Chr(13) + Chr(10))
         for j := 1 to Len(::Contents[i][2])

            if ::Contents[i][2][j][1] == NIL
               fwrite(hFile, ::Contents[i][2][j][2] + Chr(13) + Chr(10))

            else
               fwrite(hFile, ::Contents[i][2][j][1] + '=' + ::Contents[i][2][j][2] + Chr(13) + Chr(10))
            endif
         next
         fwrite(hFile, Chr(13) + Chr(10))

      elseif ValType(::Contents[i][2]) == 'C'
         fwrite(hFile, ::Contents[i][1] + '=' + ::Contents[i][2] + Chr(13) + Chr(10))

      endif
   next
   fclose(hFile)
return


Veja exemplo de uso no hBoleto.prg
/*
* $Id: hboleto.prg,v 1.3 2007/08/07 14:41:13 masturm Exp $
*/
 
/*
* Copyright 2006 Mario Simoes Filho mario@argoninformatica.com.br for original demoboleto.prg
* Copyright 2006 Marcelo Sturm <marcelo.sturm@gmail.com> for modifications in the original project
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2, or (at your option)
* any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this software; see the file COPYING.  If not, write to
* the Free Software Foundation, Inc., 59 Temple Place, Suite 330,
* Boston, MA 02111-1307 USA (or visit the web site http://www.gnu.org/).
*
* As a special exception, the Harbour Project gives permission for
* additional uses of the text contained in its release of Harbour.
*
* The exception is that, if you link the Harbour libraries with other
* files to produce an executable, this does not by itself cause the
* resulting executable to be covered by the GNU General Public License.
* Your use of that executable is in no way restricted on account of
* linking the Harbour library code into it.
*
* This exception does not however invalidate any other reasons why
* the executable file might be covered by the GNU General Public License.
*
* This exception applies only to the code released by the Harbour
* Project under the name Harbour.  If you copy code from other
* Harbour Project or Free Software Foundation releases into a copy of
* Harbour, as the General Public License permits, the exception does
* not apply to the code that you add in this way.  To avoid misleading
* anyone as to the status of such modified files, you must delete
* this exception notice from them.
*
* If you write modifications of your own for Harbour, it is your choice
* whether to permit this exception to apply to your modifications.
* If you do not wish that, delete this exception notice.
*
*/

//#include "common.ch"
#define CRLF CHR(13)+CHR(10)
#xtranslate Default( <x>, <y> ) => IIF( <x> == NIL, <y>, <x> )

// Esse programa lê um arquivo .ini de configurações de boletos e gera os boletos a partir dele.
// Gostaria de ter feito com xml, ao invés de ini, mas não conhecia nenhuma classe pronta p/ xml ... e fiz com ini mesmo.
// Se alguém quiser/puder mudar p/ xml, fique à vontade!
// Marcelo Sturm - 01/08/2007

/* -------------------------------------------------------------------------- */

FUNCTION Main( cFileName )

   LOCAL oIni, oRetIni, oBol
   LOCAL cDir, cDirRemessa, lPrint, lPreview, lPromptPrint, cBol, nI := 0

   SET DATE BRIT

   // CriaIni(cFileName)  // Descomentando esta linha, um arquivo de exemplo é gerado.

   oIni = TIniFile():New(Default(cFilename, 'bol.ini'))
   oBol := oBoleto(oIni:ReadString("CAB", "Banco"))
   oBol:lBoleto     := oIni:ReadBool("CAB", "lBoleto", .T.)
   oBol:lRemessa    := oIni:ReadBool("CAB", "lRemessa", .F.)
   oBol:lAnsi       := oIni:ReadBool("CAB", "lAnsi", .F.)
   lPrint           := oIni:ReadBool("CAB", "lPrint", .F.)
   lPreview         := oIni:ReadBool("CAB", "lPreview", .F.)
   lPromptPrint     := oIni:ReadBool("CAB", "lPromptPrint", .F.)
   oBol:nBolsPag    := oIni:ReadNumber("CAB", "nBolsPag", 2)
   oBol:cImageLnk   := oIni:ReadString("CAB", "cImageLnk")
   oBol:Cedente     := oIni:ReadString("CAB", "Cedente")
   oBol:CedenteCNPJ := oIni:ReadString("CAB", "CedenteCNPJ")
   oBol:cNumCC      := oIni:ReadString("CAB", "cNumCC")
   oBol:cNumAgencia := oIni:ReadString("CAB", "cNumAgencia")
   oBol:cCarteira   := oIni:ReadString("CAB", "cCarteira")
   oBol:EspecieTit  := oIni:ReadString("CAB", "EspecieTit")
   oBol:cTipoCob    := oIni:ReadString("CAB", "cTipoCob")
   oBol:nMora       := oIni:ReadNumber("CAB", "nMora", 0)
   oBol:nMulta      := oIni:ReadNumber("CAB", "nMulta", 0)
   oBol:nDiasProt   := oIni:ReadNumber("CAB", "nDiasProt", 0)
   cDir             := oIni:ReadString("CAB", "cDir")
   cDirRemessa      := oIni:ReadString("CAB", "cDirRemessa")
   oBol:Open("boleto") //, cDir, cDirRemessa, cDir)  // Cria html - Sempre colocar após a definição completa do Cedente, pois
                                                     // isso influencia na criação do Arquivo Remessa.
   
   DO WHILE .T.
      cBol := "BOL" + LTRIM(STR(++nI))
      IF EMPTY(oIni:ReadNumber(cBol, "nValor", 0))
         EXIT
      ENDIF
      oBol:Sacado       := oIni:ReadString(cBol, "Sacado")
      oBol:Endereco     := oIni:ReadString(cBol, "Endereco")
      oBol:Bairro       := oIni:ReadString(cBol, "Bairro")
      oBol:Cidade       := oIni:ReadString(cBol, "Cidade")
      oBol:Estado       := oIni:ReadString(cBol, "Estado")
      oBol:CEP          := oIni:ReadString(cBol, "CEP")
      oBol:CNPJ         := oIni:ReadString(cBol, "CNPJ")
      oBol:Instrucoes   := oIni:ReadString(cBol, "Instrucoes", "")
      oBol:cNumDoc      := oIni:ReadString(cBol, "cNumDoc", "")          // seu numero do documento
      oBol:cNossoNumero := oIni:ReadString(cBol, "cNossoNumero", "")     // numero do banco
      oBol:nValor       := oIni:ReadNumber(cBol, "nValor", 0)            // valor do boleto
      oBol:DtEmis       := oIni:ReadDate(cBol, "DtEmis", DATE())
      oBol:DtVenc       := oIni:ReadDate(cBol, "DtVenc", DATE())
      oBol:Execute() // monta html
   ENDDO

   oBol:Close()
   IF lPrint
      oBol:Print(lPreview, lPromptPrint) // Imprime o boleto */
   ENDIF

   IF oBol:lRemessa .AND. !EMPTY(oBol:oRem:NomeRem)
      oRetIni = TIniFile():New(Default(cFilename, 'bol.ini') + '.ret')
      oRetIni:WriteString("RET", "NomeRem", oBol:oRem:NomeRem)
      oRetIni:WriteString("RET", "Destino", oBol:oRem:Destino)
      oRetIni:WriteString("RET", "cNumSequencial", oBol:oRem:cNumSequencial)
      oRetIni:WriteNumber("RET", "nTitLote", oBol:oRem:nTitLote)
      oRetIni:UpdateFile()
   ENDIF

RETURN NIL

/* -------------------------------------------------------------------------- */

STATIC FUNCTION CriaIni( cFileName )

   LOCAL oIni

   oIni = TIniFile():New(Default(cFilename, 'bol.ini'))
   oIni:WriteString("CAB", "Banco", "409")
   oIni:WriteString("CAB", "cImageLnk", "")
   oIni:WriteBool("CAB", "lBoleto", .T.)
   oIni:WriteBool("CAB", "lRemessa", .T.)
   oIni:WriteBool("CAB", "lAnsi", .T.)
   oIni:WriteBool("CAB", "lPrint", .T.)
   oIni:WriteBool("CAB", "lPreview", .T.)
   oIni:WriteBool("CAB", "lPromptPrint", .T.)
   oIni:WriteNumber("CAB", "nBolsPag", 2)
   oIni:WriteString("CAB", "Cedente", "Teste de Cedente")
   oIni:WriteString("CAB", "CedenteCNPJ", "11111111111180")
   oIni:WriteString("CAB", "cNumCC", "100778-3")
   oIni:WriteString("CAB", "cNumAgencia", "1748-5")
   oIni:WriteString("CAB", "cCarteira", "1")
   oIni:WriteString("CAB", "EspecieTit", "DM")
   oIni:WriteString("CAB", "cTipoCob", "5")
   oIni:WriteNumber("CAB", "nMora", 0)
   oIni:WriteNumber("CAB", "nMulta", 0)
   oIni:WriteNumber("CAB", "nDiasProt", 0)
   oIni:WriteString("CAB", "cDir", "")
   oIni:WriteString("CAB", "cDirRemessa", "")

   oIni:WriteString("BOL1", "Sacado", "Sacado")
   oIni:WriteString("BOL1", "Endereco", "Endereço")
   oIni:WriteString("BOL1", "Bairro", "Bairro")
   oIni:WriteString("BOL1", "Cidade", "Cidade")
   oIni:WriteString("BOL1", "Estado", "Estado")
   oIni:WriteString("BOL1", "CEP", "20000000")
   oIni:WriteString("BOL1", "CNPJ", "0000000")
   oIni:WriteString("BOL1", "Instrucoes", "Observação")
   oIni:WriteString("BOL1", "cNumDoc", "001396")              // seu numero do documento
   oIni:WriteString("BOL1", "cNossoNumero", "7410114733")     // numero do banco
   oIni:WriteNumber("BOL1", "nValor", 1051.32)                // valor do boleto
   oIni:WriteDate("BOL1", "DtVenc", CTOD("26/09/2006"))

   oIni:WriteString("BOL2", "Sacado", "Cedente 2  - áéíóúàãõâêôüçÁÉÍÓÚÀÃÕÂÊÔÜǪº°§")
   oIni:WriteString("BOL2", "Endereco", "Endereço")
   oIni:WriteString("BOL2", "Bairro", "Bairro")
   oIni:WriteString("BOL2", "Cidade", "Cidade")
   oIni:WriteString("BOL2", "Estado", "Estado")
   oIni:WriteString("BOL2", "CEP", "20000000")
   oIni:WriteString("BOL2", "CNPJ", "0000000")
   oIni:WriteString("BOL2", "cNumDoc", "001397")              // seu numero do documento
   oIni:WriteString("BOL2", "cNossoNumero", "5682521917")     // numero do banco
   oIni:WriteNumber("BOL2", "nValor", 193.68)                 // valor do boleto
   oIni:WriteDate("BOL2", "DtVenc", CTOD("19/07/2006"))

RETURN oIni:UpdateFile()


Exemplo de uso simplificado:
   LOCAL oIni

   oIni = TIniFile():New( 'teste.ini' )
   ...
   oIni:WriteString("CAB", "Banco", "409")
   ...
   oIni:WriteBool("CAB", "lBoleto", .T.)
   ...
   oIni:WriteNumber("CAB", "nBolsPag", 2)
   ...
   oIni:WriteDate("BOL1", "DtVenc", CTOD("26/09/2006"))
   ...
   oIni:WriteString("BOL2", "Sacado", "Cedente 2  - áéíóúàãõâêôüçÁÉÍÓÚÀÃÕÂÊÔÜǪº°§")
   ...
   oIni:UpdateFile()


Para cada tipo da linguagem você tem uma função que trata e salva o conteúdo.
OPS! LINK QUEBRADO? Veja ESTE TOPICO antes e caso não encontre ENVIE seu email com link do tópico para fivolution@hotmail.com. Agradecido.

@braços : ? )

A justiça divina tarda mas não falha, enquanto que a justiça dos homens falha porque tarda.
Avatar de usuário

rochinha
Membro Master

Membro Master
 
Mensagens: 4538
Data de registro: 18 Ago 2003 20:43
Cidade/Estado: São Paulo - Brasil
Curtiu: 800 vezes
Mens.Curtidas: 242 vezes

Mapear Drive de Rede perdido

Mensagempor MSDN » 09 Fev 2017 09:14

Use o endereço IP ( se for fixo claro ) para acessar, EX : SET PATH TO "\\10.75.1.5\tabelas\" ou incorpore o endereço IP à uma variável e concatene no caminho onde vc cria/abre DBF e indice.
MSDN
Usuário Nível 4

Usuário Nível 4
 
Mensagens: 741
Data de registro: 28 Nov 2003 14:55
Cidade/Estado: CWB
Curtiu: 178 vezes
Mens.Curtidas: 123 vezes

Mapear Drive de Rede perdido

Mensagempor rochinha » 09 Fev 2017 18:40

Amiguinhos,

MSDN
Eu venho daquele tempo que comandos iniciados com NET eram só pros loucos que usavam NetWare da Novell. Tempo bão.

Desde aquela época, sempre mapeavamos um local na rede para não ter de se preocupar com números. A famosa letra F ou Z eram as letras que qualquer um iniciado em computação sabia que poderia ser o servidor.

Como durante estes anos eu sempre optei por mapear, continuei, talvez o Harbour já tenha sanado o problema de abertura na rede via UNC e IP, sem o uso de NetIO, etc. Mas meu sistema não abre nenhum arquivo ou indice se não estiver sendo chamado de um ponto mapeado.

Não lembro se usei o SET PATH TO "UNCPath" mas tentarei posteriormente para dar respaldo.

"...O homem antigo inventou a roda, é nós não paramos de aperfeiçoá-la..."
OPS! LINK QUEBRADO? Veja ESTE TOPICO antes e caso não encontre ENVIE seu email com link do tópico para fivolution@hotmail.com. Agradecido.

@braços : ? )

A justiça divina tarda mas não falha, enquanto que a justiça dos homens falha porque tarda.
Avatar de usuário

rochinha
Membro Master

Membro Master
 
Mensagens: 4538
Data de registro: 18 Ago 2003 20:43
Cidade/Estado: São Paulo - Brasil
Curtiu: 800 vezes
Mens.Curtidas: 242 vezes

Próximo



Retornar para Contribuições, Dicas e Tutoriais

Quem está online

Usuários vendo este fórum: Nenhum usuário registrado online e 21 visitantes


Ola Amigo, espero que meu site e forum tem lhe beneficiado, com exemplos e dicas de programacao.
Entao divulgue o link da Doacao abaixo para seus amigos e redes sociais ou faça uma doacao para o site forum...
MUITO OBRIGADO PELA SUA DOACAO!
Faça uma doação para o forum
cron
v
Olá visitante, seja bem-vindo ao Fórum Clipper On Line!
Efetue o seu login ou faça o seu Registro