private static List <ModelData.VertexIndex> GenerateFaceLink_Helper(List <M3D.Model.Utils.Vector3> newVerticesList, List <ModelData.FaceIndex> newFaceList, ProgressHelper progressHelper = null) { var vertexIndexList = new List <ModelData.VertexIndex>(newFaceList.Count); foreach (M3D.Model.Utils.Vector3 newVertices in newVerticesList) { vertexIndexList.Add(new ModelData.VertexIndex(new List <int>())); } for (var index = 0; index < newFaceList.Count; ++index) { ModelData.FaceIndex newFace = newFaceList[index]; vertexIndexList[newFace.P1].Faces.Add(index); vertexIndexList[newFace.P2].Faces.Add(index); vertexIndexList[newFace.P3].Faces.Add(index); progressHelper?.Process(index); } return(vertexIndexList); }
private void cmdSave_Click(object sender, EventArgs e) { var uiKey = ProgressHelper.ProgressingStarted("Saving Modules..."); try { using (var transaction = _model.Store.TransactionManager.BeginTransaction(Guid.NewGuid().ToString())) { var module = _model.Modules.FirstOrDefault(x => x.Name == (string)cboModule.SelectedItem); foreach (var item in _nodeCache) { if (item.Value.Checked) { if (item.Key.Modules.Count(x => x == module) == 0) { item.Key.AddModule(module); //Add PK if entity if (item.Key is Entity) { var entity = item.Key as Entity; var pk = entity.Indexes.FirstOrDefault(x => x.IndexType == IndexTypeConstants.PrimaryKey); if (pk != null && !_model.IndexModules.Any(x => x.IndexID == pk.Id && x.ModuleId == module.Id)) { _model.IndexModules.Add(new IndexModule(_model.Partition) { IndexID = pk.Id, ModuleId = module.Id }); } } } } else { item.Key.RemoveModule(module); //Remove PK if entity if (item.Key is Entity) { var entity = item.Key as Entity; var pk = entity.Indexes.FirstOrDefault(x => x.IndexType == IndexTypeConstants.PrimaryKey); if (pk != null) { _model.IndexModules.Remove(x => (x.IndexID == pk.Id) && (x.ModuleId == module.Id)); } } } } //Now process the enforce bits var allRelations = _nodeCache.Keys.Where(x => x is EntityHasEntities).ToList(); foreach (var key in allRelations) { if (_nodeCache[key].Checked) { var relation = _nodeCache[key].Tag as EntityHasEntities; var relationModule = _model.RelationModules.FirstOrDefault(x => x.RelationID == relation.Id && x.ModuleId == module.Id); if (relationModule == null) { _model.RelationModules.Add(new RelationModule(_model.Partition) { RelationID = relation.Id, ModuleId = module.Id, Included = true, IsEnforced = _relationEnforcement[relation] }); } else { relationModule.IsEnforced = _relationEnforcement[relation]; } } } //Process Indexes var allIndexes = _nodeCache.Keys.Where(x => x is Index).ToList(); foreach (var key in allIndexes) { if (_nodeCache[key].Checked) { var index = _nodeCache[key].Tag as Index; var indexModule = _model.IndexModules.FirstOrDefault(x => x.IndexID == index.Id && x.ModuleId == module.Id); if (indexModule == null) { _model.IndexModules.Add(new IndexModule(_model.Partition) { IndexID = index.Id, ModuleId = module.Id, }); } } } transaction.Commit(); } cmdSave.Enabled = false; cmdCancel.Enabled = false; cboModule.Enabled = true; } catch (Exception ex) { throw; } finally { ProgressHelper.ProgressingComplete(uiKey); } }
public MvxUserInteraction(IMvxMainThreadDispatcher dispatcher) { _dispatcher = dispatcher; _progressHelper = new ProgressHelper(_dispatcher); }
protected async Task MergeAsync <T>(DbContext context, Type type, IList <T> entities, TableInfo tableInfo, OperationType operationType, Action <decimal> progress, CancellationToken cancellationToken, bool isAsync) where T : class { SqliteConnection connection = isAsync ? await OpenAndGetSqliteConnectionAsync(context, tableInfo.BulkConfig, cancellationToken).ConfigureAwait(false) : OpenAndGetSqliteConnection(context, tableInfo.BulkConfig); bool doExplicitCommit = false; try { if (context.Database.CurrentTransaction == null) { //context.Database.UseTransaction(connection.BeginTransaction()); doExplicitCommit = true; } var dbTransaction = doExplicitCommit ? connection.BeginTransaction() : context.Database.CurrentTransaction.GetUnderlyingTransaction(tableInfo.BulkConfig); var transaction = (SqliteTransaction)dbTransaction; var command = GetSqliteCommand(context, type, entities, tableInfo, connection, transaction); type = tableInfo.HasAbstractList ? entities[0].GetType() : type; int rowsCopied = 0; foreach (var item in entities) { LoadSqliteValues(tableInfo, item, command, context); if (isAsync) { await command.ExecuteNonQueryAsync(cancellationToken).ConfigureAwait(false); } else { command.ExecuteNonQuery(); } ProgressHelper.SetProgress(ref rowsCopied, entities.Count, tableInfo.BulkConfig, progress); } if (operationType == OperationType.Insert && tableInfo.BulkConfig.SetOutputIdentity && tableInfo.IdentityColumnName != null) // For Sqlite Identity can be set by Db only with pure Insert method { command.CommandText = SqlQueryBuilderSqlite.SelectLastInsertRowId(); object lastRowIdScalar = isAsync ? await command.ExecuteScalarAsync(cancellationToken).ConfigureAwait(false) : command.ExecuteScalar(); SetIdentityForOutput(entities, tableInfo, lastRowIdScalar); } if (doExplicitCommit) { transaction.Commit(); } } finally { if (isAsync) { await context.Database.CloseConnectionAsync().ConfigureAwait(false); } else { context.Database.CloseConnection(); } } }
public MasterDetails <M, D>[] ReadStream(TextReader reader) #endif { if (reader == null) { throw new ArgumentNullException("reader", "The reader of the Stream cant be null"); } if (mRecordSelector == null) { throw new BadUsageException("The Recordselector cant be null, please pass a not null Selector in the constructor."); } ResetFields(); mHeaderText = String.Empty; mFooterText = String.Empty; ArrayList resArray = new ArrayList(); ForwardReader freader = new ForwardReader(reader, mMasterInfo.mIgnoreLast); freader.DiscardForward = true; string currentLine, completeLine; mLineNumber = 1; completeLine = freader.ReadNextLine(); currentLine = completeLine; #if !MINI ProgressHelper.Notify(mNotifyHandler, mProgressMode, 0, -1); #endif int currentRecord = 0; if (mMasterInfo.mIgnoreFirst > 0) { for (int i = 0; i < mMasterInfo.mIgnoreFirst && currentLine != null; i++) { mHeaderText += currentLine + StringHelper.NewLine; currentLine = freader.ReadNextLine(); mLineNumber++; } } bool byPass = false; #if !GENERICS MasterDetails record = null; #else MasterDetails <M, D> record = null; #endif ArrayList tmpDetails = new ArrayList(); LineInfo line = new LineInfo(currentLine); line.mReader = freader; while (currentLine != null) { try { currentRecord++; line.ReLoad(currentLine); #if !MINI ProgressHelper.Notify(mNotifyHandler, mProgressMode, currentRecord, -1); #endif RecordAction action = mRecordSelector(currentLine); switch (action) { case RecordAction.Master: if (record != null) { #if !GENERICS record.mDetails = tmpDetails.ToArray(); #else record.mDetails = (D[])tmpDetails.ToArray(); #endif resArray.Add(record); } mTotalRecords++; #if !GENERICS record = new MasterDetails(); #else record = new MasterDetails <M, D>(); #endif tmpDetails.Clear(); #if !GENERICS object lastMaster = mMasterInfo.StringToRecord(line); #else M lastMaster = (M)mMasterInfo.StringToRecord(line); #endif if (lastMaster != null) { record.mMaster = lastMaster; } break; case RecordAction.Detail: #if !GENERICS object lastChild = mRecordInfo.StringToRecord(line); #else D lastChild = (D)mRecordInfo.StringToRecord(line); #endif if (lastChild != null) { tmpDetails.Add(lastChild); } break; default: break; } } catch (Exception ex) { switch (mErrorManager.ErrorMode) { case ErrorMode.ThrowException: byPass = true; throw; case ErrorMode.IgnoreAndContinue: break; case ErrorMode.SaveAndContinue: ErrorInfo err = new ErrorInfo(); err.mLineNumber = mLineNumber; err.mExceptionInfo = ex; // err.mColumnNumber = mColumnNum; err.mRecordString = completeLine; mErrorManager.AddError(err); break; } } finally { if (byPass == false) { currentLine = freader.ReadNextLine(); completeLine = currentLine; mLineNumber = freader.LineNumber; } } } if (record != null) { #if !GENERICS record.mDetails = tmpDetails.ToArray(); #else record.mDetails = (D[])tmpDetails.ToArray(); #endif resArray.Add(record); } if (mMasterInfo.mIgnoreLast > 0) { mFooterText = freader.RemainingText; } #if !GENERICS return((MasterDetails[])resArray.ToArray(typeof(MasterDetails))); #else return((MasterDetails <M, D>[])resArray.ToArray(typeof(MasterDetails <M, D>))); #endif }
//private void treeView1_AfterSelect(object sender, TreeViewEventArgs e) //{ // var d = e.Node.Tag as DataTreeItem; // if (d == null) txtChanged.Text = ""; // else txtChanged.Text = d.GetChangeText(); //} private void wizard1_BeforeSwitchPages(object sender, nHydrate.Wizard.Wizard.BeforeSwitchPagesEventArgs e) { if (wizard1.WizardPages[e.OldIndex] == pageConnection) { this.Cursor = Cursors.WaitCursor; try { var auditFields = new List <SpecialField>(); auditFields.Add(new SpecialField { Name = _model.CreatedByColumnName, Type = SpecialFieldTypeConstants.CreatedBy }); auditFields.Add(new SpecialField { Name = _model.CreatedDateColumnName, Type = SpecialFieldTypeConstants.CreatedDate }); auditFields.Add(new SpecialField { Name = _model.ModifiedByColumnName, Type = SpecialFieldTypeConstants.ModifiedBy }); auditFields.Add(new SpecialField { Name = _model.ModifiedDateColumnName, Type = SpecialFieldTypeConstants.ModifiedDate }); auditFields.Add(new SpecialField { Name = _model.ConcurrencyCheckColumnName, Type = SpecialFieldTypeConstants.Timestamp }); auditFields.Add(new SpecialField { Name = _model.TenantColumnName, Type = SpecialFieldTypeConstants.Tenant }); var pkey = ProgressHelper.ProgressingStarted("Importing...", true); try { if (optDatabaseTypeSQL.Checked) { DatabaseConnectionControl1.PersistSettings(); var connectionString = DatabaseConnectionControl1.ImportOptions.GetConnectionString(); var schemaModelHelper = new nHydrate.DataImport.SqlClient.SchemaModelHelper(); if (!schemaModelHelper.IsValidConnectionString(connectionString)) { this.Cursor = Cursors.Default; e.Cancel = true; MessageBox.Show("This not a valid connection string!", "Error!", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } LoadSqlServer(connectionString, auditFields); ProgressHelper.ProgressingComplete(pkey); } else if (optDatabaseTypePostgres.Checked) { var connectionString = txtConnectionStringPostgres.Text; if (!DslPackage.Objects.Postgres.ImportDomain.TestConnection(connectionString)) { this.Cursor = Cursors.Default; e.Cancel = true; MessageBox.Show("This not a valid connection string!", "Error!", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } var errorCount = LoadPostgres(connectionString, auditFields); ProgressHelper.ProgressingComplete(pkey); if (errorCount > 0) { MessageBox.Show("There were " + errorCount + " error on import.", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning); } } else { MessageBox.Show("Unknown database", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } } catch (Exception ex) { throw; } finally { ProgressHelper.ProgressingComplete(pkey); } if (!this.AreChanges()) { this.Cursor = Cursors.Default; e.Cancel = true; MessageBox.Show("This modelRoot is up-to-date. There are no changes to refresh.", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information); } } catch (Exception ex) { throw; } finally { this.Cursor = Cursors.Default; } } else if (wizard1.WizardPages[e.OldIndex] == pageConnection && wizard1.WizardPages[e.NewIndex] == pageEntities) { } else if (wizard1.WizardPages[e.OldIndex] == pageEntities && wizard1.WizardPages[e.NewIndex] == pageSummary) { //If there are no entities selected and relations are still checked then prompt var nodeCheckedList = tvwAdd.Nodes[0].Nodes.AsEnumerable <TreeNode>().Where(x => x.Checked).ToList(); nodeCheckedList.AddRange(tvwRefresh.Nodes[0].Nodes.AsEnumerable <TreeNode>().Where(x => x.Checked).ToList()); nodeCheckedList.AddRange(tvwDelete.Nodes[0].Nodes.AsEnumerable <TreeNode>().Where(x => x.Checked).ToList()); if (nodeCheckedList.Count == 0 && !chkIgnoreRelations.Checked) { var result = MessageBox.Show("There are no entities selected but relations will be refreshed. Do you want to turn off relation refreshing?", "Ignore Relations", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question); if (result == System.Windows.Forms.DialogResult.Yes) { chkIgnoreRelations.Checked = true; } else if (result == System.Windows.Forms.DialogResult.No) { //Do Nothing } else if (result == System.Windows.Forms.DialogResult.Cancel) { e.Cancel = true; return; } } //Moving the to the summary page CreateSummary(); } }
protected void Notify(ProgressChangeHandler handler, ProgressMode mode, int current, int total) { ProgressHelper.Notify(handler, mode, current, total); }
public MvxUserInteraction(IMvxMainThreadDispatcher dispatcher, IMvxAndroidCurrentTopActivity topActivity) { _topActivity = topActivity; _dispatcher = dispatcher; _progressHelper = new ProgressHelper(_dispatcher); }
static async Task Main(string[] args) { if (args.Length != 1) { Console.Error.WriteLine("Missing firmware name argument"); Environment.Exit(1); } var fwFile = args[0]; byte[] fwData = null; Console.Write("Checking firmware... "); try { #if WINDOWS_UWP var file = await StorageFile.GetFileFromPathAsync(fwFile); var buf = await FileIO.ReadBufferAsync(file); fwData = buf.ToArray(); #else fwData = File.ReadAllBytes(fwFile); #endif Firmware.Validate(fwData); Console.WriteLine("OK."); } catch (Exception ex) { handleError(ex); } Samba device = null; try { var devices = await Samba.FindAllAsync(); device = devices.FirstOrDefault(); if (device == null) { Console.Error.WriteLine("NXT not found. Is it properly plugged in via USB?"); Environment.Exit(1); } } catch (Exception ex) { handleError(ex); } try { nxt = await device.OpenAsync(); } catch (Exception ex) { handleError(ex); } Console.WriteLine("NXT device in reset mode located and opened."); Console.WriteLine("Starting firmware flash procedure now..."); try { using (var progress = new ProgressHelper("flashing")) { await device.FlashAsync(fwData, progress); } } catch (Exception ex) { handleError(ex); } Console.WriteLine("Firmware flash complete."); try { await device.GoAsync(0x00100000); } catch (Exception ex) { handleError(ex); } Console.WriteLine("New firmware started!"); try { nxt.Dispose(); } catch (Exception ex) { handleError(ex); } }
public MainListItemViewModel(object data, string path, string quality = "HIGH", string resolution = "720") { Progress = new ProgressHelper(); DLItemList = new ObservableCollection <DownloadItem>(); if (data.GetType() == typeof(ArtistAlbumList)) { ArtistAlbumList artistAlbumList = (ArtistAlbumList)data; TidalArtistAlbumList = artistAlbumList; Title = String.Format("{0} Total Albums:{1}", artistAlbumList.Artist.Name, artistAlbumList.TotalAlbums); Type = "Album List"; Quality = quality; BasePath = path + "\\Album\\"; Author = ""; foreach (Album album in artistAlbumList.Albums) { if (album.Tracks != null) { String fullBasePath = BasePath + Tool.GetAlbumFolderName(album); foreach (Track item in album.Tracks) { DLItemList.Add(new DownloadItem(DLItemList.Count, fullBasePath, Update, item, quality, album: album)); } } } } else if (data.GetType() == typeof(Album)) { Album album = (Album)data; TidalAlbum = album; Title = album.Title; Type = "Album"; Quality = quality; BasePath = path + "\\Album\\" + Tool.GetAlbumFolderName(album); Author = album.Artist.Name; CoverPath = BasePath + '\\' + Tool.GetAlbumCoverName(album); CoverData = album.CoverData; //init DownloadList if (album.Tracks != null) { foreach (Track item in album.Tracks) { DLItemList.Add(new DownloadItem(DLItemList.Count, BasePath, Update, item, quality, cover: CoverData, coverPath: CoverPath, album: album)); } } if (album.Videos != null) { foreach (Video item in album.Videos) { DLItemList.Add(new DownloadItem(DLItemList.Count, BasePath, Update, null, null, item, resolution, album: album)); } } } else if (data.GetType() == typeof(Video)) { Video video = (Video)data; TidalVideo = video; Title = video.Title; Type = "Video"; BasePath = path + "\\Video\\"; Author = video.Artist.Name; CoverPath = BasePath + '\\' + Tool.GetVideoCoverName(video); CoverData = video.CoverData; DLItemList.Add(new DownloadItem(DLItemList.Count, BasePath, Update, null, null, video, resolution)); } //Save Cover Cover = AIGS.Common.Convert.ConverByteArrayToBitmapImage(CoverData); FileHelper.Write(CoverData, true, CoverPath); }
private List <YoutubeItem> Run() { List <YoutubeItem> result = new List <YoutubeItem>(); var youtubeService = new YouTubeService(new BaseClientService.Initializer() { ApiKey = YouTubeAPIServiceHelper.API_KEY, ApplicationName = YouTubeAPIServiceHelper.APP_NAME }); var searchListRequest = youtubeService.Search.List("snippet"); searchListRequest.Q = _pattern; // Replace with your search term. searchListRequest.MaxResults = 25; // Call the search.list method to retrieve results matching the specified query term. String obj = null; //SearchListResponse searchListResponse = searchListRequest.Execute(); ProgressHelper.SetProgress("Getting data from Youtube API", 0); using (var stream = searchListRequest.ExecuteAsStream()) { using (MemoryStream writeStream = new MemoryStream()) { byte[] buffer = new byte[256]; int readed = 0; int index = 0; while ((readed = stream.Read(buffer, 0, buffer.Length)) != 0) { writeStream.Write(buffer, 0, readed); double percent = (double)index / (double)stream.Length * 100.0; ProgressHelper.SetProgress($"Loading data {percent.ToString("0.00")}%", (int)percent); } obj = Encoding.Default.GetString(writeStream.ToArray()); } } SearchListResponse returnedItems = Newtonsoft.Json.JsonConvert.DeserializeObject <SearchListResponse>(obj); string baseURI = @"https://www.youtube.com/watch?v={0}"; // Add each result to the appropriate list, and then display the lists of // matching videos, channels, and playlists. int idx = 0; foreach (var searchResult in returnedItems.Items) { double percent = ((double)idx / (double)searchListRequest.MaxResults) * 100.0; ProgressHelper.SetProgress($"Getting data {++idx} of {searchListRequest.MaxResults}", (int)percent); switch (searchResult.Id.Kind) { case "youtube#video": result.Add(new YoutubeMovie() { Name = searchResult.Snippet.Title, ImgSrc = searchResult.Snippet.Thumbnails.Default__.Url, Source = string.Format(baseURI, searchResult.Id) }); break; case "youtube#channel": result.Add(new YoutubeChanel() { ChanelId = searchResult.Id.ChannelId, Name = searchResult.Snippet.ChannelTitle, ImgSrc = searchResult.Snippet.Thumbnails.Default__.Url, Source = string.Format(baseURI, searchResult.Snippet.ChannelId) }); break; case "youtube#playlist": result.Add(new YoutubePlaylist() { PlaylistId = searchResult.Id.PlaylistId, Name = searchResult.Snippet.ChannelTitle, ImgSrc = searchResult.Snippet.Thumbnails?.Default__?.Url, Source = string.Format(baseURI, searchResult.Snippet.Title) }); break; } } ProgressHelper.SetProgress($"Finished.", 0); return(result); }
private void Editor_ProgressChanged(object sender, ProgressChangedEventArgs e) { ProgressHelper.UpdateState(Strings.Loading, e.UserState.ToString(), e.ProgressPercentage / 100.0); }
public void WriteStream(TextWriter writer, IEnumerable <MasterDetails <M, D> > records, int maxRecords) #endif { if (writer == null) { throw new ArgumentNullException("writer", "The writer of the Stream can be null"); } if (records == null) { throw new ArgumentNullException("records", "The records can be null. Try with an empty array."); } ResetFields(); if (mHeaderText != null && mHeaderText.Length != 0) { if (mHeaderText.EndsWith(StringHelper.NewLine)) { writer.Write(mHeaderText); } else { writer.WriteLine(mHeaderText); } } string currentLine = null; int max = maxRecords; if (records is IList) { max = Math.Min(max < 0 ? int.MaxValue : max, ((IList)records).Count); } #if !MINI ProgressHelper.Notify(mNotifyHandler, mProgressMode, 0, max); #endif int recIndex = 0; #if !GENERICS foreach (MasterDetails rec in records) #else foreach (MasterDetails <M, D> rec in records) #endif { if (recIndex == maxRecords) { break; } try { if (rec == null) { throw new BadUsageException("The record at index " + recIndex.ToString() + " is null."); } #if !MINI ProgressHelper.Notify(mNotifyHandler, mProgressMode, recIndex + 1, max); #endif currentLine = mMasterInfo.RecordToString(rec.mMaster); writer.WriteLine(currentLine); if (rec.mDetails != null) { for (int d = 0; d < rec.mDetails.Length; d++) { currentLine = mRecordInfo.RecordToString(rec.mDetails[d]); writer.WriteLine(currentLine); } } } catch (Exception ex) { switch (mErrorManager.ErrorMode) { case ErrorMode.ThrowException: throw; case ErrorMode.IgnoreAndContinue: break; case ErrorMode.SaveAndContinue: ErrorInfo err = new ErrorInfo(); err.mLineNumber = mLineNumber; err.mExceptionInfo = ex; // err.mColumnNumber = mColumnNum; err.mRecordString = currentLine; mErrorManager.AddError(err); break; } } } mTotalRecords = recIndex; if (mFooterText != null && mFooterText != string.Empty) { if (mFooterText.EndsWith(StringHelper.NewLine)) { writer.Write(mFooterText); } else { writer.WriteLine(mFooterText); } } }
private static List <ModelData.EdgeIndex> GenerateEndgeList(List <ModelData.FaceIndex> faceList, ref ProgressHelper progressHelper) { var hashCollection = new Dictionary <ModelData.EdgeIndex, ModelData.EdgeIndex>(); for (var index = 0; index < faceList.Count; ++index) { ModelData.FaceIndex face = faceList[index]; ModelData.AppendEdgeToHash_Helper(ref hashCollection, index, face.P1, face.P2); ModelData.AppendEdgeToHash_Helper(ref hashCollection, index, face.P2, face.P3); ModelData.AppendEdgeToHash_Helper(ref hashCollection, index, face.P1, face.P3); progressHelper.Process(index); } return(hashCollection.Values.ToList <ModelData.EdgeIndex>()); }
/// <summary>Must Insert the records in a DataSource (DB, Excel, etc)</summary> /// <param name="records">The records to insert.</param> public override void InsertRecords(object[] records) { IDbTransaction trans = null; try { InitConnection(); if (mConn.State != ConnectionState.Open) { mConn.Open(); } var SQL = String.Empty; trans = InitTransaction(mConn); ProgressHelper.Notify(mNotifyHandler, mProgressMode, 0, records.Length); var recordNumber = 0; var batchCount = 0; foreach (var record in records) { // Insert Logic Here, must check duplicates recordNumber++; batchCount++; ProgressHelper.Notify(mNotifyHandler, mProgressMode, recordNumber, records.Length); SQL += GetInsertSql(record) + " "; if (ExecuteInBatch) { if (batchCount >= mExecuteInBatchSize) { ExecuteAndLeaveOpen(SQL); SQL = String.Empty; batchCount = 0; } } else { ExecuteAndLeaveOpen(SQL); SQL = String.Empty; } } if (SQL != null && SQL.Length != 0) { ExecuteAndLeaveOpen(SQL); SQL = String.Empty; } CommitTransaction(trans); } catch { RollBackTransaction(trans); throw; } finally { try { mConn.Close(); mConn.Dispose(); mConn = null; } catch { } } }
private T[] ReadStream(TextReader reader, int maxRecords, DataTable dt) #endif { #endif if (reader == null) { throw new ArgumentNullException("reader", "The reader of the Stream can´t be null"); } ResetFields(); mHeaderText = String.Empty; mFooterText = String.Empty; var resArray = new ArrayList(); var currentRecord = 0; var freader = new ForwardReader(reader, mRecordInfo.mIgnoreLast); freader.DiscardForward = true; string currentLine, completeLine; mLineNumber = 1; completeLine = freader.ReadNextLine(); currentLine = completeLine; #if !MINI ProgressHelper.Notify(mNotifyHandler, mProgressMode, 0, -1); #endif if (mRecordInfo.mIgnoreFirst > 0) { for (var i = 0; i < mRecordInfo.mIgnoreFirst && currentLine != null; i++) { mHeaderText += currentLine + StringHelper.NewLine; currentLine = freader.ReadNextLine(); mLineNumber++; } } var byPass = false; if (maxRecords < 0) { maxRecords = int.MaxValue; } var line = new LineInfo(currentLine); line.mReader = freader; while (currentLine != null && currentRecord < maxRecords) { try { mTotalRecords++; currentRecord++; line.ReLoad(currentLine); var skip = false; #if !MINI ProgressHelper.Notify(mNotifyHandler, mProgressMode, currentRecord, -1); skip = OnBeforeReadRecord(currentLine); #endif if (skip == false) { var record = mRecordInfo.StringToRecord(line); #if !MINI #if !GENERICS skip = OnAfterReadRecord(currentLine, record); #else skip = OnAfterReadRecord(currentLine, (T)record); #endif #endif if (skip == false && record != null) { #if MINI resArray.Add(record); #else if (dt == null) { resArray.Add(record); } else { dt.Rows.Add(mRecordInfo.RecordToValues(record)); } #endif } } } catch (Exception ex) { switch (mErrorManager.ErrorMode) { case ErrorMode.ThrowException: byPass = true; throw; case ErrorMode.IgnoreAndContinue: break; case ErrorMode.SaveAndContinue: var err = new ErrorInfo(); err.mLineNumber = freader.LineNumber; err.mExceptionInfo = ex; // err.mColumnNumber = mColumnNum; err.mRecordString = completeLine; mErrorManager.AddError(err); break; } } finally { if (byPass == false) { currentLine = freader.ReadNextLine(); completeLine = currentLine; mLineNumber++; } } } if (mRecordInfo.mIgnoreLast > 0) { mFooterText = freader.RemainingText; } #if !GENERICS return((object[]) #else return (T[]) #endif resArray.ToArray(RecordType)); }
public void Export() { #if !R2014 if (CustomExporter.IsRenderingSupported() == false) { var message = @"检测到当前 Revit 实例对数据导出的支持存在问题, 原因可能是材质库未正确安装。 本次操作可能无法成功执行, 确定要继续吗?"; if (MessageBox.Show(this, message, Text, MessageBoxButtons.OKCancel, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) != DialogResult.OK) { return; } } #endif var visualStyle = cbVisualStyle.SelectedItem as VisualStyleInfo; if (visualStyle != null) { foreach (var p in visualStyle.Features) { _Features.FirstOrDefault(x => x.Type == p.Key)?.ChangeSelected(_Features, p.Value); } } var levelOfDetail = (cbLevelOfDetail.SelectedItem as ComboItemInfo) ?? _LevelOfDetailDefault; #region 更新界面选项到 _Features void SetFeature(FeatureType featureType, bool selected) { _Features.FirstOrDefault(x => x.Type == featureType)?.ChangeSelected(_Features, selected); } SetFeature(FeatureType.Export2DViewAll, rb2DViewsAll.Checked); SetFeature(FeatureType.Export2DViewOnlySheet, rb2DViewsOnlySheet.Checked); SetFeature(FeatureType.GenerateThumbnail, cbGenerateThumbnail.Checked); SetFeature(FeatureType.GenerateElementData, cbGeneratePropDbJson.Checked); SetFeature(FeatureType.GenerateModelsDb, cbGeneratePropDbSqlite.Checked); SetFeature(FeatureType.ExportGrids, cbIncludeGrids.Checked); SetFeature(FeatureType.ExportRooms, cbIncludeRooms.Checked); SetFeature(FeatureType.ExcludeProperties, cbExcludeElementProperties.Checked); SetFeature(FeatureType.ExcludeLines, cbExcludeLines.Checked); SetFeature(FeatureType.ExcludePoints, cbExcludeModelPoints.Checked); SetFeature(FeatureType.OnlySelected, cbExcludeUnselectedElements.Checked); SetFeature(FeatureType.ConsolidateGroup, cbConsolidateArrayGroup.Checked); SetFeature(FeatureType.ConsolidateAssembly, cbConsolidateAssembly.Checked); SetFeature(FeatureType.UseLevelCategory, rbGroupByLevelDefault.Checked); SetFeature(FeatureType.UseNwLevelCategory, rbGroupByLevelNavisworks.Checked); SetFeature(FeatureType.UseBoundLevelCategory, rbGroupByLevelBoundingBox.Checked); SetFeature(FeatureType.UseCurrentViewport, cbUseCurrentViewport.Checked); #endregion var isCanncelled = false; using (var session = App.CreateSession(Application.licenseKey)) { if (session.IsValid == false) { new Plugin_manage().ShowDialog(); return; } #region 保存设置 var config = _Config.Local; config.Features = _Features.Where(x => x.Selected).Select(x => x.Type).ToList(); config.LastTargetPath = Path.Combine(TempPath, modelName + ".svfzip"); config.VisualStyle = visualStyle?.Key; config.LevelOfDetail = levelOfDetail?.Value ?? -1; _Config.Save(); #endregion var features = _Features.Where(x => x.Selected && x.Enabled).ToDictionary(x => x.Type, x => true); using (var progress = new ProgressHelper(this, Strings.MessageExporting)) { var cancellationToken = progress.GetCancellationToken(); StartExport(_UIDocument, _View, config, ExportType.Zip, null, features, false, progress.GetProgressCallback(), cancellationToken); isCanncelled = cancellationToken.IsCancellationRequested; } if (isCanncelled == false) { var t = new Thread(UploadFile); t.IsBackground = false; t.Start(); Enabled = false; progressBar1.Value = 50; } } }
public void WriteStream(TextWriter writer, IEnumerable <T> records, int maxRecords) #endif { if (writer == null) { throw new ArgumentNullException("writer", "The writer of the Stream can be null"); } if (records == null) { throw new ArgumentNullException("records", "The records can be null. Try with an empty array."); } ResetFields(); if (mHeaderText != null && mHeaderText.Length != 0) { if (mHeaderText.EndsWith(StringHelper.NewLine)) { writer.Write(mHeaderText); } else { writer.WriteLine(mHeaderText); } } string currentLine = null; //ConstructorInfo constr = mType.GetConstructor(new Type[] {}); var max = maxRecords; if (records is IList) { max = Math.Min(max < 0 ? int.MaxValue : max, ((IList)records).Count); } #if !MINI ProgressHelper.Notify(mNotifyHandler, mProgressMode, 0, max); #endif var recIndex = 0; var first = true; #if !GENERICS foreach (var rec in records) #else foreach (T rec in records) #endif { if (recIndex == maxRecords) { break; } mLineNumber++; try { if (rec == null) { throw new BadUsageException("The record at index " + recIndex.ToString() + " is null."); } if (first) { first = false; if (mRecordInfo.mRecordType.IsInstanceOfType(rec) == false) { throw new BadUsageException("This engine works with record of type " + mRecordInfo.mRecordType.Name + " and you use records of type " + rec.GetType().Name); } } var skip = false; #if !MINI ProgressHelper.Notify(mNotifyHandler, mProgressMode, recIndex + 1, max); skip = OnBeforeWriteRecord(rec); #endif if (skip == false) { currentLine = mRecordInfo.RecordToString(rec); #if !MINI currentLine = OnAfterWriteRecord(currentLine, rec); #endif writer.WriteLine(currentLine); } } catch (Exception ex) { switch (mErrorManager.ErrorMode) { case ErrorMode.ThrowException: throw; case ErrorMode.IgnoreAndContinue: break; case ErrorMode.SaveAndContinue: var err = new ErrorInfo(); err.mLineNumber = mLineNumber; err.mExceptionInfo = ex; // err.mColumnNumber = mColumnNum; err.mRecordString = currentLine; mErrorManager.AddError(err); break; } } recIndex++; } mTotalRecords = recIndex; if (mFooterText != null && mFooterText != string.Empty) { if (mFooterText.EndsWith(StringHelper.NewLine)) { writer.Write(mFooterText); } else { writer.WriteLine(mFooterText); } } }
public void GetEstimatedTimeLeftNullStopwatch() { const double prc = 10.0; Assert.Throws <ArgumentNullException>(() => ProgressHelper.GetEstimatedTimeLeft(prc, null)); }
public void Export() { if (Autodesk.Navisworks.Api.Application.ActiveDocument.Models.Count == 0) { var message = @"未打开任何模型, 确定要继续吗?"; if (MessageBox.Show(this, message, Text, MessageBoxButtons.OKCancel, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) != DialogResult.OK) { return; } return; } var visualStyle = cbVisualStyle.SelectedItem as VisualStyleInfo; if (visualStyle != null) { foreach (var p in visualStyle.Features) { _Features.FirstOrDefault(x => x.Type == p.Key)?.ChangeSelected(_Features, p.Value); } } #region 更新界面选项到 _Features void SetFeature(FeatureType featureType, bool selected) { _Features.FirstOrDefault(x => x.Type == featureType)?.ChangeSelected(_Features, selected); } SetFeature(FeatureType.ExportHyperlink, cbHyperlink.Checked); SetFeature(FeatureType.GenerateThumbnail, cbGenerateThumbnail.Checked); SetFeature(FeatureType.GenerateElementData, cbGeneratePropDbJson.Checked); SetFeature(FeatureType.GenerateModelsDb, cbGeneratePropDbSqlite.Checked); SetFeature(FeatureType.ExcludeProperties, cbExcludeElementProperties.Checked); SetFeature(FeatureType.ExcludeLines, cbExcludeLines.Checked); SetFeature(FeatureType.ExcludePoints, cbExcludeModelPoints.Checked); SetFeature(FeatureType.OnlySelected, cbExcludeUnselectedElements.Checked); #endregion var isCanncelled = false; using (var session = App.CreateSession()) { if (session.IsValid == false) { new License().ShowDialog(this); return; } var config = _Config.Local; config.Features = _Features.Where(x => x.Selected).Select(x => x.Type).ToList(); config.LastTargetPath = TempPath + ModelName + ".svfzip"; config.VisualStyle = visualStyle?.Key; _Config.Save(); var features = _Features.Where(x => x.Selected && x.Enabled).ToDictionary(x => x.Type, x => true); using (var progress = new ProgressHelper(this, Strings.MessageExporting)) { var cancellationToken = progress.GetCancellationToken(); StartExport(config, ExportType.Zip, null, features, false, progress.GetProgressCallback(), cancellationToken); isCanncelled = cancellationToken.IsCancellationRequested; } if (isCanncelled == false) { UploadFile(); Enabled = false; } } }
private void OnProgressChanged(object sender, EventArgs e) { lblProgress.Text = ProgressHelper.FormatProgressLine(_downloader.BytesDownloaded, _downloader.ContentLength); prgProgress.Value = ProgressHelper.GetProgressPercentage(_downloader.BytesDownloaded, _downloader.ContentLength); }
public void WhenTotalEqualsZero_ThenThrowsException() { var ex = Assert.Throws <ArgumentException>(() => ProgressHelper.ValidateInputs(current: 0, total: 0)); Assert.Equal("Unable to write progress. Total below ore equal zero.", ex.Message); }
public async Task InsertAsync <T>(DbContext context, Type type, IList <T> entities, TableInfo tableInfo, Action <decimal> progress, CancellationToken cancellationToken, bool isAsync) { SqliteConnection connection = tableInfo.SqliteConnection; if (connection == null) { connection = isAsync ? await OpenAndGetSqliteConnectionAsync(context, tableInfo.BulkConfig, cancellationToken).ConfigureAwait(false) : OpenAndGetSqliteConnection(context, tableInfo.BulkConfig); } bool doExplicitCommit = false; try { if (context.Database.CurrentTransaction == null) { //context.Database.UseTransaction(connection.BeginTransaction()); doExplicitCommit = true; } SqliteTransaction transaction = tableInfo.SqliteTransaction; if (transaction == null) { var dbTransaction = doExplicitCommit ? connection.BeginTransaction() : context.Database.CurrentTransaction.GetUnderlyingTransaction(tableInfo.BulkConfig); transaction = (SqliteTransaction)dbTransaction; } else { doExplicitCommit = false; } var command = GetSqliteCommand(context, type, entities, tableInfo, connection, transaction); type = tableInfo.HasAbstractList ? entities[0].GetType() : type; int rowsCopied = 0; foreach (var item in entities) { LoadSqliteValues(tableInfo, item, command, context); if (isAsync) { await command.ExecuteNonQueryAsync(cancellationToken).ConfigureAwait(false); } else { command.ExecuteNonQuery(); } ProgressHelper.SetProgress(ref rowsCopied, entities.Count, tableInfo.BulkConfig, progress); } if (doExplicitCommit) { transaction.Commit(); } } finally { if (doExplicitCommit) { if (isAsync) { await context.Database.CloseConnectionAsync().ConfigureAwait(false); } else { context.Database.CloseConnection(); } } } }
public void WhenCurrentLessThanZero_ThenThrowsException() { var ex = Assert.Throws <ArgumentException>(() => ProgressHelper.ValidateInputs(current: -1, total: 1)); Assert.Equal("Unable to write progress. Current below zero.", ex.Message); }
public void WriteStream(TextWriter writer, MasterDetails <M, D>[] records, int maxRecords) #endif { if (writer == null) { throw new ArgumentNullException("writer", "The writer of the Stream can be null"); } if (records == null) { throw new ArgumentNullException("records", "The records can be null. Try with an empty array."); } ResetFields(); if (mHeaderText != null && mHeaderText.Length != 0) { if (mHeaderText.EndsWith(StringHelper.NewLine)) { writer.Write(mHeaderText); } else { writer.WriteLine(mHeaderText); } } string currentLine = null; //ConstructorInfo constr = mType.GetConstructor(new Type[] {}); int max = records.Length; if (maxRecords >= 0) { max = Math.Min(records.Length, maxRecords); } #if !MINI ProgressHelper.Notify(mNotifyHandler, mProgressMode, 0, max); #endif for (int i = 0; i < max; i++) { try { if (records[i] == null) { throw new BadUsageException("The record at index " + i.ToString() + " is null."); } #if !MINI ProgressHelper.Notify(mNotifyHandler, mProgressMode, i + 1, max); #endif currentLine = mMasterInfo.RecordToString(records[i].mMaster); writer.WriteLine(currentLine); if (records[i].mDetails != null) { for (int d = 0; d < records[i].mDetails.Length; d++) { currentLine = mRecordInfo.RecordToString(records[i].mDetails[d]); writer.WriteLine(currentLine); } } } catch (Exception ex) { switch (mErrorManager.ErrorMode) { case ErrorMode.ThrowException: throw; case ErrorMode.IgnoreAndContinue: break; case ErrorMode.SaveAndContinue: ErrorInfo err = new ErrorInfo(); err.mLineNumber = mLineNumber; err.mExceptionInfo = ex; // err.mColumnNumber = mColumnNum; err.mRecordString = currentLine; mErrorManager.AddError(err); break; } } } mTotalRecords = records.Length; if (mFooterText != null && mFooterText != string.Empty) { if (mFooterText.EndsWith(StringHelper.NewLine)) { writer.Write(mFooterText); } else { writer.WriteLine(mFooterText); } } }
public void WhenTotalLessThanCurrent_ThenThrowsException() { var ex = Assert.Throws <ArgumentException>(() => ProgressHelper.ValidateInputs(current: 2, total: 1)); Assert.Equal("Unable to write progress. Total less than current.", ex.Message); }
private void ModelUtilitiesForm_KeyDown(object sender, KeyEventArgs e) { if (e.KeyCode == Keys.Escape) { this.Close(); } //HIDDEN - Turn off transform names if (e.KeyCode == Keys.Q && e.Control) { if (_model.TransformNames) { if (MessageBox.Show("Rename all items to Pascal name?", "Rename", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == System.Windows.Forms.DialogResult.Yes) { var uiKey = ProgressHelper.ProgressingStarted("Converting...", true, 60); try { using (var transaction = _store.TransactionManager.BeginTransaction(Guid.NewGuid().ToString())) { _model.Entities.ForEach(x => x.Name = x.PascalName); _model.Entities.ForEach(x => x.Fields.ForEach(y => y.Name = y.PascalName)); _model.Views.ForEach(x => x.Name = x.PascalName); _model.Views.ForEach(x => x.Fields.ForEach(y => y.Name = y.PascalName)); _model.StoredProcedures.ForEach(x => x.Name = x.PascalName); _model.StoredProcedures.ForEach(x => x.Fields.ForEach(y => y.Name = y.PascalName)); _model.StoredProcedures.ForEach(x => x.Parameters.ForEach(y => y.Name = y.PascalName)); _model.Functions.ForEach(x => x.Name = x.PascalName); _model.Functions.ForEach(x => x.Fields.ForEach(y => y.Name = y.PascalName)); _model.Functions.ForEach(x => x.Parameters.ForEach(y => y.Name = y.PascalName)); _model.TransformNames = false; _model.CreatedByColumnName = nHydrate.Generator.Common.Util.StringHelper.DatabaseNameToPascalCase(_model.CreatedByColumnName); _model.CreatedDateColumnName = nHydrate.Generator.Common.Util.StringHelper.DatabaseNameToPascalCase(_model.CreatedDateColumnName); _model.ModifiedByColumnName = nHydrate.Generator.Common.Util.StringHelper.DatabaseNameToPascalCase(_model.ModifiedByColumnName); _model.ModifiedDateColumnName = nHydrate.Generator.Common.Util.StringHelper.DatabaseNameToPascalCase(_model.ModifiedDateColumnName); _model.TimestampColumnName = nHydrate.Generator.Common.Util.StringHelper.DatabaseNameToPascalCase(_model.TimestampColumnName); transaction.Commit(); } this.Close(); } catch (Exception ex) { ProgressHelper.ProgressingComplete(uiKey); throw; } finally { ProgressHelper.ProgressingComplete(uiKey); } } } } //HIDDEN else if (e.KeyCode == Keys.W && e.Control) { var F = new UserDefinedScriptOrderForm(_model, _store); F.ShowDialog(); } }
protected async Task InsertAsync <T>(DbContext context, Type type, IList <T> entities, TableInfo tableInfo, Action <decimal> progress, CancellationToken cancellationToken, bool isAsync) { NpgsqlConnection connection = tableInfo.NpgsqlConnection; bool closeConnectionInternally = false; if (connection == null) { (connection, closeConnectionInternally) = isAsync ? await OpenAndGetNpgsqlConnectionAsync(context, tableInfo.BulkConfig, cancellationToken).ConfigureAwait(false) : OpenAndGetNpgsqlConnection(context, tableInfo.BulkConfig); } try { string sqlCopy = SqlQueryBuilderPostgreSql.InsertIntoTable(tableInfo, tableInfo.InsertToTempTable ? OperationType.InsertOrUpdate : OperationType.Insert); using var writer = isAsync ? await connection.BeginBinaryImportAsync(sqlCopy, cancellationToken).ConfigureAwait(false) : connection.BeginBinaryImport(sqlCopy); var uniqueColumnName = tableInfo.PrimaryKeysPropertyColumnNameDict.Values.ToList().FirstOrDefault(); var doKeepIdentity = tableInfo.BulkConfig.SqlBulkCopyOptions == SqlBulkCopyOptions.KeepIdentity; var propertiesColumnDict = ((tableInfo.InsertToTempTable || doKeepIdentity) && tableInfo.IdentityColumnName == uniqueColumnName) ? tableInfo.PropertyColumnNamesDict : tableInfo.PropertyColumnNamesDict.Where(a => a.Value != tableInfo.IdentityColumnName); var propertiesNames = propertiesColumnDict.Select(a => a.Key).ToList(); var entitiesCopiedCount = 0; foreach (var entity in entities) { if (isAsync) { await writer.StartRowAsync(cancellationToken).ConfigureAwait(false); } else { writer.StartRow(); } foreach (var propertyName in propertiesNames) { if (tableInfo.DefaultValueProperties.Contains(propertyName) && !tableInfo.PrimaryKeysPropertyColumnNameDict.ContainsKey(propertyName)) { continue; } var propertyValue = tableInfo.FastPropertyDict.ContainsKey(propertyName) ? tableInfo.FastPropertyDict[propertyName].Get(entity) : null; var propertyColumnName = tableInfo.PropertyColumnNamesDict.ContainsKey(propertyName) ? tableInfo.PropertyColumnNamesDict[propertyName] : string.Empty; var columnType = tableInfo.ColumnNamesTypesDict[propertyColumnName]; // string is 'text' which works fine if (columnType.StartsWith("character")) // when MaxLength is defined: 'character(1)' or 'character varying' { columnType = "character"; // 'character' is like 'string' } else if (columnType.StartsWith("varchar")) { columnType = "varchar"; } else if (columnType.StartsWith("numeric")) { columnType = "numeric"; } var convertibleDict = tableInfo.ConvertibleColumnConverterDict; if (convertibleDict.ContainsKey(propertyColumnName) && convertibleDict[propertyColumnName].ModelClrType.IsEnum) { if (propertyValue != null) { var clrType = tableInfo.ConvertibleColumnConverterDict[propertyColumnName].ProviderClrType; if (clrType == typeof(byte)) // columnType == "smallint" { propertyValue = (byte)propertyValue; } if (clrType == typeof(short)) { propertyValue = (short)propertyValue; } if (clrType == typeof(Int32)) { propertyValue = (int)propertyValue; } if (clrType == typeof(Int64)) { propertyValue = (long)propertyValue; } if (clrType == typeof(string)) { propertyValue = propertyValue.ToString(); } } } if (isAsync) { await writer.WriteAsync(propertyValue, columnType, cancellationToken).ConfigureAwait(false); } else { writer.Write(propertyValue, columnType); } } entitiesCopiedCount++; if (progress != null && entitiesCopiedCount % tableInfo.BulkConfig.NotifyAfter == 0) { progress?.Invoke(ProgressHelper.GetProgress(entities.Count, entitiesCopiedCount)); } } if (isAsync) { await writer.CompleteAsync(cancellationToken).ConfigureAwait(false); } else { writer.Complete(); } } finally { if (closeConnectionInternally) { //connection.Close(); if (isAsync) { await connection.CloseAsync(); //await context.Database.CloseConnectionAsync().ConfigureAwait(false); } else { connection.Close(); //context.Database.CloseConnection(); } } } }
public void Merge <T>(DbContext context, Type type, IList <T> entities, TableInfo tableInfo, OperationType operationType, Action <decimal> progress) where T : class { var connection = OpenAndGetSqliteConnection(context, tableInfo.BulkConfig); bool doExplicitCommit = false; try { if (context.Database.CurrentTransaction == null) { //context.Database.UseTransaction(connection.BeginTransaction()); doExplicitCommit = true; } var transaction = (SqliteTransaction)(context.Database.CurrentTransaction == null ? connection.BeginTransaction() : context.Database.CurrentTransaction.GetUnderlyingTransaction(tableInfo.BulkConfig)); var command = GetSqliteCommand(context, type, entities, tableInfo, connection, transaction); type = tableInfo.HasAbstractList ? entities[0].GetType() : type; int rowsCopied = 0; foreach (var item in entities) { LoadSqliteValues(tableInfo, item, command); command.ExecuteNonQuery(); ProgressHelper.SetProgress(ref rowsCopied, entities.Count, tableInfo.BulkConfig, progress); } if (operationType != OperationType.Delete && tableInfo.BulkConfig.SetOutputIdentity && tableInfo.IdentityColumnName != null) { command.CommandText = SqlQueryBuilderSqlite.SelectLastInsertRowId(); long lastRowIdScalar = (long)command.ExecuteScalar(); string identityPropertyName = tableInfo.IdentityColumnName; var identityPropertyInteger = false; var identityPropertyUnsigned = false; var identityPropertyByte = false; var identityPropertyShort = false; if (tableInfo.FastPropertyDict[identityPropertyName].Property.PropertyType == typeof(ulong)) { identityPropertyUnsigned = true; } else if (tableInfo.FastPropertyDict[identityPropertyName].Property.PropertyType == typeof(uint)) { identityPropertyInteger = true; identityPropertyUnsigned = true; } else if (tableInfo.FastPropertyDict[identityPropertyName].Property.PropertyType == typeof(int)) { identityPropertyInteger = true; } else if (tableInfo.FastPropertyDict[identityPropertyName].Property.PropertyType == typeof(ushort)) { identityPropertyShort = true; identityPropertyUnsigned = true; } else if (tableInfo.FastPropertyDict[identityPropertyName].Property.PropertyType == typeof(short)) { identityPropertyShort = true; } else if (tableInfo.FastPropertyDict[identityPropertyName].Property.PropertyType == typeof(byte)) { identityPropertyByte = true; identityPropertyUnsigned = true; } else if (tableInfo.FastPropertyDict[identityPropertyName].Property.PropertyType == typeof(sbyte)) { identityPropertyByte = true; } for (int i = entities.Count - 1; i >= 0; i--) { if (identityPropertyByte) { if (identityPropertyUnsigned) { tableInfo.FastPropertyDict[identityPropertyName].Set(entities[i], (byte)lastRowIdScalar); } else { tableInfo.FastPropertyDict[identityPropertyName].Set(entities[i], (sbyte)lastRowIdScalar); } } else if (identityPropertyShort) { if (identityPropertyUnsigned) { tableInfo.FastPropertyDict[identityPropertyName].Set(entities[i], (ushort)lastRowIdScalar); } else { tableInfo.FastPropertyDict[identityPropertyName].Set(entities[i], (short)lastRowIdScalar); } } else if (identityPropertyInteger) { if (identityPropertyUnsigned) { tableInfo.FastPropertyDict[identityPropertyName].Set(entities[i], (uint)lastRowIdScalar); } else { tableInfo.FastPropertyDict[identityPropertyName].Set(entities[i], (int)lastRowIdScalar); } } else { if (identityPropertyUnsigned) { tableInfo.FastPropertyDict[identityPropertyName].Set(entities[i], (ulong)lastRowIdScalar); } else { tableInfo.FastPropertyDict[identityPropertyName].Set(entities[i], lastRowIdScalar); } } lastRowIdScalar--; } } if (doExplicitCommit) { transaction.Commit(); } } finally { context.Database.CloseConnection(); } }
private static bool HashVertexesAndFaces_Helper(LinkedList <M3D.Model.Utils.Vector3> verticies, ref ProgressHelper progressHelper, out List <M3D.Model.Utils.Vector3> newVerticesList, out List <ModelData.FaceIndex> newFaceList) { newVerticesList = null; newFaceList = null; var num1 = 0; var num2 = 0; var source = new Dictionary <M3D.Model.Utils.Vector3, int>(); var faceIndexSet = new HashSet <ModelData.FaceIndex>(); var flag = ModelData.VerticiesFlipped(verticies); while (verticies.First != null) { M3D.Model.Utils.Vector3 vector3_1 = verticies.First.Value; ModelData.AssertIfNANOrNULL(vector3_1); verticies.RemoveFirst(); M3D.Model.Utils.Vector3 vector3_2 = verticies.First.Value; ModelData.AssertIfNANOrNULL(vector3_2); verticies.RemoveFirst(); M3D.Model.Utils.Vector3 vector3_3 = verticies.First.Value; ModelData.AssertIfNANOrNULL(vector3_3); verticies.RemoveFirst(); if (flag) { M3D.Model.Utils.Vector3 vector3_4 = vector3_1; vector3_1 = vector3_3; vector3_3 = vector3_4; } M3D.Model.Utils.Vector3 normal = ModelData.CalcNormal(vector3_1, vector3_2, vector3_3); if (!double.IsNaN(normal.X) && !double.IsNaN(normal.Y) && !double.IsNaN(normal.Z)) { int[] faceIndicies = new int[3]; M3D.Model.Utils.Vector3[] vector3Array = new M3D.Model.Utils.Vector3[3] { vector3_1, vector3_2, vector3_3 }; for (var index = 0; index < 3; ++index) { M3D.Model.Utils.Vector3 key = vector3Array[index]; int num3; if (source.ContainsKey(key)) { num3 = source[key]; } else { source.Add(key, num1); num3 = num1++; } faceIndicies[index] = num3; } for (var index1 = 0; index1 < 3; ++index1) { for (var index2 = index1 + 1; index2 < 3; ++index2) { if (faceIndicies[index1] == faceIndicies[index2]) { return(false); } } } var faceIndex = new FaceIndex(faceIndicies, normal); if (!faceIndexSet.Contains(faceIndex)) { faceIndexSet.Add(faceIndex); } progressHelper.Process(num2 += 3); } } IEnumerable <M3D.Model.Utils.Vector3> collection = source.OrderBy <KeyValuePair <M3D.Model.Utils.Vector3, int>, int>(pair => pair.Value).Select <KeyValuePair <M3D.Model.Utils.Vector3, int>, M3D.Model.Utils.Vector3>(pair => pair.Key); newVerticesList = new List <M3D.Model.Utils.Vector3>(collection); source.Clear(); newFaceList = new List <ModelData.FaceIndex>(faceIndexSet); faceIndexSet.Clear(); return(true); }