Example #1
0
 public ShopUserControl()
 {
     InitializeComponent();
     this.DataContext    = this;
     this.shopWebService = new WebServiceManager <Shop>(DataConnectionResource.LOCALAPI);
     this.shopManager    = new MySQLManager <Shop>(DataConnectionResource.LOCALMYQSL);
 }
Example #2
0
 public DashBoardViewModel(INavigationService navigationService) : base(navigationService)
 {
     try
     {
         _navigationService = navigationService;
         webServiceManager  = new WebServiceManager();
         Title        = "Inspections";
         LoginCommand = new Command(async() => ExecuteLogoutCommandAsync());
         UserRoleId   = Convert.ToInt32(RememberMe.Get("UserRoleId"));
         //Xamarin.Forms.Device.BeginInvokeOnMainThread(async () =>
         //{
         //  await Task.Delay(1000);
         //  bool IsSyncDatabse = (Boolean)RememberMe.Get("isSyncDatabse", true);
         //  if (IsSyncDatabse && ConfigurationCommon.App_Online)
         //  {
         //    InitData.SyncHeaderDetailsInServer();
         //    RememberMe.Set("isSyncDatabse", false);
         //    await Xamarin.Forms.Application.Current.SavePropertiesAsync();
         //  }
         //  InitData.GetAllInitData();
         //});
     }
     catch (Exception ex)
     {
         throw ex;
     }
 }
Example #3
0
        public static Dictionary <PropDef, object> getFilePropertiesDefs(VDF.Vault.Currency.Connections.Connection connection, File selectedFile)
        {
            Dictionary <PropDef, object> dictionary = new Dictionary <PropDef, object>();

            try
            {
                using (WebServiceManager manager = connection.WebServiceManager)
                {
                    FileIteration entity = new FileIteration(connection, selectedFile);
                    PropDef[]     propertyDefinitionsByEntityClassId = manager.PropertyService.GetPropertyDefinitionsByEntityClassId("FILE");
                    PropertyDefinitionDictionary dictionary2         = connection.PropertyManager.GetPropertyDefinitions("FILE", null, PropertyDefinitionFilter.IncludeAll);
                    foreach (PropDef def in propertyDefinitionsByEntityClassId)
                    {
                        object obj2 = connection.PropertyManager.GetPropertyValue(entity, dictionary2[def.Id], null);
                        dictionary.Add(def, (obj2 == null) ? "" : obj2);
                        //Log.logger(string.Format("== LIB pro DICT == >>   '{0}' = '{1}'", def.DispName.ToString(), (obj2 == null) ? "" : obj2.ToString()));
                    }
                }
            }
            catch (SystemException exception)
            {
                //Log.logger(exception.ToString());
            }
            return(dictionary);
        }
Example #4
0
        public static Dictionary <string, string> getFileProperties(VDF.Vault.Currency.Connections.Connection connection, File selectedFile)
        {
            Dictionary <string, string> dict = new Dictionary <string, string>();

            try
            {
                using (WebServiceManager serviceManager = connection.WebServiceManager) //using will log out after usage
                {
                    VDF.Vault.Currency.Entities.FileIteration fileInteration = new FileIteration(connection, selectedFile);
                    PropDef[] propDefs    = serviceManager.PropertyService.GetPropertyDefinitionsByEntityClassId("FILE");
                    var       propDefsAlt = connection.PropertyManager.GetPropertyDefinitions(VDF.Vault.Currency.Entities.EntityClassIds.Files, null, VDF.Vault.Currency.Properties.PropertyDefinitionFilter.IncludeAll);
                    foreach (PropDef pdef in propDefs)
                    {
                        object propValue = connection.PropertyManager.GetPropertyValue(fileInteration, propDefsAlt[pdef.Id], null);
                        //PropInst propinst = propcoll[0];
                        //string val = propinst.Val == null ? "" : propinst.Val.ToString();
                        dict.Add(pdef.DispName.ToString(), propValue == null ? "" : propValue.ToString());
                        logit.logger(string.Format("== LIB pro DICT == >>   '{0}' = '{1}'", pdef.DispName.ToString(), propValue == null ? "" : propValue.ToString()));

                        //PropInst[] propcoll = serviceManager.PropertyService.GetProperties("FILE", new long[] { selectedFile.Id }, new long[] { pdef.Id });
                    }
                }
            }
            catch (SystemException ex)
            {
                logit.logger(ex.ToString());
            }
            return(dict);
        }
Example #5
0
        public string updateCustomObjPropbyPropName(VDF.Vault.Currency.Connections.Connection connection, string PropName, long entID, string ObjType, object value) //CUSTENT
        {
            try
            {
                using (WebServiceManager serviceManager = connection.WebServiceManager) //using will log out after usage
                {
                    var propDefs = getPropertyDefDetails(connection, ObjType, PropName);
                    CES = connection.WebServiceManager.CustomEntityService;
                    //check value format
                    List <long> entitiesList = new List <long>();
                    entitiesList.Clear();
                    entitiesList.Add(entID);
                    CES.UpdateCustomEntityProperties(entitiesList.ToArray(), new PropInstParamArray[] { new PropInstParamArray()
                                                                                                        {
                                                                                                            Items = new PropInstParam[] { new PropInstParam()
                                                                                                                                          {
                                                                                                                                              PropDefId = propDefs.Id, Val = value
                                                                                                                                          } }
                                                                                                        } });
                    result = propDefs.DispName + " | " + propDefs.IsSys + " | " + propDefs.Typ + " | " + propDefs.Id;
                }
            }
            catch (SystemException ex)
            {
                result = ex.ToString();
            }

            return(result);
        }
Example #6
0
        public async void Test()
        {
            WebServiceManager manager = new WebServiceManager();
            Pokemon           bulbi   = new Pokemon();

            bulbi = await manager.GetData <Pokemon>("pokemon/1/", new Pokemon());
        }
Example #7
0
        public void OnLogOn(IApplication application)
        {
            ReleaseServiceManager();
            IWebServiceCredentials credentials = application.VaultContext.GetCredentials();

            ServiceManager = new WebServiceManager(credentials);
        }
Example #8
0
 public AddressUserControl()
 {
     InitializeComponent();
     this.DataContext       = this;
     this.addressWebService = new WebServiceManager <Address>(DataConnectionResource.LOCALAPI);
     this.addressManager    = new MySQLManager <Address>(DataConnectionResource.LOCALMYQSL);
 }
Example #9
0
        public static PropDef getPropertyDefDetails(VDF.Vault.Currency.Connections.Connection connection, string entityClassIDs, string propertyName)
        {
            Dictionary <long, string> props = new Dictionary <long, string>();

            try
            {
                using (WebServiceManager serviceManager = connection.WebServiceManager) //using will log out after usage
                {
                    var propDefs = serviceManager.PropertyService.GetPropertyDefinitionsByEntityClassId(entityClassIDs);

                    foreach (var item in propDefs)
                    {
                        //MessageBox.Show(propertyName + " == " + item.DispName + " | | | " + item.Id);
                        if (item.DispName.Equals(propertyName))
                        {
                            //MessageBox.Show(item.DispName + " | " + item.Id);
                            propinfo = item;
                        }
                    }
                }
            }
            catch (SystemException ex)
            {
                MessageBox.Show(ex.ToString());
            }
            return(propinfo);
        }
Example #10
0
        public OrganisationPickerDialog(VDF.Vault.Currency.Connections.Connection connection)
        {
            InitializeComponent();

            _wsm = connection.WebServiceManager;
            var custEntDefs = _wsm.CustomEntityService.GetAllCustomEntityDefinitions();
            var custEntDef  = custEntDefs.SingleOrDefault(c => c.DispName.Equals("Organisation"));

            Icon = GetCustomEntityIcon(custEntDef);
            var entities = new List <VDF.Vault.Currency.Entities.IEntity>();
            var custEnts = GetAllCustomEntities(custEntDef);

            foreach (var custEnt in custEnts)
            {
                entities.Add(new VDF.Vault.Currency.Entities.CustomObject(connection, custEnt));
            }
            var configuration = new VDF.Vault.Forms.Controls.VaultBrowserControl.Configuration(
                connection,
                "Grid.SelectOrganisationAndOrderNumber",
                null);

            configuration.AddInitialColumn("Name");
            configuration.AddInitialSortCriteria("Name", true);

            _navigationModel = new VDF.Vault.Forms.Models.ViewVaultNavigationModel();
            _navigationModel.AddContent(entities);

            vaultBrowserControl1.SetDataSource(configuration, _navigationModel);
            vaultBrowserControl1.Refresh();
        }
Example #11
0
 public static void updateITEMPropbyName(VDF.Vault.Currency.Connections.Connection connection, Item item, string PropName, string propValue)
 {
     try
     {
         using (WebServiceManager wServ = connection.WebServiceManager) //using will log out after usage
         {
             ItemService IS       = wServ.ItemService;
             PropDef     propDefs = getPropertyDefDetails(connection, "ITEM", PropName);
             var         editITEM = IS.EditItems(new long[] { item.RevId })[0];
             GenVaultHelper.LibNotes();
             rID = new[] { editITEM.RevId };
             PropInstParam PIP = new PropInstParam()
             {
                 PropDefId = propDefs.Id, Val = propValue
             };
             Item[] uitem = IS.UpdateItemProperties(rID, new PropInstParamArray[] { new PropInstParamArray()
                                                                                    {
                                                                                        Items = new PropInstParam[] { PIP }
                                                                                    } });
             IS.UpdateAndCommitItems(uitem); //IS.UpdateAndCommitItems(new Item[] { item });
             //IS.DeleteUncommittedItems(false);
         }
     }
     catch (System.Exception ex)
     {
         //return ex.ToString();
     }
 }
Example #12
0
        public void Constructor()
        {
            WebServiceManager webServiceManager;

            webServiceManager = new WebServiceManager();
            Assert.IsNotNull(webServiceManager);
        }
Example #13
0
        private void Handle_Worker_DoWork(object sender, DoWorkEventArgs e)
        {
            Util.DoAction(delegate
            {
                _btnStart.InvokeIfRequired(() => _btnStart.Enabled = false);
                _btnClose.InvokeIfRequired(() => _btnClose.Enabled = false);
                _btnStop.InvokeIfRequired(() => _btnStop.Enabled   = true);
                //_listView.InvokeIfRequired(() => _listView.Items.Clear());
                IgnoreKPG = ckIgnoreKPG.Checked;
                IgnoreDS  = ckIgnoreDS.Checked;
                // the method is run in separate thread so we create separate instance of WebServiceManager
                using (WebServiceManager serviceMgr = new WebServiceManager(Credentials))
                {
                    AddStepFileAction StepAction = new AddStepFileAction
                    {
                        ServiceManager = serviceMgr,
                        IgnoreKPG      = ckIgnoreKPG.Checked,
                        IgnoreDS       = ckIgnoreDS.Checked,
                    };

                    StepAction.ContinueProcessing += new EventHandler <CancelEventArgs>(Handle_StepAction_ContinueProcessing);
                    StepAction.ItemStatusUpdate   += new EventHandler <ItemStatusUpdateEventArgs>(Handle_StepAction_ItemStatusUpdate);
                    StepAction.ItemFileUpdate     += new EventHandler <ItemFileUpdateEventArgs>(Handle_StepAction_ItemFileUpdate);
                    StepAction.GenerateAndAdd(Items);
                }
            });
        }
Example #14
0
 public CategoryUserControl()
 {
     InitializeComponent();
     this.DataContext        = this;
     this.categoryManager    = new MySQLManager <Category>(DataConnectionResource.LOCALMYQSL);
     this.categoryWebService = new WebServiceManager <Category>(DataConnectionResource.LOCALAPI);
 }
Example #15
0
 public static int getFilesinFolderCountID(VDF.Vault.Currency.Connections.Connection connection, string folderID)
 {
     try
     {
         filecoll = null;
         using (WebServiceManager wServ = connection.WebServiceManager)
         {
             string     bookmark = string.Empty;
             SrchStatus status   = null;
             filecoll = wServ.DocumentService.FindFilesBySearchConditions(null, null, new long[] { Convert.ToInt64(folderID) }, false, true, ref bookmark, out status);
             if (filecoll == null)
             {
                 count = 0;
             }
             else
             {
                 count = filecoll.Count();
             }
             //MessageBox.Show("Count" + filecoll.ToList<Autodesk.Connectivity.WebServices.File>().Count().ToString());
         }
     }
     catch (SystemException ex)
     {
         //statusMess = null;
         Debug.Write("\nError: " + ex.ToString());
         statusMess += "Error: \n" + ex.ToString();
     }
     return(count);
 }
Example #16
0
        public CustEnt[] getCustomentitiesbyPropName(VDF.Vault.Currency.Connections.Connection connection, string ObjType, string PropName, string srchop, string searchText)
        {
            try
            {
                //
                using (WebServiceManager serviceManager = connection.WebServiceManager) //using will log out after usage
                {
                    //get property details
                    var propDefs = getPropertyDefDetails(connection, ObjType, PropName);
                    result = connection.Vault.ToString();
                    DocumentService docServ = serviceManager.DocumentService;

                    SrchCond srchCond = new SrchCond()
                    {
                        PropDefId = propDefs.Id,
                        PropTyp   = PropertySearchType.AllProperties,
                        SrchOper  = SrchOperator(srchop), // is equal
                        SrchRule  = SearchRuleType.Must,
                        SrchTxt   = searchText.ToString()
                    };

                    //result = propDefs.Id.ToString();
                    string     bookmark = string.Empty;
                    SrchStatus status   = null;
                    custEntities = connection.WebServiceManager.CustomEntityService.FindCustomEntitiesBySearchConditions(new SrchCond[] { srchCond }, null, ref bookmark, out status);
                }
            }
            catch (SystemException ex)
            {
                result = ex.ToString();
            }
            return(custEntities);
        }
Example #17
0
        protected override void Establish_context()
        {
            base.Establish_context();
            contentToDownloadPath = Path.Combine(contentDirectoryName, checkingFileName);

            NetworkSettings.SetupGet(setting => setting.BlockSize).Returns(10000);
            NetworkSettings.SetupGet(setting => setting.ProxyIP).Returns("");
            NetworkSettings.SetupGet(setting => setting.ProxyPort).Returns(1043);
            NetworkSettings.SetupGet(settng => settng.UseProxy).Returns(false);

            string downloadUri = Path.Combine(httpServiceEndpoint, contentDirectoryName, checkingFileName).Replace("\\", "/");

            UriSource.Setup(source => source.Uri).Returns(downloadUri);


            this.createDirectoryIfNotExists();
            this.createFileToDownloadInDirectory();
            webServiceManager           = new WebServiceManager(contentDirectoryName, "");
            saveDownloadedContentStream = new MemoryStream();

            string errorMessage = "";

            if (!webServiceManager.TryStart(httpServiceEndpoint, out errorMessage))
            {
                throw new InvalidOperationException(errorMessage);
            }
            NetworkClient.OnBlockDownloaded += new Action <byte[], int>(NetworkClient_OnBlockDownloaded);
        }
Example #18
0
        public static void Main(string[] args)
        {
            WebServiceManager <Class1> managerC1 = new WebServiceManager <Class1>("http://localhost:60984/");
            WebServiceManager <Class2> managerC2 = new WebServiceManager <Class2>("http://localhost:60984/");

            foreach (var item in managerC1.Get().Result)
            {
                Console.WriteLine(item);
            }

            foreach (var item in managerC2.Get().Result)
            {
                Console.WriteLine(item);
            }

            for (int i = 0; i < 5; i++)
            {
                Class1 class1 = new Class1()
                {
                    Data = "c1B" + i
                };
                managerC1.Post(class1);
            }

            Console.ReadKey();
        }
Example #19
0
        /// <summary>
        /// Getter All Lower Assortment with Higher Assortment Id
        /// </summary>
        /// <param name="assortmentId">Higher Assortment Id</param>
        /// <returns></returns>
        public List <GetterModel> GetLowerAssortment(int assortmentId)
        {
            WebServiceManager  wsm = new WebServiceManager();
            string             jsonLowerAssortment  = wsm.PostManager("https://derbis.dernekler.gov.tr/IstatistikDerneklerWeb/GetAltNeviler", new { neviPk = assortmentId });
            List <GetterModel> listLowerAssortments = JsonConvert.DeserializeObject <List <GetterModel> >(jsonLowerAssortment);

            return(listLowerAssortments);
        }
 public RegistrationViewModel(INavigationService _navigationService) : base(_navigationService)
 {
     navigationService = _navigationService;
     webServiceManager = new WebServiceManager();
     Title             = "Registration Page";
     OkayCommand       = new Command(async() => Okay_Command());
     GetAllInitData();
 }
Example #21
0
        public List <GetterModel> GetDistricts(int cityId)
        {
            WebServiceManager  wsm           = new WebServiceManager();
            string             jsonDistrict  = wsm.PostManager("https://derbis.dernekler.gov.tr/IstatistikDerneklerWeb/IlIlceleriniYukle", new { ilPk = cityId });
            List <GetterModel> listDistricts = JsonConvert.DeserializeObject <List <GetterModel> >(jsonDistrict);

            return(listDistricts);
        }
Example #22
0
 public OwnerUserControl()
 {
     InitializeComponent();
     this.DataContext     = this;
     this.ownerWebService = new WebServiceManager <Owner>(DataConnectionResource.LOCALAPI);
     this.ownerManager    = new MySQLManager <Owner>(DataConnectionResource.LOCALMYQSL);
     Load();
 }
Example #23
0
 public static long createCustomObj(VDF.Vault.Currency.Connections.Connection connection, int PropDefID, string objName)
 {
     using (WebServiceManager serviceManager = connection.WebServiceManager) //using will log out after usage
     {
         ent = CES.AddCustomEntity(PropDefID, objName);
     }
     return(ent.Id);
 }
Example #24
0
 public ProductUserControl()
 {
     InitializeComponent();
     //this.CategoryUserControl.Category = this.product.Category;
     this.DataContext       = this;
     this.productManager    = new MySQLManager <Product>(DataConnectionResource.LOCALMYQSL);
     this.productWebService = new WebServiceManager <Product>(DataConnectionResource.LOCALAPI);
 }
Example #25
0
 private void ReleaseServiceManager()
 {
     if (ServiceManager != null)
     {
         ServiceManager.Dispose();
         ServiceManager = null;
     }
 }
Example #26
0
 public OrderUserControl()
 {
     InitializeComponent();
     this.DataContext     = this;
     this.orderManager    = new MySQLManager <Order>(DataConnectionResource.LOCALMYQSL);
     this.productManager  = new MySQLManager <Product>(DataConnectionResource.LOCALMYQSL);
     this.orderWebService = new WebServiceManager <Order>(DataConnectionResource.LOCALAPI);
 }
Example #27
0
        protected override void Establish_context()
        {
            string errorMessage = "";

            base.Establish_context();
            WebServiceManager.TryStart(EndpointAddress, out errorMessage);
            Request = EndpointAddress + "Filelist";
        }
Example #28
0
        private void CheckBox_Unchecked(object sender, RoutedEventArgs e)
        {
            WebServiceManager.GetAllCards(0); // use 1 to get only collectible cards
            List <MainConsole.Classes.Card> listCards = WebServiceManager.ProvideCardList();

            dataGrid.ItemsSource = null;
            dataGrid.ItemsSource = listCards;
        }
 public LifxManager(string auth)
 {
     if (auth.Length != 64)
     {
         throw new FormatException("Authentication token should be 64 characters long");
     }
     var webServiceManager = new WebServiceManager(auth, "Bearer");
 }
Example #30
0
 private WebServiceManager GetWebServiceManager(Boolean refresh = false)
 {
     if (_webServiceManager.IsNull() || refresh)
     {
         _webServiceManager = new WebServiceManager();
     }
     return(_webServiceManager);
 }
        /// <summary>
        /// List Member Requirment by member name
        /// </summary>
        /// <param name="memberName">member name</param>
        /// <returns>member requirements</returns>
        public IList<requirement> ListMemberRequirements(string memberName)
        {
            WebServiceManager _wsManager = new WebServiceManager("http://localhost/fsllCore");
            var members = _wsManager.Get("/Member/GetMember?name=" + memberName);

            if (members.Count > 0 && members[0]["MemberID"] != null)
            {
                return ListMemberRequirements(members[0].MemberID);
            }
            else
            {
                throw new Exception("Multiple Member Name Detected");
            }
        }
 protected override void Establish_context()
 {
     base.Establish_context();
     WebServiceManager = new WebServiceManager(contentFolderPath, "");
     createContentDirectory();
 }
Example #33
0
        static void Main(string[] args)
        {
            if (args.Length > 0)
            {
                for (int i = 0; i < args.Length; i++)
                {
                    if (args[i].Equals("-d") && i < (args.Length - 1))
                    {
                        downdir = args[++i];
                        if (!downdir.EndsWith("\\"))
                        {
                            downdir = downdir + "\\";
                        }
                    }
                }
            }

            // Le o arquivo de configuração
            //config = ReadPropertyFile(Directory.GetCurrentDirectory() + "\\vaultsrv.conf");
            LOG.imprimeLog(System.DateTime.Now + " === Vai ler o arquivo de configuracao=" + downdir + "vaultsrv.conf");
            config = Util.ReadPropertyFile(downdir + "vaultsrv.conf");
            if (config != null)
            {
                LOG.imprimeLog(System.DateTime.Now + " ============ VAULTSRV.CONF ENCONTRADO");
                mailPort = Util.GetProperty(config, "mailPort") != null ? System.Convert.ToInt32(Util.GetProperty(config, "mailPort"), 10) : 0;
                mailHost = Util.GetProperty(config, "mailHost");
                mailSender = Util.GetProperty(config, "mailSender");
                mailUser = Util.GetProperty(config, "mailUser");
                mailPassword = Util.GetProperty(config, "mailPassword");
                mailTO = Util.GetProperty(config, "mailTO");
                mailEnableSSL = Util.GetProperty(config, "mailEnableSSL") != null && Util.GetProperty(config, "mailEnableSSL").Equals("true");
            }

            // Le arquivo com as imagens que apresentaram erro na conversao.
            reconvert = Util.ReadPropertyFile("reconvert.conf");

            Util.SetProperty(config, "ultimaExecucao", DateTime.Now.ToUniversalTime().ToString("yyyy/MM/dd HH:mm:ss"));

            // Parse dos parametros
            if (args.Length > 0)
            {
                for (int i = 0; i < args.Length; i++)
                {
                    if (args[i].Equals("-ecmlogin") && i < (args.Length - 1))
                    {
                        ecmLogin = args[++i];
                        if (ecmUser == null)
                        {
                            ecmUser = ecmLogin;
                        }
                    }
                    else
                        if (args[i].Equals("-ecmuser") && i < (args.Length - 1))
                        {
                            ecmUser = args[++i];
                        }
                        else
                            if (args[i].Equals("-ecmpassword") && i < (args.Length - 1))
                            {
                                ecmPassword = args[++i];
                            }
                            else
                                if (args[i].Equals("-ecmurl") && i < (args.Length - 1))
                                {
                                    ecmURL = args[++i];
                                }
                                else
                                    if (args[i].Equals("-ecmcompany") && i < (args.Length - 1))
                                    {
                                        ecmCompany = System.Convert.ToInt32(args[++i], 10);
                                    }
                                    else
                                        if (args[i].Equals("-ecmrootfolder") && i < (args.Length - 1))
                                        {
                                            ecmRootFolder = System.Convert.ToInt32(args[++i], 10);
                                        }
                                        else
                                            if (args[i].Equals("-ecmdeljpg"))
                                            {
                                                ecmDelJpg = true;
                                            }
                                            else

                                                if (args[i].Equals("-i") && i < (args.Length - 1))
                                                {
                                                    propid = System.Convert.ToInt32(args[++i], 10);
                                                }
                                                else
                                                    if (args[i].Equals("-u") && i < (args.Length - 1))
                                                    {
                                                        user = args[++i];
                                                    }
                                                    else
                                                        if (args[i].Equals("-p") && i < (args.Length - 1))
                                                        {
                                                            pass = args[++i];
                                                        }
                                                        else
                                                            if (args[i].Equals("-imagetype") && i < (args.Length - 1))
                                                            {
                                                                if (args[++i].ToLower().Equals("anvisa"))
                                                                    imageType = "ANVISA_";
                                                                else if (args[++i].ToLower().Equals("fda"))
                                                                    imageType = "FDA_";
                                                                else if (args[++i].ToLower().Equals("des"))
                                                                    imageType = "DES_";
                                                                pass = args[++i];
                                                            }
                                                            else
                                                                if (args[i].Equals("-h") && i < (args.Length - 1))
                                                                {
                                                                    server = args[++i];
                                                                }
                                                                else
                                                                    if (args[i].Equals("-v") && i < (args.Length - 1))
                                                                    {
                                                                        vault = args[++i];
                                                                    }
                                                                    else
                                                                        if (args[i].Equals("-s") && i < (args.Length - 1))
                                                                        {
                                                                            searchType = System.Convert.ToInt32(args[++i], 10);
                                                                        }
                                                                        else
                                                                            if (args[i].Equals("-printer"))
                                                                            {
                                                                                if (i < args.Length - 1)
                                                                                {
                                                                                    printerName = args[++i];
                                                                                }
                                                                            }
                                                                            else
                                                                                if (args[i].Equals("-single"))
                                                                                {
                                                                                    single = true;
                                                                                }
                                                                                else
                                                                                    if (args[i].Equals("-d") && i < (args.Length - 1))
                                                                                    {
                                                                                        downdir = args[++i];
                                                                                        if (!downdir.EndsWith("\\"))
                                                                                        {
                                                                                            downdir = downdir + "\\";
                                                                                        }
                                                                                    }
                                                                                    else
                                                                                        if (args[i].Equals("-nd"))
                                                                                        {
                                                                                            download = false;
                                                                                        }
                                                                                        else
                                                                                            if (args[i].Equals("-la"))
                                                                                            {
                                                                                                listall = true;
                                                                                            }
                                                                                            else
                                                                                                if (args[i].Equals("-ci"))
                                                                                                {
                                                                                                    if (i < args.Length - 1)
                                                                                                    {
                                                                                                        checkInDate = args[++i];
                                                                                                    }
                                                                                                    else
                                                                                                    {
                                                                                                        checkInDate = Util.GetProperty(config, "LastCheckInDate");
                                                                                                        if (checkInDate == null || checkInDate == "")
                                                                                                        {
                                                                                                            checkInDate = new DateTime(1980 /*agora.Year*/, 1 /*agora.Month*/, 1 /*agora.Day*/, 0 /*agora.Hour*/, 0 /*agora.Minute*/, 0 /*agora.Second*/, 0 /*agora.Millisecond*/).ToUniversalTime().ToString("MM/dd/yyyy HH:mm:ss");
                                                                                                        }
                                                                                                    }
                                                                                                    Util.SetProperty(config, "LastCheckInDate", DateTime.Now.ToString("MM/dd/yyyy HH:mm:ss"));
                                                                                                }
                                                                                                else
                                                                                                    if (args[i].Equals("-cv"))
                                                                                                    {
                                                                                                        converter = true;
                                                                                                        download = true;
                                                                                                    }
                                                                                                    else
                                                                                                        if (args[i].Equals("-del"))
                                                                                                        {
                                                                                                            delFiles = true;
                                                                                                        }
                                                                                                        else
                                                                                                            if (args[i].Equals("-nolog"))
                                                                                                            {
                                                                                                                LOG.geraLog = false;
                                                                                                            }
                                                                                                            else
                                                                                                                if (args[i].Equals("-imgdir"))
                                                                                                                {
                                                                                                                    if (i < args.Length - 1)
                                                                                                                    {
                                                                                                                        imageDir = args[++i];
                                                                                                                    }
                                                                                                                }
                                                                                                                else
                                                                                                                    if (args[i].Equals("-dreview"))
                                                                                                                    {
                                                                                                                        if (i < args.Length - 1)
                                                                                                                        {
                                                                                                                            dwfCommand = args[++i];
                                                                                                                        }
                                                                                                                    }
                                                                                                                    else
                                                                                                                        if (args[i].Equals("-audit"))
                                                                                                                        {
                                                                                                                            lAudit = true;
                                                                                                                            listall = true;
                                                                                                                        }
                                                                                                                        else
                                                                                                                            if (args[i].Equals("-getdes") && i < (args.Length - 1))
                                                                                                                            {
                                                                                                                                getdes = args[++i].ToLower().Equals("true") || args[i].ToLower().Equals("yes");
                                                                                                                            }
                                                                                                                            else
                                                                                                                                if (args[i].Equals("-getanvisa") && i < (args.Length - 1))
                                                                                                                                {
                                                                                                                                    getanvisa = args[++i].ToLower().Equals("true") || args[i].ToLower().Equals("yes");
                                                                                                                                }
                                                                                                                                else
                                                                                                                                    if (args[i].Equals("-getfda") && i < (args.Length - 1))
                                                                                                                                    {
                                                                                                                                        getfda = args[++i].ToLower().Equals("true") || args[i].ToLower().Equals("yes");
                                                                                                                                    }
                                                                                                                                    else
                                                                                                                                        /*if (args[i].Equals("-getordem") && i < (args.Length - 1))
                                                                                                                                        {
                                                                                                                                            getordem = args[++i].ToLower().Equals("true") || args[i].ToLower().Equals("yes");
                                                                                                                                        }
                                                                                                                                        else*/
                                                                                                                                            if (args[i].Equals("-getcheckedout") && i < (args.Length - 1))
                                                                                                                                            {
                                                                                                                                                getcheckedout = args[++i].ToLower().Equals("true") || args[i].ToLower().Equals("yes");
                                                                                                                                            }
                                                                                                                                            else
                                                                                                                                            {
                                                                                                                                                item = args[i];
                                                                                                                                            }
                }
            }

            if (ecmLogin != null
                && ecmPassword != null
                && ecmUser != null
                && ecmURL != null
                && ecmCompany > 0
                && ecmRootFolder > 0)
            {
                LOG.imprimeLog(System.DateTime.Now + " === Integracao com ECM habilitada");
                ecmEnabled = true;
                if (item != null && !converter)
                {
                    LOG.imprimeLog(System.DateTime.Now + " === Download do ECM habilitado");
                    ecmDownload = true;
                }
            }

            if (lAudit)
            {
                LOG.imprimeLog(System.DateTime.Now + " === WARN: Modo de auditoria");
            }

            string auditDir = downdir + "audit";
            if (lAudit && !Directory.Exists(auditDir))
            {
                LOG.imprimeLog(System.DateTime.Now + " ==== Vai criar diretorio=" + auditDir);
                Directory.CreateDirectory(auditDir);
                LOG.imprimeLog(System.DateTime.Now + " ==== Criou diretorio=" + auditDir);
            }
            string auditFile = auditDir + "\\audit.csv";
            string auditBat = auditDir + "\\auditconv.bat";

            //ADSK.SecurityService ss = null;
            try
            {
                if (!ecmDownload)
                {
                    serviceManager = new WebServiceManager((IWebServiceCredentials)new UserPasswordCredentials(Program.server, Program.vault, Program.user, Program.pass, true));
                }
                /* Efetua o Login */
                /*imprimeLog("====== Usuario.: " + user);
                imprimeLog("====== Senha...: " + pass);
                imprimeLog("====== Servidor: " + server);
                imprimeLog("====== Base....: " + vault);*/

                if (ecmEnabled)
                {
                    ecm = new ECM(ecmLogin, ecmPassword, ecmUser, ecmURL, ecmCompany, ecmRootFolder, imageDir, ecmUpload, ecmProxy);
                    if (ecm == null)
                    {
                        throw new Exception("A conexao com o ECM falhou");
                    }
                    LOG.imprimeLog(System.DateTime.Now + " ==== Instanciou o ECM");
                }

                if (ecmDownload)
                {
                    if (getanvisa || getfda || getdes)
                    {
                        getordem = false;
                    }
                    LOG.imprimeLog(System.DateTime.Now + " ==== Deve baixar do ECM");
                    LOG.imprimeLog(System.DateTime.Now + " ==== Baixar OP........: " + getordem);
                    LOG.imprimeLog(System.DateTime.Now + " ==== Baixar DES.......: " + getdes);
                    LOG.imprimeLog(System.DateTime.Now + " ==== Baixar ANVISA....: " + getanvisa);
                    LOG.imprimeLog(System.DateTime.Now + " ==== Baixar FDA.......: " + getfda);
                    LOG.imprimeLog(System.DateTime.Now + " ==== Baixar CheckedOut: " + getcheckedout);

                    try
                    {
                        string DeCodigo = item.Replace(' ', '_');
                        String ItemDir = downdir + DeCodigo;
                        string DeCodigoLog = ItemDir + "\\" + DeCodigo + ".log";
                        Dictionary<string, string> fileProps = new Dictionary<string, string>();
                        DeleteFilesFromDir(ItemDir);
                        LOG.imprimeLog(System.DateTime.Now + " ==== Limpou diretorio=" + ItemDir);
                        LOG.imprimeLog(System.DateTime.Now + " ==== Vai baixar os desenhos do ECM");
                        fileProps = ecm.downloadECMDocuments(DeCodigo, ItemDir, fileProps, getordem, getdes, getanvisa, getfda, getcheckedout);
                    }
                    catch (Exception ex)
                    {
                        sendMail("ERRO baixando do ECM o desenho '" + item + "'", ex.Message);
                    }
                    //LOG.imprimeLog(System.DateTime.Now + " ==== Vai gerar o log do desenho=" + DeCodigoLog);
                    //saveInfo(DeCodigoLog, fileProps);
                }
                else
                {
                    LOG.imprimeLog(System.DateTime.Now + " === Vai baixar do Vault");
                    LoginInfo loginInfo = new LoginInfo(Program.user, Program.pass, Program.server, Program.vault);
                    DocumentService documentService = serviceManager.DocumentService;

                    ADSK.Folder[] fld = documentService.FindFoldersByPaths(new string[] { "$/Neodent/Produção" });
                    //ADSK.Folder[] fldDesenv = documentService.FindFoldersByPaths(new string[] { "$/Neodent/Engenharia" });
                    ADSK.Folder[] fldPreset = documentService.FindFoldersByPaths(new string[] { "$/Neodent/Preset" });
                    do
                    {
                        /*if (lDesenv)
                        {
                            fld = fldDesenv;
                        }*/
                        if (lPreset)
                        {
                            fld = fldPreset;
                        }
                        if (fld != null)
                        {
                            foreach (ADSK.Folder f in fld)
                            {
                                folderIds = new long[1];
                                folderIds[0] = f.Id;
                            }
                        }
                        string filename = item + ".idw";

                        List<ADSK.File> fileList = new List<ADSK.File>();
                        List<BatchConvertItem> batchList = new List<BatchConvertItem>();

                        if (listall)
                        {
                            LOG.imprimeLog(System.DateTime.Now + " ==== Listando todos");
                            List<ADSK.File> fl = findByMatches(documentService, ".idw");
                            List<string> allf = new List<string>();

                            if (fl != null && fl.Count > 0)
                            {
                                LOG.imprimeLog(System.DateTime.Now + " ==== Arquivos .idw: " + fl.Count);
                                foreach (ADSK.File file in fl)
                                {
                                    if (file.Name.EndsWith(".idw"))
                                    {
                                        string fcode = file.Name.Substring(0, file.Name.Length - 4);
                                        if (!allf.Contains(fcode))
                                        {
                                            allf.Add(fcode);
                                            fileList.Add(file);
                                        }
                                    }
                                }
                            }
                            fl = findByMatches(documentService, ".dwg");
                            if (fl != null && fl.Count > 0)
                            {
                                LOG.imprimeLog(System.DateTime.Now + " ==== Arquivos .dwg: " + fl.Count);
                                foreach (ADSK.File file in fl)
                                {
                                    if (file.Name.EndsWith(".pdf"))
                                    {
                                        string fcode = file.Name.Substring(0, file.Name.Length - 4);
                                        if (!allf.Contains(fcode))
                                        {
                                            allf.Add(fcode);
                                            fileList.Add(file);
                                        }
                                    }
                                }
                            }
                            fl = findByMatches(documentService, ".pdf");
                            if (fl != null && fl.Count > 0)
                            {
                                LOG.imprimeLog(System.DateTime.Now + " ==== Arquivos .pdf: " + fl.Count);
                                foreach (ADSK.File file in fl)
                                {
                                    if (file.Name.EndsWith(".pdf"))
                                    {
                                        string fcode = file.Name.Substring(0, file.Name.Length - 4);
                                        if (!allf.Contains(fcode))
                                        {
                                            allf.Add(fcode);
                                            fileList.Add(file);
                                        }
                                    }
                                }
                            }
                            //fileList = null;
                        }
                        else if (checkInDate != null)
                        {
                            fileList = findByCheckinDate(documentService, checkInDate);

                            if (reconvert != null)
                            {
                                // Adiciona as imagens que deram problemas na conversao.
                                Dictionary<string, string>.KeyCollection keyColl = reconvert.Keys;
                                foreach (string s in keyColl)
                                {
                                    List<ADSK.File> fl = findByEquals(documentService, s);
                                    if (fl != null && fl.Count > 0)
                                    {
                                        foreach (ADSK.File file in fl)
                                        {
                                            if (file.Name.Equals(filename))
                                            {
                                                fileList.Add(file);
                                            }
                                        }
                                    }
                                }
                            }

                        }
                        else
                        {
                            List<ADSK.File> fl = null;
                            if (searchType == 2)
                            {
                                LOG.imprimeLog(System.DateTime.Now + " ==== Buscando desenho: " + filename);
                                fl = findByEquals(documentService, filename);
                                /*if (fl == null || fl.Count == 0)
                                {
                                    filename = item + ".dwg.dwf";
                                    fl = findByEquals(documentService, filename);
                                }*/
                                if (fl == null || fl.Count == 0)
                                {
                                    filename = item + ".dwg";
                                    LOG.imprimeLog(System.DateTime.Now + " ==== Buscando desenho: " + filename);
                                    fl = findByEquals(documentService, filename);
                                }
                                if (fl == null || fl.Count == 0)
                                {
                                    filename = item + ".pdf";
                                    LOG.imprimeLog(System.DateTime.Now + " ==== Buscando desenho: " + filename);
                                    fl = findByEquals(documentService, filename);
                                }
                            }
                            else
                            {
                                fl = findByMatches(documentService, item);
                            }
                            if (fl != null && fl.Count > 0)
                            {
                                foreach (ADSK.File file in fl)
                                {
                                    if (file.Name.Equals(filename))
                                    {
                                        fileList.Add(file);
                                    }
                                }
                            }
                        }

                        if (fileList != null && fileList.Count > 0)
                        {
                            LOG.imprimeLog(System.DateTime.Now + " ====== Desenhos encontrados: " + fileList.Count);
                            foreach (ADSK.File file in fileList)
                            {
                                string nomeImagem = file.Name;
                                if (isReconvert(nomeImagem))
                                {
                                    sendMail("AVISO: Reconvertendo imagem: " + nomeImagem, "Uma nova tentativa esta sendo feita para converter a imagem " + nomeImagem);
                                }
                                try
                                {
                                    ADSK.File fileDown = null;
                                    LOG.imprimeLog(System.DateTime.Now + " Processando arquivo: " + file.Name);
                                    Boolean alterou = false;
                                    Boolean ren = false;

                                    string DeCodigo = file.Name.Replace(' ', '_');
                                    //if (DeCodigo.ToLower().EndsWith(".idw.dwf") || DeCodigo.ToLower().EndsWith(".dwg.dwf"))
                                    if (DeCodigo.ToLower().EndsWith(".idw") || DeCodigo.ToLower().EndsWith(".dwg"))
                                    {
                                        //DeCodigo = DeCodigo.Substring(0, DeCodigo.Length - 8);
                                        DeCodigo = DeCodigo.Substring(0, DeCodigo.Length - 4);
                                        List<ADSK.File> fl = findByEquals(documentService, file.Name + ".dwf");
                                        if (fl != null && fl.Count > 0)
                                        {
                                            fileDown = fl.ToArray()[0];
                                        }
                                    }
                                    else
                                    {
                                        if (DeCodigo.EndsWith(".dwf"))
                                        {
                                            DeCodigo = DeCodigo.Substring(0, DeCodigo.Length - 4);
                                            fileDown = file;
                                        }
                                        else if (DeCodigo.EndsWith(".pdf"))
                                        {
                                            DeCodigo = DeCodigo.Substring(0, DeCodigo.Length - 4);
                                            fileDown = file;
                                        }
                                    }
                                    if (fileDown == null)
                                    {
                                        LOG.imprimeLog(System.DateTime.Now + " ====== Nao achou DWF, ignorando arquivo");
                                        continue;
                                    }

                                    String ItemDir = downdir + DeCodigo;
                                    LOG.imprimeLog(System.DateTime.Now + " ===== ItemDir=" + ItemDir);

                                    if (!Directory.Exists(ItemDir))
                                    {
                                        Directory.CreateDirectory(ItemDir);
                                        LOG.imprimeLog(System.DateTime.Now + " ==== Criou diretorio=" + ItemDir);
                                        alterou = true;
                                    }

                                    String ItemFile = ItemDir + "\\" + fileDown.Name;
                                    string DeCodigoLog = ItemDir + "\\" + DeCodigo + ".log";
                                    LOG.imprimeLog(System.DateTime.Now + " ==== Arquivo de log=" + DeCodigoLog);

                                    if (!System.IO.File.Exists(DeCodigoLog))
                                    {
                                        LOG.imprimeLog(System.DateTime.Now + " ==== Arquivo de log ainda nao existia=" + DeCodigoLog);
                                        alterou = true;
                                    }
                                    else
                                    {
                                        Dictionary<string, string> d = Util.ReadPropertyFile(DeCodigoLog);
                                        if (Util.GetProperty(d, "CkInDate") == null
                                            || !Util.GetProperty(d, "CkInDate").Equals(file.CkInDate.ToUniversalTime().ToString("MM/dd/yyyy HH:mm:ss"))
                                            || Util.GetProperty(d, "Cksum") == null
                                            || !Util.GetProperty(d, "Cksum").Equals(file.Cksum.ToString())
                                            || Util.GetProperty(d, "FileSize") == null
                                            || !Util.GetProperty(d, "FileSize").Equals(file.FileSize.ToString())
                                            )
                                        {
                                            alterou = true;
                                        }
                                    }

                                    Dictionary<string, string> fileProps = new Dictionary<string, string>();

                                    //filename = file.Name;

                                    if (lAudit)
                                    {
                                        LOG.imprimeLog(System.DateTime.Now + " ==== Modo auditoria");
                                        AuditItem auditIt = new AuditItem();
                                        auditIt.item = DeCodigo;
                                        auditIt.checkinDate = file.CkInDate != null ? file.CkInDate.ToUniversalTime().ToString("MM/dd/yyyy HH:mm:ss") : "NULL";
                                        auditIt.checkedOut = file.CheckedOut.ToString();
                                        audits.Add(auditIt);
                                        try
                                        {

                                            if (ecm.downloadItemLog(DeCodigo, auditDir))
                                            {
                                                DeCodigoLog = auditDir + "\\" + DeCodigo + ".log";
                                                Dictionary<string, string> d = Util.ReadPropertyFile(DeCodigoLog);
                                                auditIt.fluigCheckinDate = Util.GetProperty(d, "CkInDate");
                                                auditIt.fluigCheckedOut = Util.GetProperty(d, "CheckedOut");
                                                if (!auditIt.checkedOut.Equals(auditIt.fluigCheckedOut))
                                                {
                                                    auditIt.message = "Status checkout diferente";
                                                } else if (!auditIt.checkinDate.Equals(auditIt.fluigCheckinDate))
                                                {
                                                    auditIt.message = "Data de checkin diferente";
                                                }
                                                else
                                                {
                                                    auditIt.message = "OK";
                                                }
                                                DeleteFile(DeCodigoLog);
                                            }
                                            else
                                            {
                                                auditIt.message = "Nao achou o arquivo de LOG no fluig";
                                            }
                                        }
                                        catch (Exception exDown)
                                        {
                                            auditIt.message = exDown.Message;
                                        }
                                    }
                                    else
                                    {
                                        if (download && alterou)
                                        {
                                            DeleteFilesFromDir(ItemDir);
                                            LOG.imprimeLog(System.DateTime.Now + " ==== Limpou diretorio=" + ItemDir);
                                            DownloadFile(fileDown, ItemFile, documentService);
                                            LOG.imprimeLog(System.DateTime.Now + " ==== Baixou arquivo=" + ItemFile);
                                            if (ItemFile.ToLower().EndsWith(".dwf"))
                                            {
                                                try
                                                {
                                                    fileProps = extract(ItemDir, ItemFile, fileProps);
                                                    if (converter)
                                                    {
                                                        if (!single)
                                                        {
                                                            StringBuilder sb = new StringBuilder();
                                                            sb.Append("<configuration_file>");
                                                            sb.Append(AddFileToBpj(ItemFile));
                                                            sb.Append("</configuration_file>");

                                                            StreamWriter sw = new StreamWriter(ItemFile + ".bpj");
                                                            sw.Write(sb.ToString());
                                                            sw.Flush();
                                                            sw.Close();
                                                            sw.Dispose();
                                                            LOG.imprimeLog(System.DateTime.Now + " === Arquivo bpj: " + sb.ToString());

                                                            /*if (System.IO.File.Exists(imageDir + "\\execok.exe.txt"))
                                                            {
                                                                DeleteFile(imageDir + "\\execok.exe.txt");
                                                            }*/

                                                            bool bOk = false;
                                                            System.Diagnostics.Process proc = new System.Diagnostics.Process();
                                                            proc.StartInfo.FileName = dwfCommand;
                                                            proc.StartInfo.Arguments = /*"\"" +*/ ItemFile + ".bpj" /*+ "\""*/;
                                                            proc.StartInfo.UseShellExecute = false;
                                                            proc.StartInfo.RedirectStandardOutput = false;
                                                            LOG.imprimeLog(System.DateTime.Now + " ==== Vai converter=" + dwfCommand + " " + proc.StartInfo.Arguments);
                                                            Exception exception = null;
                                                            for (int i = 0; i < 3; i++)
                                                            {
                                                                try
                                                                {
                                                                    proc.Start();
                                                                    exception = null;
                                                                }
                                                                catch (Exception ex)
                                                                {
                                                                    LOG.imprimeLog(System.DateTime.Now + " ========= Nao conseguiu executar o Design Review: " + ex.Message);
                                                                    exception = ex;
                                                                    if (i < 2)
                                                                    {
                                                                        System.Threading.Thread.Sleep(2000);
                                                                        LOG.imprimeLog(System.DateTime.Now + " ========= Esperando 2 segundos antes de tentar novamente");
                                                                    }
                                                                }
                                                            }
                                                            if (exception != null)
                                                            {
                                                                throw exception;
                                                            }
                                                            LOG.imprimeLog(System.DateTime.Now + " ====== Iniciou processo de conversao");
                                                            proc.WaitForExit(60000);
                                                            LOG.imprimeLog(System.DateTime.Now + " ====== Expirou os 60000 ms");
                                                            if (!proc.HasExited)
                                                            {
                                                                LOG.imprimeLog(System.DateTime.Now + " ====== ERRO executando DesignReview, tentando fechar");
                                                                proc.Kill();
                                                            }
                                                            else
                                                            {
                                                                // Espera a imagem começar a ser gerada pelo driver.
                                                                for (int i = 0; i < 30; i++)
                                                                {
                                                                    LOG.imprimeLog(System.DateTime.Now + " ====== Aguardando inicio da impressao: " + i);
                                                                    if (HasPrintJobs(printerName))
                                                                    {
                                                                        i = 30;
                                                                        bOk = true;
                                                                    }
                                                                    else
                                                                    {
                                                                        String[] files = Directory.GetFiles(imageDir);
                                                                        if (files != null && files.Length > 0)
                                                                        {
                                                                            LOG.imprimeLog(System.DateTime.Now + " ====== Nao achou impressao, mas achou arquivos");
                                                                            for (int j = 0; j < files.Length; j++)
                                                                            {
                                                                                if (files[j].ToLower().EndsWith(".jpg"))
                                                                                {
                                                                                    j = files.Length;
                                                                                    bOk = true;
                                                                                    i = 30;
                                                                                }
                                                                            }
                                                                        }
                                                                        else
                                                                        {
                                                                            System.Threading.Thread.Sleep(1000);
                                                                        }
                                                                    }
                                                                }
                                                            }
                                                            if (!bOk)
                                                            {
                                                                throw new Exception("Nao conseguiu iniciar a impressao para gerar os JPG");
                                                            }

                                                            // Espera a imagem terminar de ser gerada pelo driver
                                                            LOG.imprimeLog(System.DateTime.Now + " ===== Diretorio para salvar imagens: " + imageDir);
                                                            bOk = false;
                                                            for (int i = 0; i < 30; i++)
                                                            {
                                                                LOG.imprimeLog(System.DateTime.Now + " ====== Aguardando termino da impressao: " + i);
                                                                if (!HasPrintJobs(printerName))
                                                                {
                                                                    i = 30;
                                                                    bOk = true;
                                                                }
                                                                else
                                                                {
                                                                    System.Threading.Thread.Sleep(1000);
                                                                }
                                                            }
                                                            if (!bOk)
                                                            {
                                                                throw new Exception("Nao conseguiu concluir a impressao para gerar os JPG");
                                                            }
                                                            LOG.imprimeLog(System.DateTime.Now + " ==== Converteu");

                                                            ren = true;
                                                        }
                                                    }
                                                }
                                                catch (Exception ex)
                                                {
                                                    LOG.imprimeLog(System.DateTime.Now + " =========== Error extraindo arquivos=" + ex.Message);
                                                    for (int i = 0; i < ex.StackTrace.Length; i++)
                                                    {
                                                        LOG.imprimeLog("StackTrace: " + ex.StackTrace);
                                                    }
                                                    if (isReconvert(nomeImagem))
                                                    {
                                                        sendMail("ERRO RECONVERTENDO desenho: " + nomeImagem, ex.Message);
                                                    }
                                                    else
                                                    {
                                                        addReconvert(nomeImagem);
                                                        sendMail("ERRO convertendo desenho: " + nomeImagem, ex.Message);
                                                    }
                                                    continue;
                                                }
                                            }
                                            else if (ItemFile.ToLower().EndsWith(".pdf"))
                                            {
                                                if (converter)
                                                {
                                                    LOG.imprimeLog(System.DateTime.Now + " =========== Vai converter um PDF. Comando: " + pdfCommand);
                                                    System.Diagnostics.Process proc = new System.Diagnostics.Process();
                                                    proc.StartInfo.FileName = pdfCommand;
                                                    proc.StartInfo.Arguments = "--dest=\"" + imageDir + "\" --format=1 --src=\"" + ItemFile + "\"";
                                                    proc.StartInfo.UseShellExecute = false;
                                                    proc.StartInfo.RedirectStandardOutput = false;
                                                    LOG.imprimeLog(System.DateTime.Now + " =========== Iniciando conversao do PDF: " + proc.StartInfo.Arguments);
                                                    proc.Start();
                                                    proc.WaitForExit();
                                                    LOG.imprimeLog(System.DateTime.Now + " =========== PDF convertido");
                                                    int cont = 0;
                                                    String[] files = Directory.GetFiles(imageDir);
                                                    if (files != null && files.Length > 0)
                                                    {
                                                        foreach (string f in files)
                                                        {
                                                            if (f.EndsWith(".jpg"))
                                                            {
                                                                cont++;
                                                                if (lDesenv)
                                                                {
                                                                    Util.SetProperty(fileProps, "" + cont, "DES=" + cont);
                                                                }
                                                                else if (lPreset)
                                                                {
                                                                    Util.SetProperty(fileProps, "" + cont, "PS=" + cont);
                                                                }
                                                                else
                                                                {
                                                                    Util.SetProperty(fileProps, "" + cont, "OP=" + cont);
                                                                }
                                                            }
                                                        }
                                                    }

                                                    ren = true;
                                                }
                                            }
                                            else
                                            {
                                                LOG.imprimeLog(System.DateTime.Now + " ======= ERRO: " + ItemFile + " NAO ESTA EM UM FORMATO CONHECIDO");
                                            }
                                        }

                                        if (single && ItemFile.ToLower().EndsWith(".dwf") && download && alterou)
                                        {
                                            BatchConvertItem it = new BatchConvertItem();
                                            it.ItemFile = ItemFile;
                                            it.file = file;
                                            it.fileDown = fileDown;
                                            it.fileLog = DeCodigoLog;
                                            it.props = fileProps;
                                            it.imageDir = imageDir;
                                            it.ItemDir = ItemDir;
                                            it.DeCodigo = DeCodigo;
                                            batchList.Add(it);
                                        }
                                        else
                                        {
                                            if (ecmEnabled && download && alterou)
                                            {
                                                ecm.deleteECMDocument(DeCodigo);
                                            }
                                            if (alterou || file.CheckedOut)
                                            {
                                                LOG.imprimeLog(System.DateTime.Now + " ==== Vai gerar o log do desenho (1)=" + DeCodigoLog);
                                                showInfo(file, fileDown, DeCodigoLog, fileProps);
                                                if (ecmEnabled)
                                                {
                                                    LOG.imprimeLog(System.DateTime.Now + " ==== Vai fazer upload para o ECM");
                                                    ecm.updateECMDocument(DeCodigo, DeCodigoLog);
                                                }

                                            }
                                            LOG.imprimeLog(System.DateTime.Now + " ==== download=" + download + ", alterou=" + alterou);
                                            if (download && alterou)
                                            {
                                                LOG.imprimeLog(System.DateTime.Now + " ==== Vai renomear os jpg");
                                                DeleteRenameFilesFromDir(imageDir, ItemDir, DeCodigo, delFiles, ren /*&& !fileDown.Name.EndsWith(".pdf")*/);
                                            }
                                        }
                                    }

                                }
                                catch (Exception ex)
                                {
                                    if (isReconvert(nomeImagem))
                                    {
                                        sendMail("ERRO RECONVERTENDO desenho: " + nomeImagem, ex.Message);
                                    }
                                    else
                                    {
                                        addReconvert(nomeImagem);
                                        sendMail("ERRO convertendo desenho: " + nomeImagem, ex.Message);
                                    }
                                }
                            }
                        }

                        if (batchList != null && batchList.Count > 0)
                        {
                            // Divide em lotes
                            int MAX = 10;

                            while (batchList.Count > 0)
                            {
                                List<BatchConvertItem> bList = new List<BatchConvertItem>();

                                while (bList.Count < MAX && batchList.Count > 0)
                                {
                                    bList.Add(batchList.ToArray()[0]);
                                    batchList.RemoveAt(0);
                                }

                                StringBuilder sb = new StringBuilder();
                                sb.Append("<configuration_file>");
                                foreach (BatchConvertItem it in bList)
                                {
                                    sb.Append(AddFileToBpj(it.ItemFile));
                                }
                                sb.Append("</configuration_file>");

                                string convfile = downdir + "converte.bpj";

                                StreamWriter sw = new StreamWriter(convfile);
                                sw.Write(sb.ToString());
                                sw.Flush();
                                sw.Close();
                                sw.Dispose();
                                LOG.imprimeLog(System.DateTime.Now + " === Arquivo bpj: " + sb.ToString());

                                /*if (System.IO.File.Exists(imageDir + "\\execok.exe.txt"))
                                {
                                    DeleteFile(imageDir + "\\execok.exe.txt");
                                }*/

                                System.Diagnostics.Process proc = new System.Diagnostics.Process();
                                proc.StartInfo.FileName = dwfCommand;
                                proc.StartInfo.Arguments = convfile;
                                proc.StartInfo.UseShellExecute = false;
                                proc.StartInfo.RedirectStandardOutput = false;
                                LOG.imprimeLog(System.DateTime.Now + " ==== Vai converter=" + dwfCommand + " " + proc.StartInfo.Arguments);
                                proc.Start();
                                proc.WaitForExit();
                                // Espera a imagem ser gerada pelo driver
                                LOG.imprimeLog(System.DateTime.Now + " ===== Diretorio para salvar imagens: " + imageDir);
                                for (int i = 0; i < (30 * bList.Count); i++)
                                {
                                    LOG.imprimeLog(System.DateTime.Now + " ====== Aguardando inicio da impressao: " + i);
                                    if (HasPrintJobs(printerName))
                                    {
                                        i = 30 * bList.Count;
                                    }
                                    else
                                    {
                                        System.Threading.Thread.Sleep(1000);
                                    }
                                }
                                for (int i = 0; i < (30 * bList.Count); i++)
                                {
                                    LOG.imprimeLog(System.DateTime.Now + " ====== Aguardando término da impressao: " + i);
                                    if (!HasPrintJobs(printerName))
                                    {
                                        i = 30 * bList.Count;
                                    }
                                    else
                                    {
                                        System.Threading.Thread.Sleep(1000);
                                    }
                                }
                                LOG.imprimeLog(System.DateTime.Now + " ==== Converteu");

                                foreach (BatchConvertItem it in bList)
                                {
                                    LOG.imprimeLog(System.DateTime.Now + " ==== Vai gerar o log do desenho (2)=" + it.fileLog);
                                    /*if (ecmEnabled)
                                    {
                                        ecm.deleteECMDocument(basename);
                                    }*/
                                    showInfo(it.file, it.fileDown, it.fileLog, it.props);

                                    LOG.imprimeLog(System.DateTime.Now + " ==== Vai renomear os jpg");
                                    DeleteRenameFilesFromDir(it);
                                }
                            }
                        }
                        //lDesenv = (!lDesenv);
                        //lDesenv = false;
                        lPreset = (!lPreset);
                        //} while (lDesenv);
                    } while (lPreset);

                    //ss.SignOut();
                }
            }
            catch (Exception ex)
            {
                LOG.imprimeLog(System.DateTime.Now + " Error=" + ex.Message);
                LOG.imprimeLog("StackTrace: " + ex.StackTrace);
                erro = true;
                sendMail("ERRO convertendo desenhos", ex.Message);
            }
            if (!erro && !lAudit)
            {
                LOG.imprimeLog(System.DateTime.Now + " Vai salvar arquivo de configuracao=" + downdir + "vaultsrv.conf");
                Util.WritePropertyFile(downdir + "vaultsrv.conf", config);
            }
            if (reconvertNew != null && !lAudit)
            {
                Util.WritePropertyFile("reconvert.conf", reconvertNew);
            }
            if (lAudit)
            {
                LOG.imprimeLog(System.DateTime.Now + " Vai salvar arquivo de auditoria");
                WriteAuditLog(auditFile);
                WriteAuditBat(auditBat);
            }
            if (serviceManager != null)
            {
                serviceManager.Dispose();
            }
            LOG.imprimeLog(System.DateTime.Now + " Fim --------------------------------------");

            //Console.WriteLine("Fim --------------------------------------");
            //Console.Write("Pressione enter para terminar");
            //Console.ReadLine();
        }
 public _TestController()
 {
     var CoreServiceUrl = System.Web.Configuration.WebConfigurationManager.AppSettings["FSLLCoreServiceURL"];
     _wsCoreManager = new WebServiceManager(CoreServiceUrl);
 }