/// <summary> /// Finds the record based on id of the EquipmentMaintenance. /// </summary> /// <param name="filePath"></param> /// <param name="equipMaintenanceID"></param> /// <returns></returns> public EquipmentMaintenance Find(int equipMaintenanceID) { FileOperations objEquipMaintenanceDB = new FileOperations(); EquipmentMaintenance objEquipMaintenance = new EquipmentMaintenance(); List<EquipmentMaintenance> objEquipMaintenanceColl = SelectAllData(); return objEquipMaintenanceColl.FirstOrDefault(equipMaintenance => equipMaintenance.MaintenanceWorkId == equipMaintenanceID); }
public bool AddRecord(EquipmentMaintenance objEquipMaintenance) { FileOperations objEquipMaintenanceDB = new FileOperations(); string data = (GetMaxID() + 1).ToString() + "," + objEquipMaintenance.Date.Date.ToString("dd/MM/yyyy") +","+ objEquipMaintenance.Time+","+objEquipMaintenance.WorksDescription+","+objEquipMaintenance.ObjEquip.ID.ToString()+"," +objEquipMaintenance.TimeTaken.ToString(); return objEquipMaintenanceDB.Add(EquipmentMaintenaceFilePath, data); }
public ShellFileOperation() { // set default properties Operation = FileOperations.FO_COPY; OwnerWindow = IntPtr.Zero; OperationFlags = ShellFileOperationFlags.FOF_ALLOWUNDO | ShellFileOperationFlags.FOF_MULTIDESTFILES | ShellFileOperationFlags.FOF_NO_CONNECTED_ELEMENTS | ShellFileOperationFlags.FOF_WANTNUKEWARNING; ProgressTitle = ""; }
public void TransformWithFileNames(string[] files, string indexPath, HashSet <string> searchHashSet, SearchSpinn3rType searchType) { double tweetCnt = 0; TokenizeConfig tokenizeConfig = new TokenizeConfig(TokenizerType.Twitter); var indexWriter = LuceneOperations.GetIndexWriter(indexPath); var progress = new ProgramProgress(files.Length); int docFoundCount = 0; int totalDocCount = 0; foreach (var file in files) { FileOperations.ReadJsonFile <Spinn3rTwitterData>(file, (data) => { tweetCnt += data.count; //Console.WriteLine(data.count); //Console.WriteLine(data.items[0].main); foreach (var tweet in data.items) { if (tweet.lang != "en") { continue; } bool isContainSearch = false; switch (searchType) { case SearchSpinn3rType.Main: var words = NLPOperations.Tokenize(tweet.main, tokenizeConfig); foreach (var word in words) { if (searchHashSet.Contains(word)) { isContainSearch = true; break; } } break; case SearchSpinn3rType.User: isContainSearch = searchHashSet.Contains(tweet.author_link.ToLower()); break; default: throw new ArgumentException(); } if (isContainSearch) { var document = new Document(); document.Add(new Field(TweetFields.TweetId, tweet.permalink, Field.Store.YES, Field.Index.ANALYZED)); document.Add(new Field(TweetFields.Text, tweet.main, Field.Store.YES, Field.Index.ANALYZED)); document.Add(new Field(TweetFields.UserScreenName, tweet.author_link, Field.Store.YES, Field.Index.ANALYZED)); document.Add(new Field(TweetFields.UserName, tweet.author_name, Field.Store.YES, Field.Index.ANALYZED)); document.Add(new Field(TweetFields.Tags, StringOperations.ConvertNullStringToEmpty(StringOperations.GetMergedString(tweet.tags)), Field.Store.YES, Field.Index.ANALYZED)); document.Add(new Field(TweetFields.CreatedAt, tweet.published, Field.Store.YES, Field.Index.ANALYZED)); document.Add(new Field(TweetFields.Location, tweet.source_location, Field.Store.YES, Field.Index.ANALYZED)); document.Add(new Field(TweetFields.UserDescription, tweet.source_description, Field.Store.YES, Field.Index.ANALYZED)); document.Add(new Field(TweetFields.UserFollowersCount, tweet.source_followers.ToString(), Field.Store.YES, Field.Index.ANALYZED)); document.Add(new Field(TweetFields.UserFriendsCount, tweet.source_following.ToString(), Field.Store.YES, Field.Index.ANALYZED)); indexWriter.AddDocument(document); docFoundCount++; } totalDocCount++; } }); progress.PrintIncrementExperiment(string.Format("docFound: {0} out of {1} ({2}%)", docFoundCount, totalDocCount, 100 * docFoundCount / totalDocCount)); } progress.PrintTotalTime(); Console.WriteLine("Final docFound: {0} out of {1} ({2}%)", docFoundCount, totalDocCount, 100 * docFoundCount / totalDocCount); Console.WriteLine("Start writing index..."); indexWriter.Commit(); indexWriter.Close(); Util.ProgramFinishHalt(); }
/// <summary> /// This method is used to upload a file and print the response. /// </summary> public static void UploadFiles() { //Get instance of RecordOperations Class FileOperations fileOperations = new FileOperations(); //Get instance of FileBodyWrapper Class that will contain the request body BodyWrapper bodyWrapper = new BodyWrapper(); //Get instance of StreamWrapper class that takes absolute path of the file to be attached as parameter StreamWrapper streamWrapper = new StreamWrapper("/Users/Desktop/py.html"); //Get instance of StreamWrapper class that takes absolute path of the file to be attached as parameter StreamWrapper streamWrapper1 = new StreamWrapper("/Users/Desktop/download.png"); //Get instance of StreamWrapper class that takes absolute path of the file to be attached as parameter StreamWrapper streamWrapper2 = new StreamWrapper("/Users/Desktop/samplecode.txt"); //Set file to the FileBodyWrapper instance bodyWrapper.File = new List <StreamWrapper>() { streamWrapper, streamWrapper1, streamWrapper2 }; //Get instance of ParameterMap Class ParameterMap paramInstance = new ParameterMap(); //Call uploadFile method that takes BodyWrapper instance as parameter. APIResponse <ActionHandler> response = fileOperations.UploadFiles(bodyWrapper, paramInstance); if (response != null) { //Get the status code from response Console.WriteLine("Status Code: " + response.StatusCode); //Check if expected response is received if (response.IsExpected) { //Get object from response ActionHandler actionHandler = response.Object; if (actionHandler is ActionWrapper) { //Get the received ActionWrapper instance ActionWrapper actionWrapper = (ActionWrapper)actionHandler; //Get the list of obtained action responses List <ActionResponse> actionResponses = actionWrapper.Data; foreach (ActionResponse actionResponse in actionResponses) { //Check if the request is successful if (actionResponse is SuccessResponse) { //Get the received SuccessResponse instance SuccessResponse successResponse = (SuccessResponse)actionResponse; //Get the Status Console.WriteLine("Status: " + successResponse.Status.Value); //Get the Code Console.WriteLine("Code: " + successResponse.Code.Value); Console.WriteLine("Details: "); //Get the details map foreach (KeyValuePair <string, object> entry in successResponse.Details) { //Get each value in the map Console.WriteLine(entry.Key + " : " + JsonConvert.SerializeObject(entry.Value)); } //Get the Message Console.WriteLine("Message: " + successResponse.Message.Value); } //Check if the request returned an exception else if (actionResponse is APIException) { //Get the received APIException instance APIException exception = (APIException)actionResponse; //Get the Status Console.WriteLine("Status: " + exception.Status.Value); //Get the Code Console.WriteLine("Code: " + exception.Code.Value); Console.WriteLine("Details: "); //Get the details map foreach (KeyValuePair <string, object> entry in exception.Details) { //Get each value in the map Console.WriteLine(entry.Key + ": " + JsonConvert.SerializeObject(entry.Value)); } //Get the Message Console.WriteLine("Message: " + exception.Message.Value); } } } //Check if the request returned an exception else if (actionHandler is APIException) { //Get the received APIException instance APIException exception = (APIException)actionHandler; //Get the Status Console.WriteLine("Status: " + exception.Status.Value); //Get the Code Console.WriteLine("Code: " + exception.Code.Value); Console.WriteLine("Details: "); //Get the details map foreach (KeyValuePair <string, object> entry in exception.Details) { //Get each value in the map Console.WriteLine(entry.Key + ": " + JsonConvert.SerializeObject(entry.Value)); } //Get the Message Console.WriteLine("Message: " + exception.Message.Value); } } else { //If response is not as expected //Get model object from response Model responseObject = response.Model; //Get the response object's class Type type = responseObject.GetType(); //Get all declared fields of the response class Console.WriteLine("Type is: {0}", type.Name); PropertyInfo[] props = type.GetProperties(); Console.WriteLine("Properties (N = {0}):", props.Length); foreach (var prop in props) { if (prop.GetIndexParameters().Length == 0) { Console.WriteLine("{0} ({1}) : {2}", prop.Name, prop.PropertyType.Name, prop.GetValue(responseObject)); } else { Console.WriteLine("{0} ({1}) : <Indexed>", prop.Name, prop.PropertyType.Name); } } } } }
private async void Button_Create_Click(object sender, RoutedEventArgs e) { tmpInfo.Title = textboxTitle.Text; tmpInfo.Author = textboxAuthor.Text; tmpInfo.Desc = textboxDesc.Text; tmpInfo.Contact = textboxWebsite.Text; tmpInfo.License = textboxLicense.Text; //tmpInfo.Type = (SetupDesktop.WallpaperType)comboBoxType.SelectedItem; tmpInfo.Type = wallpaperTypes[comboBoxType.SelectedIndex].Type; tmpInfo.Arguments = textboxArgs.Text; if (folderContents.Count == 0 || String.IsNullOrWhiteSpace(tmpInfo.FileName)) { MessageBox.Show(Properties.Resources.txtMsgSelectWallpaperFile); return; } if (String.IsNullOrEmpty(tmpInfo.Title) || String.IsNullOrEmpty(tmpInfo.Desc) || String.IsNullOrEmpty(tmpInfo.Author) ) //|| String.IsNullOrEmpty(tmpInfo.contact) ) { MessageBox.Show(Properties.Resources.txtMsgFillAllFields); return; } /* * //Optional * if( !File.Exists(tmpInfo.Thumbnail) || !File.Exists(tmpInfo.Preview) ) * { * MessageBox.Show(Properties.Resources.txtSelectPreviewThumb); * return; * } */ SaveFileDialog saveFileDialog1 = new SaveFileDialog { Title = "Select location to save the file", Filter = "Lively/zip file|*.zip", OverwritePrompt = true }; if (saveFileDialog1.ShowDialog() == true) { if (!String.IsNullOrEmpty(saveFileDialog1.FileName)) { //to write to Livelyinfo.json file only, tmp object. SaveData.LivelyInfo tmp = new SaveData.LivelyInfo(tmpInfo); tmp.FileName = Path.GetFileName(tmp.FileName); tmp.Preview = Path.GetFileName(tmp.Preview); tmp.Thumbnail = Path.GetFileName(tmp.Thumbnail); SaveData.SaveWallpaperMetaData(tmp, Path.Combine(App.PathData, "tmpdata")); /* * //if previous livelyinfo.json file(s) exists in wallpaper directory, remove all of them. * folderContents.RemoveAll(x => Path.GetFileName(x).Equals(Path.GetFileName(folderContents[folderContents.Count - 1]), * StringComparison.InvariantCultureIgnoreCase)); */ folderContents.Add(Path.Combine(App.PathData, "tmpdata", "LivelyInfo.json")); //btnCreateWallpaer.IsEnabled = false; await CreateZipFile(saveFileDialog1.FileName, folderContents); string folderPath = System.IO.Path.GetDirectoryName(saveFileDialog1.FileName); if (Directory.Exists(folderPath)) { ProcessStartInfo startInfo = new ProcessStartInfo { Arguments = folderPath, FileName = "explorer.exe" }; Process.Start(startInfo); } //clearing temp files if any. FileOperations.EmptyDirectory(Path.Combine(App.PathData, "SaveData", "wptmp")); //this.NavigationService.GoBack(); //won't work, since prev is window, not page. var wnd = Window.GetWindow(this); wnd.Close(); } } else { return; } }
private void NormalizeChordTypes() { _currentSong.ContentText = FileOperations.Transpose(_currentSong.ContentText, TransposeDirection.Up, 0, chkUseSharps.Active); txtEditor.Buffer.Text = _currentSong.ContentText; }
private async Task UpdateSavedQueryXml(IOrganizationServiceExtented service, CommonConfiguration commonConfig, XDocument doc, string filePath, SavedQuery savedQuery) { string fieldName = SavedQueryRepository.GetFieldNameByXmlRoot(doc.Root.Name.ToString()); string fieldTitle = SavedQueryRepository.GetFieldTitleByXmlRoot(doc.Root.Name.ToString()); if (string.Equals(fieldName, SavedQuery.Schema.Attributes.layoutxml, StringComparison.InvariantCulture) && !string.IsNullOrEmpty(savedQuery.ReturnedTypeCode) ) { var entityData = service.ConnectionData.GetEntityIntellisenseData(savedQuery.ReturnedTypeCode); if (entityData != null && entityData.ObjectTypeCode.HasValue) { XAttribute attr = doc.Root.Attribute("object"); if (attr != null) { attr.Value = entityData.ObjectTypeCode.ToString(); } } } { string xmlContent = savedQuery.GetAttributeValue <string>(fieldName); if (!string.IsNullOrEmpty(xmlContent)) { commonConfig.CheckFolderForExportExists(this._iWriteToOutput); string fileNameBackUp = EntityFileNameFormatter.GetSavedQueryFileName(service.ConnectionData.Name, savedQuery.ReturnedTypeCode, savedQuery.Name, fieldTitle + " BackUp", FileExtension.xml); string filePathBackUp = Path.Combine(commonConfig.FolderForExport, FileOperations.RemoveWrongSymbols(fileNameBackUp)); try { xmlContent = ContentComparerHelper.FormatXmlByConfiguration( xmlContent , commonConfig , XmlOptionsControls.SavedQueryXmlOptions , schemaName: AbstractDynamicCommandXsdSchemas.FetchSchema , savedQueryId: savedQuery.Id , entityName: savedQuery.ReturnedTypeCode ); File.WriteAllText(filePathBackUp, xmlContent, new UTF8Encoding(false)); this._iWriteToOutput.WriteToOutput(service.ConnectionData, Properties.OutputStrings.InConnectionEntityFieldExportedToFormat5, service.ConnectionData.Name, SavedQuery.Schema.EntityLogicalName, savedQuery.Name, fieldTitle, filePathBackUp); } catch (Exception ex) { this._iWriteToOutput.WriteErrorToOutput(service.ConnectionData, ex); } } else { this._iWriteToOutput.WriteToOutput(service.ConnectionData, Properties.OutputStrings.InConnectionEntityFieldIsEmptyFormat4, service.ConnectionData.Name, SavedQuery.Schema.EntityLogicalName, savedQuery.Name, fieldTitle); this._iWriteToOutput.ActivateOutputWindow(service.ConnectionData); } } var newText = doc.ToString(SaveOptions.DisableFormatting); if (string.Equals(fieldName, SavedQuery.Schema.Attributes.fetchxml, StringComparison.InvariantCulture)) { try { _iWriteToOutput.WriteToOutput(service.ConnectionData, Properties.OutputStrings.ExecutingValidateSavedQueryRequest); var request = new ValidateSavedQueryRequest() { FetchXml = newText, QueryType = savedQuery.QueryType.GetValueOrDefault() }; service.Execute(request); } catch (Exception ex) { this._iWriteToOutput.WriteErrorToOutput(service.ConnectionData, ex); } } _iWriteToOutput.WriteToOutput(service.ConnectionData, Properties.OutputStrings.SavingEntityFormat1, savedQuery.LogicalName); _iWriteToOutput.WriteToOutputEntityInstance(service.ConnectionData, savedQuery.LogicalName, savedQuery.Id); var updateEntity = new SavedQuery { Id = savedQuery.Id, }; updateEntity.Attributes[fieldName] = newText; await service.UpdateAsync(updateEntity); _iWriteToOutput.WriteToOutput(service.ConnectionData, Properties.OutputStrings.SavingEntityCompletedFormat1, savedQuery.LogicalName); _iWriteToOutput.WriteToOutput(service.ConnectionData, Properties.OutputStrings.InConnectionPublishingEntitiesFormat2, service.ConnectionData.Name, savedQuery.ReturnedTypeCode); { var repositoryPublish = new PublishActionsRepository(service); await repositoryPublish.PublishEntitiesAsync(new[] { savedQuery.ReturnedTypeCode }); } service.TryDispose(); }
private async Task CreatingAllDependencyNodesDescription(ConnectionData connectionData, CommonConfiguration commonConfig) { var service = await ConnectAndWriteToOutputAsync(connectionData); if (service == null) { return; } StringBuilder content = new StringBuilder(); content.AppendLine(Properties.OutputStrings.ConnectingToCRM); content.AppendLine(connectionData.GetConnectionDescription()); content.AppendFormat(Properties.OutputStrings.CurrentServiceEndpointFormat1, service.CurrentServiceEndpoint).AppendLine(); var hash = new HashSet <Tuple <int, Guid> >(); { var repository = new DependencyNodeRepository(service); var components = await repository.GetDistinctListAsync(); foreach (var item in components.Where(en => en.ComponentType != null && en.ObjectId.HasValue)) { hash.Add(Tuple.Create(item.ComponentType.Value, item.ObjectId.Value)); } } if (hash.Any()) { content.AppendLine().AppendLine(); var solutionComponents = hash.Select(e => new SolutionComponent { ComponentType = new OptionSetValue(e.Item1), ObjectId = e.Item2, }).ToList(); var descriptor = new SolutionComponentDescriptor(service); descriptor.WithUrls = true; descriptor.WithManagedInfo = true; descriptor.WithSolutionsInfo = true; descriptor.MetadataSource.DownloadEntityMetadata(); var desc = await descriptor.GetSolutionComponentsDescriptionAsync(solutionComponents); content.AppendLine(desc); commonConfig.CheckFolderForExportExists(this._iWriteToOutput); string fileName = string.Format( "{0}.Dependency Nodes Description at {1}.txt" , connectionData.Name , DateTime.Now.ToString("yyyy.MM.dd HH-mm-ss") ); string filePath = Path.Combine(commonConfig.FolderForExport, FileOperations.RemoveWrongSymbols(fileName)); File.WriteAllText(filePath, content.ToString(), new UTF8Encoding(false)); this._iWriteToOutput.WriteToOutput(connectionData, "Dependency Nodes Description were exported to {0}", filePath); this._iWriteToOutput.PerformAction(service.ConnectionData, filePath); } }
public void Load() { FileOperations.LoadConfiguration(this, FILE_NAME); }
public bool FileOperation(FileOperations mode, bool recycle) { return FileOperation(mode, null, null, null, recycle); }
public bool DeleteRecord(int id) { FileOperations objEquipMaintenanceDB = new FileOperations(); ArrayList lines = Delete(id); //This searches the targeted id and deletes the record. return objEquipMaintenanceDB.Update(EquipmentMaintenaceFilePath, lines); }
/// <summary> /// Searches required string by ID and then replaces old value with new value. /// </summary> /// <param name="filePath"></param> /// <param name="objEquipMaintenance"></param> /// <returns></returns> private ArrayList Edit( EquipmentMaintenance objNewEquipMaintenance) { FileOperations objEquipMaintenaceDB = new FileOperations(); List<EquipmentMaintenance> objEquipMaintenaceColl = SelectAllData(); ArrayList lines = new ArrayList(); lines.Add("MaintenanceWorkId,Date,Time,WorksDescription,EquipmentId,TimeTaken"); foreach (EquipmentMaintenance equipMaintenace in objEquipMaintenaceColl) { if (equipMaintenace.MaintenanceWorkId == objNewEquipMaintenance.MaintenanceWorkId) lines.Add(objNewEquipMaintenance.ToString()); else lines.Add(equipMaintenace.ToString()); } return lines; }
/// <summary> /// Searches required string by ID and then skips it. /// </summary> /// <param name="filePath"></param> /// <param name="objEquipMaintenance"></param> /// <returns></returns> private ArrayList Delete(int id) { List<EquipmentMaintenance> objEquipMaintenanceColl = SelectAllData(); objEquipMaintenanceColl.RemoveAll(equipMain => equipMain.MaintenanceWorkId == id); FileOperations objEquipDB = new FileOperations(); ArrayList lines = new ArrayList(); lines.Add("MaintenanceWorkId,Date,Time,WorksDescription,EquipmentId,TimeTaken"); foreach (EquipmentMaintenance equipMaintenance in objEquipMaintenanceColl) { lines.Add(equipMaintenance.ToString()); } return lines; }
public override void Execute(CancellationToken cancellationToken) { base.Execute(cancellationToken); DebugLogger.Log("Uninstalling."); var entries = _localMetaData.GetRegisteredEntries(); var files = entries.Where(s => !s.EndsWith("/")).ToArray(); // TODO: Uncomment this after fixing directory registration in install content command //var directories = entries.Where(s => s.EndsWith("/")); int counter = 0; foreach (var fileName in files) { cancellationToken.ThrowIfCancellationRequested(); var filePath = _localData.Path.PathCombine(fileName); if (File.Exists(filePath)) { FileOperations.Delete(filePath); } _localMetaData.UnregisterEntry(fileName); counter++; _statusReporter.OnProgressChanged(counter / (double)entries.Length); } // TODO: Delete this after fixing directory registration in install content command // Temporary solution for deleting directories during uninstallation. foreach (var fileName in files) { cancellationToken.ThrowIfCancellationRequested(); string parentDirName = fileName; do { parentDirName = Path.GetDirectoryName(parentDirName); var parentDirPath = _localData.Path.PathCombine(parentDirName); if (Directory.Exists(parentDirPath)) { if (DirectoryOperations.IsDirectoryEmpty(parentDirPath)) { DirectoryOperations.Delete(parentDirPath, false); } else { break; } } } while (parentDirName != null); } // TODO: Uncomment this after fixing directory registration in install content command /* * foreach (var dirName in directories) * { * cancellationToken.ThrowIfCancellationRequested(); * * var dirPath = _localData.Path.PathCombine(dirName); * * if (Directory.Exists(dirPath) && DirectoryOperations.IsDirectoryEmpty(dirPath)) * { * DirectoryOperations.Delete(dirPath, false); * } * * _localMetaData.UnregisterEntry(dirName); * * counter++; * _statusReporter.OnProgressChanged(counter / (double)entries.Length); * }*/ }
private async Task StartGettingSiteMaps() { try { var service = await GetServiceAsync(); if (service == null) { return; } _siteMapIntellisenseData.ClearData(); if (Version.TryParse(_connectionData.OrganizationVersion, out var organizationVersion)) { string version = "365.8.2"; switch (organizationVersion.Major) { case 5: version = "2011"; break; case 6: version = "2013"; break; case 7: if (organizationVersion.Minor == 0) { version = "2015"; } else { version = "2015SP1"; } break; case 8: if (organizationVersion.Minor == 0) { version = "2016"; } else if (organizationVersion.Minor == 1) { version = "2016SP1"; } else { version = "365.8.2"; } break; } Uri uri = FileOperations.GetSiteMapResourceUri(version); StreamResourceInfo info = Application.GetResourceStream(uri); var doc = XDocument.Load(info.Stream); _siteMapIntellisenseData.LoadDataFromSiteMap(doc); info.Stream.Dispose(); } { var repository = new SitemapRepository(service); var listSiteMaps = await repository.GetListAsync(new ColumnSet(SiteMap.Schema.Attributes.sitemapxml)); foreach (var item in listSiteMaps) { if (string.IsNullOrEmpty(item.SiteMapXml)) { continue; } if (ContentCoparerHelper.TryParseXmlDocument(item.SiteMapXml, out var doc)) { _siteMapIntellisenseData.LoadDataFromSiteMap(doc); } } } if (service.ConnectionData.OrganizationId.HasValue) { var repository = new OrganizationRepository(service); var organization = await repository.GetByIdAsync(service.ConnectionData.OrganizationId.Value, new ColumnSet(Organization.Schema.Attributes.referencesitemapxml, Organization.Schema.Attributes.sitemapxml)); if (organization != null) { if (!string.IsNullOrEmpty(organization.ReferenceSiteMapXml)) { if (ContentCoparerHelper.TryParseXmlDocument(organization.ReferenceSiteMapXml, out var doc)) { _siteMapIntellisenseData.LoadDataFromSiteMap(doc); } } if (!string.IsNullOrEmpty(organization.SiteMapXml)) { if (ContentCoparerHelper.TryParseXmlDocument(organization.SiteMapXml, out var doc)) { _siteMapIntellisenseData.LoadDataFromSiteMap(doc); } } } } { var repository = new SystemFormRepository(service); var listSystemForms = await repository.GetListByTypeAsync((int)SystemForm.Schema.OptionSets.type.Dashboard_0, new ColumnSet(SystemForm.Schema.Attributes.objecttypecode, SystemForm.Schema.Attributes.name, SystemForm.Schema.Attributes.description)); _siteMapIntellisenseData.LoadDashboards(listSystemForms); } } catch (Exception ex) { DTEHelper.WriteExceptionToLog(ex); } finally { lock (_syncObjectTaskGettingSiteMapInformation) { _taskGettingSiteMapInformation = null; } } }
public bool FileOperation(FileOperations mode, string from, bool recycle) { return FileOperation(mode, from, null, null, recycle); }
private async Task CheckingGlobalOptionSetDuplicates(ConnectionData connectionData, CommonConfiguration commonConfig) { var service = await ConnectAndWriteToOutputAsync(connectionData); if (service == null) { return; } StringBuilder content = new StringBuilder(); content.AppendLine(Properties.OutputStrings.ConnectingToCRM); content.AppendLine(connectionData.GetConnectionDescription()); content.AppendFormat(Properties.OutputStrings.CurrentServiceEndpointFormat1, service.CurrentServiceEndpoint).AppendLine(); var entityMetadataSource = new SolutionComponentMetadataSource(service); var descriptor = new SolutionComponentDescriptor(service); descriptor.WithUrls = true; descriptor.WithManagedInfo = true; descriptor.WithSolutionsInfo = true; var dependencyRepository = new DependencyRepository(service); var descriptorHandler = new DependencyDescriptionHandler(descriptor); RetrieveAllOptionSetsRequest request = new RetrieveAllOptionSetsRequest(); RetrieveAllOptionSetsResponse response = (RetrieveAllOptionSetsResponse)service.Execute(request); bool hasInfo = false; foreach (var optionSet in response.OptionSetMetadata.OfType <OptionSetMetadata>().OrderBy(e => e.Name)) { var coll = await dependencyRepository.GetDependentComponentsAsync((int)ComponentType.OptionSet, optionSet.MetadataId.Value); if (coll.Any()) { var filter = coll .Where(c => c.DependentComponentType.Value == (int)ComponentType.Attribute) .Select(c => new { Dependency = c, Attribute = entityMetadataSource.GetAttributeMetadata(c.DependentComponentObjectId.Value) }) .Where(c => c.Attribute != null) .GroupBy(c => c.Attribute.EntityLogicalName) .Where(gr => gr.Count() > 1) .SelectMany(gr => gr.Select(c => c.Dependency)) .ToList() ; if (filter.Any()) { var desc = await descriptorHandler.GetDescriptionDependentAsync(filter); if (!string.IsNullOrEmpty(desc)) { if (content.Length > 0) { content .AppendLine(new string('-', 150)) .AppendLine(); } hasInfo = true; content.AppendFormat("Global OptionSet Name {0} IsCustomOptionSet {1} IsManaged {2}", optionSet.Name, optionSet.IsCustomOptionSet, optionSet.IsManaged).AppendLine(); content.AppendLine(desc); } } } } if (!hasInfo) { content.AppendLine("No duplicates were found."); } commonConfig.CheckFolderForExportExists(this._iWriteToOutput); string fileName = string.Format("{0}.Checking Global OptionSet Duplicates on Entity at {1}.txt", connectionData.Name, DateTime.Now.ToString("yyyy.MM.dd HH-mm-ss")); string filePath = Path.Combine(commonConfig.FolderForExport, FileOperations.RemoveWrongSymbols(fileName)); File.WriteAllText(filePath, content.ToString(), new UTF8Encoding(false)); this._iWriteToOutput.WriteToOutput(connectionData, Properties.OutputStrings.CreatedFileWithCheckingGlobalOptionSetDuplicatesOnEntityFormat1, filePath); this._iWriteToOutput.PerformAction(service.ConnectionData, filePath); }
public bool FileOperation(FileOperations mode, string from, string to, string newName) { return FileOperation(mode, from, to, newName, true); }
private void 制各种文件到皮肤文件夹() { Comment = "复制各种文件到皮肤文件夹"; FileOperations.CreateDir(Soft.SkinPath(Skin)); File.Copy(FilePath, Soft.SkinFile(Skin), true); }
public bool FileOperation(FileOperations mode, string from, string to, string newName, bool recycle) { Application.Current.Properties[nameof(AppProps.FileOperationResult)] = new Dictionary<string, string>(); //Copy, Move or delete selected MediaItems or folder using (FileOperation fo = new FileOperation(new PicFileOperationProgressSink())) { var flags = FileOperationFlags.FOF_NOCONFIRMMKDIR | (recycle ? FileOperationFlags.FOFX_RECYCLEONDELETE : FileOperationFlags.FOF_WANTNUKEWARNING); fo.SetOperationFlags(flags); if (from == null) { //MediaItems foreach (var mi in MediaItems.Items.Where(x => x.IsSelected)) { switch (mode) { case FileOperations.Copy: { fo.CopyItem(mi.FilePath, to, mi.FileNameWithExt); break; } case FileOperations.Move: { fo.MoveItem(mi.FilePath, to, mi.FileNameWithExt); break; } case FileOperations.Delete: { fo.DeleteItem(mi.FilePath); break; } } } } else { //Folders switch (mode) { case FileOperations.Copy: { fo.CopyItem(from, to, newName); break; } case FileOperations.Move: { fo.MoveItem(from, to, newName); break; } case FileOperations.Delete: { fo.DeleteItem(from); break; } } } fo.PerformOperations(); } var foResult = (Dictionary<string, string>)Application.Current.Properties[nameof(AppProps.FileOperationResult)]; if (foResult.Count == 0) return false; //update DB and thumbnail cache using (FileOperation fo = new FileOperation()) { fo.SetOperationFlags(FileOperationFlags.FOF_SILENT | FileOperationFlags.FOF_NOCONFIRMATION | FileOperationFlags.FOF_NOERRORUI | FileOperationFlags.FOFX_KEEPNEWERFILE); var cachePath = @Settings.Default.CachePath; var mItems = Db.MediaItems; var dirs = Db.Directories; if (mode == FileOperations.Delete) { var itemsToDel = new List<DataModel.MediaItem>(); if (from == null) { //delete by file/s foreach (var mi in MediaItems.Items.Where(x => x.IsSelected)) { if (File.Exists(mi.FilePath)) continue; var cacheFilePath = mi.FilePath.Replace(":\\", cachePath); if (!File.Exists(cacheFilePath)) continue; fo.DeleteItem(cacheFilePath); itemsToDel.Add(mi.Data); } } else { //delete by folder foreach (var dir in dirs.Where(x => x.Path.Equals(from) || x.Path.StartsWith(from + "\\"))) { foreach (var mi in mItems.Where(x => x.DirectoryId.Equals(dir.Id))) { var miFilePath = Path.Combine(dir.Path, mi.FileName); if (File.Exists(miFilePath)) continue; var cacheFilePath = miFilePath.Replace(":\\", cachePath); if (!File.Exists(cacheFilePath)) continue; fo.DeleteItem(cacheFilePath); itemsToDel.Add(mi); } } } foreach (var mi in itemsToDel) { foreach(var mik in Db.MediaItemKeywords.Where(x => x.MediaItemId == mi.Id)) { Db.DeleteOnSubmit(mik); } foreach (var mip in Db.MediaItemPeople.Where(x => x.MediaItemId == mi.Id)) { Db.DeleteOnSubmit(mip); } Db.DeleteOnSubmit(mi); } } if (mode == FileOperations.Copy || mode == FileOperations.Move) { foreach (var item in foResult) { if (MediaItems.SuportedExts.Any(ext => item.Value.EndsWith(ext, StringComparison.OrdinalIgnoreCase))) { if (!File.Exists(item.Value)) continue; var srcDirId = dirs.SingleOrDefault(x => x.Path.Equals(Path.GetDirectoryName(item.Key)))?.Id; if (srcDirId == null) continue; var srcPic = mItems.SingleOrDefault(x => x.DirectoryId == srcDirId && x.FileName == Path.GetFileName(item.Key)); if (srcPic == null) continue; //get destination directory or create it if doesn't exists var dirPath = Path.GetDirectoryName(item.Value); var destDirId = Db.InsertDirecotryInToDb(dirPath); #region Copy files if (mode == FileOperations.Copy) { //duplicate Picture var destPicId = Db.GetNextIdFor<DataModel.MediaItem>(); Db.InsertOnSubmit(new DataModel.MediaItem { Id = destPicId, DirectoryId = destDirId, FileName = Path.GetFileName(item.Value), Rating = srcPic.Rating, Comment = srcPic.Comment, Orientation = srcPic.Orientation }); //duplicate Picture Keywords foreach (var mik in Db.MediaItemKeywords.Where(x => x.MediaItemId == srcPic.Id)) { Db.InsertOnSubmit(new DataModel.MediaItemKeyword { Id = Db.GetNextIdFor<DataModel.MediaItemKeyword>(), KeywordId = mik.KeywordId, MediaItemId = destPicId }); } //duplicate Picture People foreach (var mip in Db.MediaItemPeople.Where(x => x.MediaItemId == srcPic.Id)) { Db.InsertOnSubmit(new DataModel.MediaItemPerson { Id = Db.GetNextIdFor<DataModel.MediaItemPerson>(), PersonId = mip.PersonId, MediaItemId = destPicId }); } //duplicate thumbnail fo.CopyItem(item.Key.Replace(":\\", cachePath), Path.GetDirectoryName(item.Value)?.Replace(":\\", cachePath), Path.GetFileName(item.Value)); } #endregion #region Move files if (mode == FileOperations.Move) { //BUG: if the file already exists in the destination directory, FileOperation returns COPYENGINE_S_USER_IGNORED and source thumbnail file is not deleted srcPic.DirectoryId = destDirId; srcPic.FileName = Path.GetFileName(item.Value); Db.UpdateOnSubmit(srcPic); //delete empty directory if (mItems.Count(x => x.DirectoryId.Equals(srcDirId)) == 0) { var emptyDir = dirs.SingleOrDefault(x => x.Id.Equals(srcDirId)); if (emptyDir != null) { Db.DeleteOnSubmit(emptyDir); } } //move thumbnail fo.MoveItem(item.Key.Replace(":\\", cachePath), Path.GetDirectoryName(item.Value)?.Replace(":\\", cachePath), Path.GetFileName(item.Value)); } #endregion } else { #region Move directories if (mode == FileOperations.Move) { //test if it is directory if (!Directory.Exists(item.Value)) continue; foreach (var dir in dirs.Where(x => x.Path.Equals(item.Key) || x.Path.StartsWith(item.Key + "\\"))) { dir.Path = dir.Path.Replace(item.Key, item.Value); Db.UpdateOnSubmit(dir); } //move thumbnails var destPath = Path.GetDirectoryName(item.Value); if (destPath != null) fo.MoveItem(item.Key.Replace(":\\", cachePath), destPath.Replace(":\\", cachePath), item.Value.Substring(destPath.Length + 1)); } #endregion } } } fo.PerformOperations(); Db.SubmitChanges(); } return true; }
public bool UpdateRecord( EquipmentMaintenance objEquipMaintenance) { FileOperations objEquipMaintenanceDB = new FileOperations(); ArrayList lines = Edit( objEquipMaintenance); //This searches the targeted id and replaces name string. return objEquipMaintenanceDB.Update(EquipmentMaintenaceFilePath, lines); }
public RemoteFile(FileInfo file1, FileOperations fileOp,string newFullName) { this.Name = file1.Name; this.FullName = file1.FullName; this.Length = file1.Length; this.ParentDirectory = file1.Directory.FullName; this.IsDirectory = false; this.LastWriteTime = file1.LastWriteTime; this.LastWriteTimeUtc = file1.LastWriteTimeUtc; this.FileOperation = fileOp; this.NewFullName = newFullName; }
private async Task PerformExportApplicationRibbonDiffXml() { if (!this.IsControlsEnabled) { return; } var service = await GetService(); this._iWriteToOutput.WriteToOutputStartOperation(service.ConnectionData, Properties.OperationNames.ExportingApplicationRibbonDiffXmlFormat1, service.ConnectionData.Name); ToggleControls(service.ConnectionData, false, Properties.WindowStatusStrings.ExportingApplicationRibbonDiffXml); var repositoryPublisher = new PublisherRepository(service); var publisherDefault = await repositoryPublisher.GetDefaultPublisherAsync(); if (publisherDefault == null) { ToggleControls(service.ConnectionData, true, Properties.WindowStatusStrings.NotFoundedDefaultPublisher); _iWriteToOutput.ActivateOutputWindow(service.ConnectionData); return; } var repositoryRibbonCustomization = new RibbonCustomizationRepository(service); var ribbonCustomization = await repositoryRibbonCustomization.FindApplicationRibbonCustomizationAsync(); if (ribbonCustomization == null) { ToggleControls(service.ConnectionData, true, Properties.WindowStatusStrings.NotFoundedApplicationRibbonRibbonCustomization); _iWriteToOutput.ActivateOutputWindow(service.ConnectionData); return; } try { string ribbonDiffXml = await repositoryRibbonCustomization.GetRibbonDiffXmlAsync(_iWriteToOutput, null, ribbonCustomization); if (string.IsNullOrEmpty(ribbonDiffXml)) { ToggleControls(service.ConnectionData, true, Properties.WindowStatusStrings.ExportingApplicationRibbonDiffXmlFailed); return; } ribbonDiffXml = ContentCoparerHelper.FormatXmlByConfiguration(ribbonDiffXml, _commonConfig, _xmlOptions , schemaName: AbstractDynamicCommandXsdSchemas.SchemaRibbonXml , ribbonEntityName: string.Empty ); { string fileName = EntityFileNameFormatter.GetApplicationRibbonDiffXmlFileName(service.ConnectionData.Name); string filePath = Path.Combine(_commonConfig.FolderForExport, FileOperations.RemoveWrongSymbols(fileName)); File.WriteAllText(filePath, ribbonDiffXml, new UTF8Encoding(false)); this._iWriteToOutput.WriteToOutput(service.ConnectionData, Properties.OutputStrings.ExportedAppliationRibbonDiffXmlForConnectionFormat2, service.ConnectionData.Name, filePath); this._iWriteToOutput.PerformAction(service.ConnectionData, filePath); } ToggleControls(service.ConnectionData, true, Properties.WindowStatusStrings.ExportingApplicationRibbonDiffXmlCompleted); } catch (Exception ex) { this._iWriteToOutput.WriteErrorToOutput(service.ConnectionData, ex); ToggleControls(service.ConnectionData, true, Properties.WindowStatusStrings.ExportingApplicationRibbonDiffXmlFailed); } this._iWriteToOutput.WriteToOutputEndOperation(service.ConnectionData, Properties.OperationNames.ExportingApplicationRibbonDiffXmlFormat1, service.ConnectionData.Name); }
public RemoteFile(DirectoryInfo dir1, FileOperations fileOp, string newFullName) { this.Name = dir1.Name; this.FullName = dir1.FullName; this.Length = 0; this.ParentDirectory = "";//dir1.Parent.FullName; this.IsDirectory = true; this.LastWriteTime = dir1.LastWriteTime; this.LastWriteTimeUtc = dir1.LastWriteTimeUtc; this.FileOperation = fileOp; this.NewFullName = newFullName; }
/// <summary> /// This method is used to download a file. /// </summary> /// <param name="id">The ID of the uploaded File.</param> /// <param name="destinationFolder">The absolute path of the destination folder to store the File</param> public static void GetFile(string id, string destinationFolder) { //example //string id = "ae9c7cefa418aec1d6a5cc2d7d5e00a54b7563c0dd42b"; //string destinationFolder = "/Users/user_name/Desktop" //Get instance of FileOperations Class FileOperations fileOperations = new FileOperations(); //Get instance of ParameterMap Class ParameterMap paramInstance = new ParameterMap(); paramInstance.Add(GetFileParam.ID, id); //Call getFile method that takes paramInstance as parameters APIResponse <ResponseHandler> response = fileOperations.GetFile(paramInstance); if (response != null) { //Get the status code from response Console.WriteLine("Status Code: " + response.StatusCode); if (new List <int>() { 204, 304 }.Contains(response.StatusCode)) { Console.WriteLine(response.StatusCode == 204? "No Content" : "Not Modified"); return; } //Check if expected response is received if (response.IsExpected) { //Get object from response ResponseHandler responseHandler = response.Object; if (responseHandler is FileBodyWrapper) { //Get object from response FileBodyWrapper fileBodyWrapper = (FileBodyWrapper)responseHandler; //Get StreamWrapper instance from the returned FileBodyWrapper instance StreamWrapper streamWrapper = fileBodyWrapper.File; Stream file = streamWrapper.Stream; string fullFilePath = Path.Combine(destinationFolder, streamWrapper.Name); using (FileStream outputFileStream = new FileStream(fullFilePath, FileMode.Create)) { file.CopyTo(outputFileStream); } } //Check if the request returned an exception else if (responseHandler is APIException) { //Get the received APIException instance APIException exception = (APIException)responseHandler; //Get the Status Console.WriteLine("Status: " + exception.Status.Value); //Get the Code Console.WriteLine("Code: " + exception.Code.Value); Console.WriteLine("Details: "); //Get the details map foreach (KeyValuePair <string, object> entry in exception.Details) { //Get each value in the map Console.WriteLine(entry.Key + ": " + JsonConvert.SerializeObject(entry.Value)); } //Get the Message Console.WriteLine("Message: " + exception.Message.Value); } } else { //If response is not as expected //Get model object from response Model responseObject = response.Model; if (responseObject != null) { //Get the response object's class Type type = responseObject.GetType(); //Get all declared fields of the response class Console.WriteLine("Type is: {0}", type.Name); PropertyInfo[] props = type.GetProperties(); Console.WriteLine("Properties (N = {0}):", props.Length); foreach (var prop in props) { if (prop.GetIndexParameters().Length == 0) { Console.WriteLine("{0} ({1}) : {2}", prop.Name, prop.PropertyType.Name, prop.GetValue(responseObject)); } else { Console.WriteLine("{0} ({1}) : <Indexed>", prop.Name, prop.PropertyType.Name); } } } } } }
private async void AddFolder() { LogClient.Info("Adding a folder to the collection."); var dlg = new WPFFolderBrowserDialog(); if ((bool)dlg.ShowDialog()) { try { this.IsLoadingFolders = true; AddFolderResult result = AddFolderResult.Error; // Initial value // First, check if the folder's content is accessible. If not, don't add the folder. if (FileOperations.IsDirectoryContentAccessible(dlg.FileName)) { result = await this.folderRepository.AddFolderAsync(dlg.FileName); } else { result = AddFolderResult.Inaccessible; } this.IsLoadingFolders = false; switch (result) { case AddFolderResult.Success: this.indexingService.OnFoldersChanged(); this.GetFoldersAsync(); break; case AddFolderResult.Error: this.dialogService.ShowNotification( 0xe711, 16, ResourceUtils.GetString("Language_Error"), ResourceUtils.GetString("Language_Error_Adding_Folder"), ResourceUtils.GetString("Language_Ok"), true, ResourceUtils.GetString("Language_Log_File")); break; case AddFolderResult.Duplicate: this.dialogService.ShowNotification( 0xe711, 16, ResourceUtils.GetString("Language_Already_Exists"), ResourceUtils.GetString("Language_Folder_Already_In_Collection"), ResourceUtils.GetString("Language_Ok"), false, ""); break; case AddFolderResult.Inaccessible: this.dialogService.ShowNotification( 0xe711, 16, ResourceUtils.GetString("Language_Error"), ResourceUtils.GetString("Language_Folder_Could_Not_Be_Added_Check_Permissions").Replace("{foldername}", dlg.FileName), ResourceUtils.GetString("Language_Ok"), false, ""); break; } } catch (Exception ex) { LogClient.Error("Exception: {0}", ex.Message); this.dialogService.ShowNotification( 0xe711, 16, ResourceUtils.GetString("Language_Error"), ResourceUtils.GetString("Language_Error_Adding_Folder"), ResourceUtils.GetString("Language_Ok"), true, ResourceUtils.GetString("Language_Log_File")); } finally { this.IsLoadingFolders = false; } } }
public int GetVMIP(string ServerIP, string username, string password, string VMNameLabel, int Timer) { Logger NewLogObj = new Logger(); string LogFilePath = NewLogObj.GetLogFilePath(); FileOperations FileObj = new FileOperations(); string hostname = ServerIP; int port = 80; // default int ExceptionHandlingnotReqdFlag = 0; try { Session session = new Session(hostname, port); session.login_with_password(username, password, API_Version.API_1_3); //MessageBox.Show("Conection Successfully Estabilished to the XenServer: " +Connection_XS_IP +""); List <XenRef <VM> > vmRefs = VM.get_all(session); StartSearch: foreach (XenRef <VM> vmRef in vmRefs) { //http://forums.citrix.com/thread.jspa?threadID=244784 VM vm = VM.get_record(session, vmRef); if (!vm.is_a_template && !vm.is_control_domain && !vm.is_a_snapshot && !vm.is_snapshot_from_vmpp) { //System.Console.Write("\nVM Name: {0} -> IP Address: ", vm.name_label); if (string.Compare(vm.name_label, VMNameLabel) == 0) { try { NewLogObj.WriteLogFile(LogFilePath, VMNameLabel + " found. Fetching records", "info"); bool dict_key = true; int WaitTimeout = 2400000; //40 mins //Wait till VM starts running while (!(string.Compare(vm.power_state.ToString(), "Running") == 0) && Timer < WaitTimeout) { System.Console.WriteLine("Waiting for VM " + VMNameLabel + " to poweron"); Thread.Sleep(1000); Timer = Timer + 1000; goto StartSearch; } if (!(string.Compare(vm.power_state.ToString(), "Running") == 0) && Timer >= WaitTimeout) { System.Console.WriteLine("Timeout waiting for VM " + VMNameLabel + " to poweron."); NewLogObj.WriteLogFile(LogFilePath, "Timeout waiting for VM " + VMNameLabel + " to poweron.", "fail"); return(-1); } while (dict_key == true && Timer < WaitTimeout) { try { int IPFound = 0; XenRef <VM_guest_metrics> gmsref = vm.guest_metrics; VM_guest_metrics gms = VM_guest_metrics.get_record(session, gmsref); Dictionary <String, String> dict = null; dict = gms.networks; String vmIP = null; foreach (String keyStr in dict.Keys) { dict_key = false; vmIP = (String)(dict[keyStr]); //excluding IPv6 address which contains the character : if (!vmIP.Contains(':')) { if (!vmIP.StartsWith("169")) { System.Console.WriteLine(vmIP); NewLogObj.WriteLogFile(LogFilePath, "IP address obtained for VM " + VMNameLabel + " is " + vmIP, "info"); IPFound = 1; return(1); } } } //for each keyStr if (dict_key == false || IPFound == 0) { System.Console.WriteLine("No valid IP addressfound for " + VMNameLabel); NewLogObj.WriteLogFile(LogFilePath, "No valid IP addressfound for " + VMNameLabel, "fail"); ExceptionHandlingnotReqdFlag = 1; return(-1); } } catch (Exception e) { //To avoid reduntant calls to function if (ExceptionHandlingnotReqdFlag == 1) { return(-1); } else { //System.Console.WriteLine(e.ToString() + " Waiting .."); System.Console.WriteLine(" Waiting for VM " + VMNameLabel + "to aquire IP address.."); Thread.Sleep(1000); Timer = Timer + 1000; goto StartSearch; //GetVMIP(ServerIP, username, password, VMNameLabel, Timer); } } } if (dict_key == true && Timer > WaitTimeout) { NewLogObj.WriteLogFile(LogFilePath, "Timeout waiting for the VM " + VMNameLabel + " to obtain IP address", "fail"); FileObj.ExitTestEnvironment(); return(-1); } } //try loop catch (Exception e) { System.Console.WriteLine(e.ToString()); return(-1); } } } //check and allow only VMs there by excluding templates/controldomain/snapshots/etc... } //For each... } // try to connect XenServer host. catch (Exception e1) { string exceptionText = "Server \"" + hostname + "\" cannot be contacted." + "\n\nError: " + e1.ToString(); System.Console.WriteLine(exceptionText); } //System.Console.WriteLine("Press a key to continue..."); //System.Console.ReadLine(); return(-1); }
private void frmManageDigitalSignature_Load(object sender, EventArgs e) { compatibleDocuments.Clear(); compatibleDocuments = FileOperations.ListAllowedFilesAndSubfolders(documents, true, includeSubfolders); listFiles(compatibleDocuments.ToArray()); }
public bool InvokeOperation(IntPtr? ownerWindow = null, FileOperations operation = FileOperations.Copy, String[] sourceFiles = null, String[] destinationFiles = null) { if (!ownerWindow.HasValue || ownerWindow.Value == null) ownerWindow = IntPtr.Zero; Connection.Native.ShellFileOperation shellFileOperation = new Connection.Native.ShellFileOperation { hwnd = ownerWindow.Value, wFunc = (uint)operation }; string multiSource = this.StringArrayToMultiString(sourceFiles); string multiDest = this.StringArrayToMultiString(destinationFiles); shellFileOperation.pFrom = Marshal.StringToHGlobalUni(multiSource); shellFileOperation.pTo = Marshal.StringToHGlobalUni(multiDest); shellFileOperation.fFlags = (ushort) this.operationFlags; shellFileOperation.lpszProgressTitle = this.progressTitle; shellFileOperation.fAnyOperationsAborted = 0; shellFileOperation.hNameMappings = IntPtr.Zero; int retVal = WindowsApi.SHFileOperation(ref shellFileOperation); WindowsApi.SHChangeNotify(/* ShellChangeNotificationEvents.SHCNE_ALLEVENTS = */ 0x7FFFFFFF /* All events have occurred. */,/* ShellChangeNotificationFlags.SHCNF_DWORD = */ 0x0003 /*The dwItem1 and dwItem2 parameters are DWORD values. */,IntPtr.Zero,IntPtr.Zero); if (retVal != 0) return false; if (shellFileOperation.fAnyOperationsAborted != 0) return false; return true; }
public List <byte[]> GetAllCertificates() { List <byte[]> certificates = new List <byte[]>(); bool canRead = (readerIndex > -1); if (!canRead) { canRead = IsCardInserted; } if (canRead) { CreateCacheFolder(); string fileName = Path.Combine(cacheFolder, serialNumber + ".ca"); if (FileOperations.FileExists(fileName)) { certificates.Add(File.ReadAllBytes(fileName)); } else { CardReader reader = engine.GetReader(readerIndex); if (reader != null) { Card card = reader.GetCard(true); if (card != null) { byte[] result = card.ReadCertificate(CertificateType.CaCertificate); if (result != null) { File.WriteAllBytes(fileName, result); certificates.Add(result); } } } } fileName = Path.Combine(cacheFolder, serialNumber + ".root"); if (FileOperations.FileExists(fileName)) { certificates.Add(File.ReadAllBytes(fileName)); } else { CardReader reader = engine.GetReader(readerIndex); if (reader != null) { Card card = reader.GetCard(true); if (card != null) { byte[] result = card.ReadCertificate(CertificateType.RootCaCertificate); if (result != null) { File.WriteAllBytes(fileName, result); certificates.Add(result); } } } } } return(certificates); }
public async Task <string> ProcessAsync(DiscordMessage message) { if (_expletiveCommandText.Length + 2 > message.Content.Length) { return("Are you stupid?"); } string nonCommand = message.Content.Substring(_expletiveCommandText.Length + 2); string[] words = nonCommand.Split(' '); string[] subCommands = { "add", "confirm", "delete", "status" }; if (IsMention(words[0])) { if (words.Length > 1) { return("What are you doing?"); } else { if (_lastUseTime.Keys.Contains(message.Author.Id)) { var diff = DateTime.UtcNow - _lastUseTime[message.Author.Id]; int seconds = (int)Math.Ceiling(diff.TotalSeconds); if (seconds < _timeLimitSecs) { return($"{message.Author.Mention} You can abuse again in {_timeLimitSecs - seconds} seconds."); } } _lastUseTime[message.Author.Id] = DateTime.UtcNow; return(GetRandomAbuse(message.MentionedUsers.First().Id)); } } else { switch (words[0].ToLowerInvariant()) { case "add": await message.DeleteAsync(); if (UserAlreadyProcessing(message.Author.Id)) { return("You cannot submit another expletive until your first one is processed."); } if (words.Where(x => x.IndexOf(":user:"******"There must be a `:user:` mentioned in the abuse."); } string encryptedExpletive = _crypter.Encrypt(string.Join(' ', words.Skip(1))); string toStore = $"{message.Author.Id}|{encryptedExpletive}"; FileOperations.AppendLine(ExpletiveConfig.UnconfiremedExpletivesFile, toStore); return($"{message.Author.Mention}, your abuse has been submitted for processing."); case "status": DiscordMember messageAuthor = IsMemberAuthorized(message.Author.Id, _members); if (messageAuthor == null) { return("You are not authorized to use this command."); } using (StreamReader reader = new StreamReader(ExpletiveConfig.UnconfiremedExpletivesFile)) { string line = null; await messageAuthor.SendMessageAsync("Vote Status:"); while ((line = reader.ReadLine()) != null) { var splitLine = line.Split('|'); string actualLine = $"{GetNameFromId(splitLine[0], _members)} - {_crypter.Decrypt(splitLine[1])}"; await messageAuthor.SendMessageAsync(actualLine); } } return("Status sent."); case "approve": messageAuthor = IsMemberAuthorized(message.Author.Id, _members); if (messageAuthor == null) { return("You are not authorized to use this command."); } if (words.Length != 2) { return("Usage: `approve @user`"); } var approvedUser = message.MentionedUsers.First(); int lineNo = -1; string expletive = null; string submitter = null; using (StreamReader reader = new StreamReader(ExpletiveConfig.UnconfiremedExpletivesFile)) { string line = null; for (int i = 0; (line = reader.ReadLine()) != null; i++) { words = line.Split('|'); if (words[0].Equals(approvedUser.Id.ToString())) { lineNo = i; expletive = words[1]; submitter = words[0]; break; } } } if (lineNo < 0) { return("Submission not found for the user."); } FileOperations.AppendLine(ExpletiveConfig.StoredExpletivesFile, expletive); FileOperations.DeleteLine(ExpletiveConfig.UnconfiremedExpletivesFile, lineNo); return($"<@{submitter}>, your abuse has been approved."); case "reject": messageAuthor = IsMemberAuthorized(message.Author.Id, _members); if (messageAuthor == null) { return("You are not authorized to use this command."); } if (words.Length != 2) { return("Usage: `reject @user`"); } approvedUser = message.MentionedUsers.First(); lineNo = -1; expletive = null; submitter = null; using (StreamReader reader = new StreamReader(ExpletiveConfig.UnconfiremedExpletivesFile)) { string line = null; for (int i = 0; (line = reader.ReadLine()) != null; i++) { words = line.Split('|'); if (words[0].Equals(approvedUser.Id.ToString())) { lineNo = i; expletive = line.Split('|')[1]; submitter = line.Split('|')[0]; break; } } } if (lineNo < 0) { return("Submission not found for the user."); } FileOperations.DeleteLine(ExpletiveConfig.UnconfiremedExpletivesFile, lineNo); return($"<@{submitter}>, your abuse has been rejected."); } } return(string.Empty); }
public EidSignature(string pin) { this.pin = pin; this.cacheFolder = Path.Combine(FileOperations.IncludeTrailingPathDelimiter(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData)), "cache.eid"); engine.Active = true; }
public void Save() { FileOperations.SaveConfiguration(this, FILE_NAME); }
public Params(FileOperations fo, DestinationDirectoriesFormat ddf) { mode = fo; format = ddf; }
private async Task ShowingWebResourcesDependentComponents(ConnectionData connectionData, CommonConfiguration commonConfig, List <SelectedFile> selectedFiles) { var service = await ConnectAndWriteToOutputAsync(connectionData); if (service == null) { return; } StringBuilder content = new StringBuilder(); content.AppendLine(Properties.OutputStrings.ConnectingToCRM); content.AppendLine(connectionData.GetConnectionDescription()); content.AppendFormat(Properties.OutputStrings.CurrentServiceEndpointFormat1, service.CurrentServiceEndpoint).AppendLine(); var descriptor = new SolutionComponentDescriptor(service); descriptor.WithUrls = true; descriptor.WithManagedInfo = true; descriptor.WithSolutionsInfo = true; var descriptorHandler = new DependencyDescriptionHandler(descriptor); var dependencyRepository = new DependencyRepository(service); bool isconnectionDataDirty = false; List <string> listNotExistsOnDisk = new List <string>(); List <string> listNotFoundedInCRMNoLink = new List <string>(); List <string> listLastLinkEqualByContent = new List <string>(); List <SolutionComponent> webResourceNames = new List <SolutionComponent>(); Dictionary <SolutionComponent, string> webResourceDescriptions = new Dictionary <SolutionComponent, string>(); WebResourceRepository repositoryWebResource = new WebResourceRepository(service); FormatTextTableHandler tableWithoutDependenComponents = new FormatTextTableHandler(); tableWithoutDependenComponents.SetHeader("FilePath", "Web Resource Name", "Web Resource Type"); var groups = selectedFiles.GroupBy(sel => sel.Extension); foreach (var gr in groups) { var names = gr.Select(sel => sel.FriendlyFilePath).ToArray(); var dict = repositoryWebResource.FindMultiple(gr.Key, names); foreach (var selectedFile in gr) { if (File.Exists(selectedFile.FilePath)) { string name = selectedFile.FriendlyFilePath.ToLower(); var webresource = WebResourceRepository.FindWebResourceInDictionary(dict, name, gr.Key); if (webresource == null) { Guid?webId = connectionData.GetLastLinkForFile(selectedFile.FriendlyFilePath); if (webId.HasValue) { webresource = await repositoryWebResource.GetByIdAsync(webId.Value); if (webresource != null) { listLastLinkEqualByContent.Add(selectedFile.FriendlyFilePath); } } } if (webresource != null) { // Запоминается файл isconnectionDataDirty = true; connectionData.AddMapping(webresource.Id, selectedFile.FriendlyFilePath); var coll = await dependencyRepository.GetDependentComponentsAsync((int)ComponentType.WebResource, webresource.Id); var desc = await descriptorHandler.GetDescriptionDependentAsync(coll); if (!string.IsNullOrEmpty(desc)) { var component = new SolutionComponent() { ComponentType = new OptionSetValue((int)ComponentType.WebResource), ObjectId = webresource.Id, }; webResourceNames.Add(component); webResourceDescriptions.Add(component, desc); } else { tableWithoutDependenComponents.AddLine(selectedFile.FriendlyFilePath, webresource.Name, "'" + webresource.FormattedValues[WebResource.Schema.Attributes.webresourcetype] + "'"); } } else { connectionData.RemoveMapping(selectedFile.FriendlyFilePath); listNotFoundedInCRMNoLink.Add(selectedFile.FriendlyFilePath); } } else { listNotExistsOnDisk.Add(selectedFile.FilePath); } } } if (isconnectionDataDirty) { //Сохранение настроек после публикации connectionData.Save(); } FindsController.WriteToContentList(listNotFoundedInCRMNoLink, content, "File NOT FOUNDED in CRM: {0}"); FindsController.WriteToContentList(listLastLinkEqualByContent, content, "Files NOT FOUNDED in CRM, but has Last Link: {0}"); FindsController.WriteToContentList(listNotExistsOnDisk, content, Properties.OutputStrings.FileNotExistsFormat1); FindsController.WriteToContentList(tableWithoutDependenComponents.GetFormatedLines(true), content, "Files without dependent components: {0}"); FindsController.WriteToContentDictionary(descriptor, content, webResourceNames, webResourceDescriptions, "WebResource dependent components: {0}"); commonConfig.CheckFolderForExportExists(this._iWriteToOutput); string fileName = string.Format("{0}.WebResourceDependent at {1}.txt", connectionData.Name, DateTime.Now.ToString("yyyy.MM.dd HH-mm-ss")); string filePath = Path.Combine(commonConfig.FolderForExport, FileOperations.RemoveWrongSymbols(fileName)); File.WriteAllText(filePath, content.ToString(), new UTF8Encoding(false)); this._iWriteToOutput.WriteToOutput(connectionData, Properties.OutputStrings.CreatedFileWithWebResourcesDependentComponentsFormat1, filePath); this._iWriteToOutput.PerformAction(service.ConnectionData, filePath); }
public void TestInit() { this.fileOperations = new FileOperations(); }
private async Task CheckingComponentTypeEnum(ConnectionData connectionData, CommonConfiguration commonConfig) { var service = await ConnectAndWriteToOutputAsync(connectionData); if (service == null) { return; } StringBuilder content = new StringBuilder(); content.AppendLine(Properties.OutputStrings.ConnectingToCRM); content.AppendLine(connectionData.GetConnectionDescription()); content.AppendFormat(Properties.OutputStrings.CurrentServiceEndpointFormat1, service.CurrentServiceEndpoint).AppendLine(); var hash = new HashSet <Tuple <int, Guid> >(); { var repository = new SolutionComponentRepository(service); var components = await repository.GetDistinctSolutionComponentsAsync(); foreach (var item in components.Where(en => en.ComponentType != null && en.ObjectId.HasValue)) { if (!item.IsDefinedComponentType()) { hash.Add(Tuple.Create(item.ComponentType.Value, item.ObjectId.Value)); } } } { var repository = new DependencyNodeRepository(service); var components = await repository.GetDistinctListUnknownComponentTypeAsync(); foreach (var item in components.Where(en => en.ComponentType != null && en.ObjectId.HasValue)) { if (!item.IsDefinedComponentType()) { hash.Add(Tuple.Create(item.ComponentType.Value, item.ObjectId.Value)); } } } { var repository = new InvalidDependencyRepository(service); var components = await repository.GetDistinctListAsync(); foreach (var item in components.Where(en => en.MissingComponentType != null && en.MissingComponentId.HasValue)) { if (!item.IsDefinedMissingComponentType()) { hash.Add(Tuple.Create(item.MissingComponentType.Value, item.MissingComponentId.Value)); } } foreach (var item in components.Where(en => en.ExistingComponentType != null && en.ExistingComponentId.HasValue)) { if (!item.IsDefinedExistingComponentType()) { hash.Add(Tuple.Create(item.ExistingComponentType.Value, item.ExistingComponentId.Value)); } } } if (hash.Any()) { var groups = hash.GroupBy(e => e.Item1); content.AppendLine().AppendLine(); content.AppendFormat("ComponentTypes not founded in Enum: {0}", groups.Count()); foreach (var gr in groups.OrderBy(e => e.Key)) { content.AppendLine().AppendLine(); foreach (var item in gr.OrderBy(e => e.Item2)) { content.AppendFormat(_tabSpacer + item.Item1.ToString() + _tabSpacer + item.Item2.ToString()).AppendLine(); } } string fileName = string.Format("{0}.Checking ComponentType Enum at {1}.txt" , connectionData.Name , DateTime.Now.ToString("yyyy.MM.dd HH-mm-ss") ); commonConfig.CheckFolderForExportExists(this._iWriteToOutput); string filePath = Path.Combine(commonConfig.FolderForExport, FileOperations.RemoveWrongSymbols(fileName)); File.WriteAllText(filePath, content.ToString(), new UTF8Encoding(false)); this._iWriteToOutput.WriteToOutput(connectionData, "New ComponentTypes were exported to {0}", filePath); this._iWriteToOutput.PerformAction(service.ConnectionData, filePath); } else { this._iWriteToOutput.WriteToOutput(connectionData, "No New ComponentTypes in CRM were founded."); this._iWriteToOutput.ActivateOutputWindow(connectionData); } }
public TeacherAppProxy(FileOperations dbOp) { _dbOp = dbOp; }
private async Task CheckingUnknownFormControlType(ConnectionData connectionData, CommonConfiguration commonConfig) { var service = await ConnectAndWriteToOutputAsync(connectionData); if (service == null) { return; } StringBuilder content = new StringBuilder(); content.AppendLine(Properties.OutputStrings.ConnectingToCRM); content.AppendLine(connectionData.GetConnectionDescription()); content.AppendFormat(Properties.OutputStrings.CurrentServiceEndpointFormat1, service.CurrentServiceEndpoint).AppendLine(); Dictionary <string, FormatTextTableHandler> dictUnknownControls = new Dictionary <string, FormatTextTableHandler>(StringComparer.InvariantCultureIgnoreCase); var descriptor = new SolutionComponentDescriptor(service); var handler = new FormDescriptionHandler(descriptor, new DependencyRepository(service)); var repositorySystemForm = new SystemFormRepository(service); var formList = await repositorySystemForm.GetListAsync(null, null, new ColumnSet(true)); foreach (var systemForm in formList .OrderBy(f => f.ObjectTypeCode) .ThenBy(f => f.Type?.Value) .ThenBy(f => f.Name) ) { string formXml = systemForm.FormXml; if (!string.IsNullOrEmpty(formXml)) { XElement doc = XElement.Parse(formXml); var tabs = handler.GetFormTabs(doc); var unknownControls = tabs.SelectMany(t => t.Sections).SelectMany(s => s.Controls).Where(c => c.GetControlType() == FormControl.FormControlType.UnknownControl); foreach (var control in unknownControls) { if (!dictUnknownControls.ContainsKey(control.ClassId)) { FormatTextTableHandler tableUnknownControls = new FormatTextTableHandler(); tableUnknownControls.SetHeader("Entity", "FormType", "Form", "State", "Attribute", "Form Url"); dictUnknownControls[control.ClassId] = tableUnknownControls; } dictUnknownControls[control.ClassId].AddLine( systemForm.ObjectTypeCode , systemForm.FormattedValues[SystemForm.Schema.Attributes.type] , systemForm.Name , systemForm.FormattedValues[SystemForm.Schema.Attributes.formactivationstate] , control.Attribute , service.UrlGenerator.GetSolutionComponentUrl(ComponentType.SystemForm, systemForm.Id) ); } } } if (dictUnknownControls.Count > 0) { content.AppendLine().AppendLine(); content.AppendFormat("Unknown Form Control Types: {0}", dictUnknownControls.Count); foreach (var classId in dictUnknownControls.Keys.OrderBy(s => s)) { content.AppendLine().AppendLine(); content.AppendLine(classId); var tableUnknownControls = dictUnknownControls[classId]; foreach (var str in tableUnknownControls.GetFormatedLines(false)) { content.AppendLine(_tabSpacer + str); } } commonConfig.CheckFolderForExportExists(this._iWriteToOutput); string fileName = string.Format("{0}.Checking Unknown Form Control Types at {1}.txt" , connectionData.Name , DateTime.Now.ToString("yyyy.MM.dd HH-mm-ss") ); string filePath = Path.Combine(commonConfig.FolderForExport, FileOperations.RemoveWrongSymbols(fileName)); File.WriteAllText(filePath, content.ToString(), new UTF8Encoding(false)); this._iWriteToOutput.WriteToOutput(connectionData, "Unknown Form Control Types were exported to {0}", filePath); this._iWriteToOutput.PerformAction(service.ConnectionData, filePath); } else { this._iWriteToOutput.WriteToOutput(connectionData, "No Unknown Form Control Types in CRM were founded."); this._iWriteToOutput.ActivateOutputWindow(connectionData); } }
private async Task DifferenceReport(ConnectionData connectionData, CommonConfiguration commonConfig, SelectedFile selectedFile, string fieldName, string fieldTitle, bool withSelect) { if (!File.Exists(selectedFile.FilePath)) { this._iWriteToOutput.WriteToOutput(connectionData, Properties.OutputStrings.FileNotExistsFormat1, selectedFile.FilePath); return; } var service = await ConnectAndWriteToOutputAsync(connectionData); if (service == null) { return; } if (string.IsNullOrEmpty(fieldName)) { fieldName = Report.Schema.Attributes.originalbodytext; fieldTitle = Report.Schema.Headers.originalbodytext; } Report reportEntity = null; using (service.Lock()) { // Репозиторий для работы с веб-ресурсами var reportRepository = new ReportRepository(service); if (withSelect) { Guid?reportId = connectionData.GetLastLinkForFile(selectedFile.FriendlyFilePath); bool?dialogResult = null; Guid?selectedReportId = null; string selectedPath = string.Empty; var thread = new Thread(() => { try { var form = new Views.WindowReportSelect(this._iWriteToOutput, service, selectedFile, reportId); dialogResult = form.ShowDialog(); selectedReportId = form.SelectedReportId; } catch (Exception ex) { DTEHelper.WriteExceptionToOutput(connectionData, ex); } }); thread.SetApartmentState(ApartmentState.STA); thread.Start(); thread.Join(); if (dialogResult.GetValueOrDefault()) { if (selectedReportId.HasValue) { this._iWriteToOutput.WriteToOutput(connectionData, "Custom report is selected."); reportEntity = await reportRepository.GetByIdAsync(selectedReportId.Value); connectionData.AddMapping(reportEntity.Id, selectedFile.FriendlyFilePath); connectionData.Save(); } else { this._iWriteToOutput.WriteToOutput(connectionData, "!Warning. Report not exists. name: {0}.", selectedFile.Name); } } else { this._iWriteToOutput.WriteToOutput(connectionData, Properties.OutputStrings.DifferenceWasCancelled); return; } } else { reportEntity = await reportRepository.FindAsync(selectedFile.FileName); if (reportEntity != null) { this._iWriteToOutput.WriteToOutput(connectionData, "Report founded by name."); connectionData.AddMapping(reportEntity.Id, selectedFile.FriendlyFilePath); connectionData.Save(); } else { Guid?reportId = connectionData.GetLastLinkForFile(selectedFile.FriendlyFilePath); if (reportId.HasValue) { reportEntity = await reportRepository.GetByIdAsync(reportId.Value); } if (reportEntity != null) { this._iWriteToOutput.WriteToOutput(connectionData, "Report not founded by name. Last link report is selected for difference."); connectionData.AddMapping(reportEntity.Id, selectedFile.FriendlyFilePath); connectionData.Save(); } else { this._iWriteToOutput.WriteToOutput(connectionData, "Report not founded by name and has not Last link."); this._iWriteToOutput.WriteToOutput(connectionData, "Starting Custom Report selection form."); bool?dialogResult = null; Guid?selectedReportId = null; string selectedPath = string.Empty; var thread = new Thread(() => { try { var form = new Views.WindowReportSelect(this._iWriteToOutput, service, selectedFile, reportId); dialogResult = form.ShowDialog(); selectedReportId = form.SelectedReportId; } catch (Exception ex) { DTEHelper.WriteExceptionToOutput(connectionData, ex); } }); thread.SetApartmentState(ApartmentState.STA); thread.Start(); thread.Join(); if (dialogResult.GetValueOrDefault()) { if (selectedReportId.HasValue) { this._iWriteToOutput.WriteToOutput(connectionData, "Custom report is selected."); reportEntity = await reportRepository.GetByIdAsync(selectedReportId.Value); connectionData.AddMapping(reportEntity.Id, selectedFile.FriendlyFilePath); connectionData.Save(); } else { this._iWriteToOutput.WriteToOutput(connectionData, "!Warning. Report not exists. name: {0}.", selectedFile.Name); } } else { this._iWriteToOutput.WriteToOutput(connectionData, Properties.OutputStrings.DifferenceWasCancelled); return; } } } } } if (reportEntity == null) { this._iWriteToOutput.WriteToOutput(connectionData, Properties.OutputStrings.InConnectionReportWasNotFoundFormat2, connectionData.Name, selectedFile.FileName); return; } var reportName = EntityFileNameFormatter.GetReportFileName(connectionData.Name, reportEntity.Name, reportEntity.Id, fieldTitle, selectedFile.Extension); string temporaryFilePath = FileOperations.GetNewTempFilePath(Path.GetFileNameWithoutExtension(reportName), selectedFile.Extension); var textReport = reportEntity.GetAttributeValue <string>(fieldName); if (ContentComparerHelper.TryParseXml(textReport, out var doc)) { textReport = doc.ToString(); } File.WriteAllText(temporaryFilePath, textReport, new UTF8Encoding(false)); //DownloadReportDefinitionRequest rdlRequest = new DownloadReportDefinitionRequest //{ // ReportId = reportEntity.Id //}; //DownloadReportDefinitionResponse rdlResponse = (DownloadReportDefinitionResponse)service.Execute(rdlRequest); //using (XmlTextWriter reportDefinitionFile = new XmlTextWriter(temporaryFilePath, System.Text.Encoding.UTF8)) //{ // reportDefinitionFile.WriteRaw(rdlResponse.BodyText); // reportDefinitionFile.Close(); //} this._iWriteToOutput.WriteToOutput(connectionData, "Starting Compare Program for {0} and {1}", selectedFile.FriendlyFilePath, reportName); string fileLocalPath = selectedFile.FilePath; string fileLocalTitle = selectedFile.FileName; string filePath2 = temporaryFilePath; string fileTitle2 = connectionData.Name + "." + selectedFile.FileName + " - " + temporaryFilePath; await this._iWriteToOutput.ProcessStartProgramComparerAsync(connectionData, fileLocalPath, filePath2, fileLocalTitle, fileTitle2); }
private async void ClearUnmanagedSolution_Click(object sender, RoutedEventArgs e) { var solution = GetSelectedEntity(); if (solution == null) { return; } string question = string.Format(Properties.MessageBoxStrings.ClearSolutionFormat1, solution.UniqueName); if (MessageBox.Show(question, Properties.MessageBoxStrings.QuestionTitle, MessageBoxButton.OKCancel, MessageBoxImage.Question) != MessageBoxResult.OK) { return; } try { ToggleControls(false, Properties.WindowStatusStrings.ClearingSolutionFormat2, _service.ConnectionData.Name, solution.UniqueName); var commonConfig = CommonConfiguration.Get(); var descriptor = new SolutionComponentDescriptor(_service); descriptor.SetSettings(commonConfig); SolutionDescriptor solutionDescriptor = new SolutionDescriptor(_iWriteToOutput, _service, descriptor); this._iWriteToOutput.WriteToOutput(_service.ConnectionData, string.Empty); this._iWriteToOutput.WriteToOutput(_service.ConnectionData, "Creating backup Solution Components in '{0}'.", solution.UniqueName); { string fileName = EntityFileNameFormatter.GetSolutionFileName( _service.ConnectionData.Name , solution.UniqueName , "Components Backup" ); string filePath = Path.Combine(commonConfig.FolderForExport, FileOperations.RemoveWrongSymbols(fileName)); await solutionDescriptor.CreateFileWithSolutionComponentsAsync(filePath, solution.Id); this._iWriteToOutput.WriteToOutput(_service.ConnectionData, "Created backup Solution Components in '{0}': {1}", solution.UniqueName, filePath); this._iWriteToOutput.WriteToOutputFilePathUri(_service.ConnectionData, filePath); } { string fileName = EntityFileNameFormatter.GetSolutionFileName( _service.ConnectionData.Name , solution.UniqueName , "SolutionImage Backup before Clearing" , "xml" ); string filePath = Path.Combine(commonConfig.FolderForExport, FileOperations.RemoveWrongSymbols(fileName)); SolutionImage solutionImage = await solutionDescriptor.CreateSolutionImageAsync(solution.Id, solution.UniqueName); await solutionImage.SaveAsync(filePath); } SolutionComponentRepository repository = new SolutionComponentRepository(_service); await repository.ClearSolutionAsync(solution.UniqueName); ToggleControls(true, Properties.WindowStatusStrings.ClearingSolutionCompletedFormat2, _service.ConnectionData.Name, solution.UniqueName); } catch (Exception ex) { this._iWriteToOutput.WriteErrorToOutput(_service.ConnectionData, ex); ToggleControls(true, Properties.WindowStatusStrings.ClearingSolutionFailedFormat2, _service.ConnectionData.Name, solution.UniqueName); } }
private async Task ThreeFileDifferenceReport(SelectedFile selectedFile, string fieldName, string fieldTitle, ConnectionData connectionData1, ConnectionData connectionData2, ShowDifferenceThreeFileType differenceType, CommonConfiguration commonConfig) { if (differenceType == ShowDifferenceThreeFileType.ThreeWay) { if (!File.Exists(selectedFile.FilePath)) { this._iWriteToOutput.WriteToOutput(null, Properties.OutputStrings.FileNotExistsFormat1, selectedFile.FilePath); return; } } var doubleConnection = await ConnectAndWriteToOutputDoubleConnectionAsync(connectionData1, connectionData2); if (doubleConnection == null) { return; } var service1 = doubleConnection.Item1; var service2 = doubleConnection.Item2; if (string.IsNullOrEmpty(fieldName)) { fieldName = Report.Schema.Attributes.originalbodytext; fieldTitle = Report.Schema.Headers.originalbodytext; } // Репозиторий для работы с веб-ресурсами ReportRepository reportRepository1 = new ReportRepository(service1); ReportRepository reportRepository2 = new ReportRepository(service2); var taskReport1 = reportRepository1.FindAsync(selectedFile.FileName); var taskReport2 = reportRepository2.FindAsync(selectedFile.FileName); Report reportEntity1 = await taskReport1; Report reportEntity2 = await taskReport2; if (reportEntity1 != null) { this._iWriteToOutput.WriteToOutput(null, "{0}: Report founded by name.", connectionData1.Name); connectionData1.AddMapping(reportEntity1.Id, selectedFile.FriendlyFilePath); connectionData1.Save(); } else { Guid?reportId = connectionData1.GetLastLinkForFile(selectedFile.FriendlyFilePath); if (reportId.HasValue) { reportEntity1 = await reportRepository1.GetByIdAsync(reportId.Value); if (reportEntity1 != null) { this._iWriteToOutput.WriteToOutput(null, "{0}: Report not founded by name. Last link report is selected for difference.", connectionData1.Name); connectionData1.AddMapping(reportEntity1.Id, selectedFile.FriendlyFilePath); connectionData1.Save(); } } } if (reportEntity2 != null) { this._iWriteToOutput.WriteToOutput(null, "{0}: Report founded by name.", connectionData2.Name); connectionData2.AddMapping(reportEntity2.Id, selectedFile.FriendlyFilePath); connectionData2.Save(); } else { Guid?reportId = connectionData2.GetLastLinkForFile(selectedFile.FriendlyFilePath); if (reportId.HasValue) { reportEntity2 = await reportRepository2.GetByIdAsync(reportId.Value); if (reportEntity2 != null) { this._iWriteToOutput.WriteToOutput(null, "{0}: Report not founded by name. Last link report is selected for difference.", connectionData2.Name); connectionData2.AddMapping(reportEntity2.Id, selectedFile.FriendlyFilePath); connectionData2.Save(); } } } if (!File.Exists(selectedFile.FilePath)) { this._iWriteToOutput.WriteToOutput(null, Properties.OutputStrings.FileNotExistsFormat1, selectedFile.FilePath); } if (reportEntity1 == null) { this._iWriteToOutput.WriteToOutput(null, "{0}: Report not founded in CRM: {1}", connectionData1.Name, selectedFile.FileName); } if (reportEntity2 == null) { this._iWriteToOutput.WriteToOutput(null, "{0}: Report not founded in CRM: {1}", connectionData2.Name, selectedFile.FileName); } string fileLocalPath = selectedFile.FilePath; string fileLocalTitle = selectedFile.FileName; string filePath1 = string.Empty; string fileTitle1 = string.Empty; string filePath2 = string.Empty; string fileTitle2 = string.Empty; if (reportEntity1 != null) { var textReport = reportEntity1.GetAttributeValue <string>(fieldName); if (ContentComparerHelper.TryParseXml(textReport, out var doc)) { textReport = doc.ToString(); } var reportName = EntityFileNameFormatter.GetReportFileName(connectionData1.Name, reportEntity1.Name, reportEntity1.Id, fieldTitle, selectedFile.Extension); filePath1 = FileOperations.GetNewTempFilePath(Path.GetFileNameWithoutExtension(reportName), selectedFile.Extension); fileTitle1 = connectionData1.Name + "." + selectedFile.FileName + " - " + filePath1; File.WriteAllText(filePath1, textReport, new UTF8Encoding(false)); } if (reportEntity2 != null) { var textReport = reportEntity2.GetAttributeValue <string>(fieldName); if (ContentComparerHelper.TryParseXml(textReport, out var doc)) { textReport = doc.ToString(); } var reportName = EntityFileNameFormatter.GetReportFileName(connectionData2.Name, reportEntity2.Name, reportEntity2.Id, fieldTitle, selectedFile.Extension); filePath2 = FileOperations.GetNewTempFilePath(Path.GetFileNameWithoutExtension(reportName), selectedFile.Extension); fileTitle1 = connectionData2.Name + "." + selectedFile.FileName + " - " + filePath2; File.WriteAllText(filePath2, textReport, new UTF8Encoding(false)); } switch (differenceType) { case ShowDifferenceThreeFileType.OneByOne: ShowDifferenceOneByOne(commonConfig, connectionData1, connectionData2, fileLocalPath, fileLocalTitle, filePath1, fileTitle1, filePath2, fileTitle2); break; case ShowDifferenceThreeFileType.TwoConnections: await this._iWriteToOutput.ProcessStartProgramComparerAsync(connectionData1, filePath1, filePath2, fileTitle1, fileTitle2, connectionData2); break; case ShowDifferenceThreeFileType.ThreeWay: ShowDifferenceThreeWay(commonConfig, connectionData1, connectionData2, fileLocalPath, fileLocalTitle, filePath1, fileTitle1, filePath2, fileTitle2); break; default: break; } }
private async Task SaveSelectedPlaylistsAsync() { if (this.SelectedPlaylists != null && this.SelectedPlaylists.Count > 0) { if (this.SelectedPlaylists.Count > 1) { // Save all the selected playlists // ------------------------------- var dlg = new WPFFolderBrowserDialog(); if ((bool)dlg.ShowDialog()) { try { ExportPlaylistsResult result = await this.collectionService.ExportPlaylistsAsync(this.SelectedPlaylists, dlg.FileName); if (result == ExportPlaylistsResult.Error) { this.dialogService.ShowNotification( 0xe711, 16, ResourceUtils.GetStringResource("Language_Error"), ResourceUtils.GetStringResource("Language_Error_Saving_Playlists"), ResourceUtils.GetStringResource("Language_Ok"), true, ResourceUtils.GetStringResource("Language_Log_File")); } } catch (Exception ex) { LogClient.Instance.Logger.Error("Exception: {0}", ex.Message); this.dialogService.ShowNotification( 0xe711, 16, ResourceUtils.GetStringResource("Language_Error"), ResourceUtils.GetStringResource("Language_Error_Saving_Playlists"), ResourceUtils.GetStringResource("Language_Ok"), true, ResourceUtils.GetStringResource("Language_Log_File")); } } } else if (this.SelectedPlaylists.Count == 1) { // Save 1 playlist // --------------- var dlg = new Microsoft.Win32.SaveFileDialog(); dlg.FileName = FileOperations.SanitizeFilename(this.SelectedPlaylists[0].PlaylistName); dlg.DefaultExt = FileFormats.M3U; dlg.Filter = string.Concat(ResourceUtils.GetStringResource("Language_Playlists"), " (", FileFormats.M3U, ")|*", FileFormats.M3U); if ((bool)dlg.ShowDialog()) { try { ExportPlaylistsResult result = await this.collectionService.ExportPlaylistAsync(this.SelectedPlaylists[0], dlg.FileName, false); if (result == ExportPlaylistsResult.Error) { this.dialogService.ShowNotification( 0xe711, 16, ResourceUtils.GetStringResource("Language_Error"), ResourceUtils.GetStringResource("Language_Error_Saving_Playlist"), ResourceUtils.GetStringResource("Language_Ok"), true, ResourceUtils.GetStringResource("Language_Log_File")); } } catch (Exception ex) { LogClient.Instance.Logger.Error("Exception: {0}", ex.Message); this.dialogService.ShowNotification(0xe711, 16, ResourceUtils.GetStringResource("Language_Error"), ResourceUtils.GetStringResource("Language_Error_Saving_Playlist"), ResourceUtils.GetStringResource("Language_Ok"), true, ResourceUtils.GetStringResource("Language_Log_File")); } } } else { // Should not happen } } }
/// <summary> /// Selects all data from the file /// </summary> /// <returns></returns> public List<EquipmentMaintenance> SelectAllData() { FileOperations objEquipMaintenanceDB = new FileOperations(); return GetEquipmentMaintenaceColl(objEquipMaintenanceDB.ReadAll(EquipmentMaintenaceFilePath)); }