private StringFunctions(StringFunctions other) : base(other) { this.funcType = other.funcType; Query[] tmp = new Query[other.argList.Count]; { for (int i = 0; i < tmp.Length; i ++) { tmp[i] = Clone(other.argList[i]); } } this.argList = tmp; }
private StringFunctions(StringFunctions other) : base(other) { this.funcType = other.funcType; Query[] queryArray = new Query[other.argList.Count]; for (int i = 0; i < queryArray.Length; i++) { queryArray[i] = Query.Clone(other.argList[i]); } this.argList = queryArray; }
public static string CleanYouTubeVideo(string strInput) { /* * http://www.youtube.com/watch?v=8c1Gd2PXgPg */ if (strInput.Contains("?v=")) { strInput = StringFunctions.AllAfter(strInput, "?v="); } else if (strInput.Contains("youtube.com/watch?")) { strInput = StringFunctions.AllAfter(strInput, "youtube.com/watch?"); } else if (strInput.Contains("youtu.be/")) { strInput = StringFunctions.AllAfter(strInput, "youtu.be/"); } return(strInput); }
private static QuestDictionary <string> PopulateInternal(Regex regex, string input) { if (!regex.IsMatch(input)) { throw new Exception(string.Format("String '{0}' is not a match for Regex '{1}'", input, regex.ToString())); } QuestDictionary <string> result = new QuestDictionary <string>(); foreach (string groupName in regex.GetGroupNames()) { if (!StringFunctions.IsNumeric(groupName)) { string groupMatch = regex.Match(input).Groups[groupName].Value; result.Add(groupName, groupMatch); } } return(result); }
public static List <Model.Error404Redirect> GetError404Redirects(int intAppID, string strClientID) { SqlCommand cmd; cmd = new SqlCommand("[dbo].[pr_Error404Redirect_SelectAll]"); cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@AppID", intAppID); if (!StringFunctions.IsNullOrWhiteSpace(strClientID)) { cmd.Parameters.AddWithValue("@ClientID", strClientID); } DataTable objTable = SqlHelper.ExecuteDataset(cmd, null, ConnectionStringName).Tables[0]; List <Model.Error404Redirect> lstModels = new List <Model.Error404Redirect>(); foreach (DataRow objRow in objTable.Rows) { lstModels.Add(GetError404RedirectModel(objRow)); } return(lstModels); }
public virtual async Task <IActionResult> Details(Guid id) { if (!HasDetails) { return(NotFound()); } TEntityDto entity = await this.entityManager.GetEntityAsync <TEntity, TEntityDto>(id); EntityDetailsViewModel model = new EntityDetailsViewModel(); model.Details = DetailsMapper.DtoMapper <TEntityDto>(entity); model.Title = $"{StringFunctions.SplitWordsByCapitalLetters(typeof(TEntity).Name)} Details"; string singleEntityName = StringFunctions.SplitWordsByCapitalLetters(typeof(TEntity).Name); ViewData[BreadcrumbEntityNamePluralPlaceholder] = singleEntityName.ToPluralString(); return(View("AbstractViews/Details", model)); }
static void AddDocComments(docMember member, CodeCommentStatementCollection comments) { if (member != null && comments != null) { if (member.summary != null) { comments.Add(new CodeCommentStatement("<summary>", true)); var noIndent = StringFunctions.TrimTrimIndentsOfArray(member.summary.Text); if (noIndent != null) { foreach (var item in noIndent) { comments.Add(new CodeCommentStatement(item, true)); } } comments.Add(new CodeCommentStatement("</summary>", true)); } } }
private static bool TrySetReservedValues(StateSave stateSave, string variableName, object value, InstanceSave instanceSave) { bool isReservedName = false; // Check for reserved names if (variableName == "Name") { stateSave.ParentContainer.Name = value as string; isReservedName = true; } else if (variableName == "Base Type") { stateSave.ParentContainer.BaseType = value.ToString(); isReservedName = true; // don't do anything } if (StringFunctions.ContainsNoAlloc(variableName, '.')) { string instanceName = variableName.Substring(0, variableName.IndexOf('.')); ElementSave elementSave = stateSave.ParentContainer; // This is a variable on an instance if (variableName.EndsWith(".Name")) { instanceSave.Name = (string)value; isReservedName = true; } else if (variableName.EndsWith(".Base Type")) { instanceSave.BaseType = value.ToString(); isReservedName = true; } else if (variableName.EndsWith(".Locked")) { instanceSave.Locked = (bool)value; isReservedName = true; } } return(isReservedName); }
private void addItemsToolStripMenuItem_Click(object sender, EventArgs e) { if (openFileDialog1.ShowDialog(this) == DialogResult.OK) { watch = new System.Threading.Timer(Tick, null, 0, 10); new Thread(() => { Thread.CurrentThread.IsBackground = true; foreach (string file in openFileDialog1.FileNames) { if (file.EndsWith(".rpf")) { TimeLabel.Text = "Scanning RPFs and Extracting Files ..."; RpfFile rpf = new RpfFile(file, Path.GetDirectoryName(file)); try { rpf.ScanStructure(null, null); var fileTypes = new List <string>() { ".ybn", ".ydr", ".yft", ".ydd" }; RPFFunctions.SearchRPF(rpf, file, CurrentList, fileTypes); } catch (Exception) { MessageBox.Show("Error can't read " + file + ".\nThis file has been skipped.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } } else { if (!StringFunctions.DoesItemExist(CurrentList, file)) { CurrentList.Items.Add(file); } } } StringFunctions.SetCount(CurrentList, FilesAddedLabel, startButton); watch.Dispose(); }).Start(); } }
private void PastedCopiedState() { ElementSave container = SelectedState.Self.SelectedElement; /////////////////////Early Out////////////////// if (container == null) { return; } //////////////////End Early Out//////////////// if (container.Categories.Count != 0) { MessageBox.Show("Pasting into elements with state categories may cause unexpected results. Please complain on codeplex!"); } StateSave newStateSave = mCopiedState.Clone(); newStateSave.Variables.RemoveAll(item => item.CanOnlyBeSetInDefaultState); newStateSave.ParentContainer = container; string name = mCopiedState.Name + "Copy"; name = StringFunctions.MakeStringUnique(name, container.States.Select(item => item.Name)); newStateSave.Name = name; container.States.Add(newStateSave); StateTreeViewManager.Self.RefreshUI(container); //SelectedState.Self.SelectedInstance = targetInstance; SelectedState.Self.SelectedStateSave = newStateSave; GumCommands.Self.FileCommands.TryAutoSaveElement(container); }
public void AddAllStemmed(IEnumerator <string> it) { while (it.MoveNext()) { string current = it.Current; Document d = new Document() { Name = current.GetNameWhenFirst() }; documents++; current = current.ConsumeName(); string[] words = current.Split(' '); foreach (string s in words) { string temp = StringFunctions.Normalize(s); //stem here temp = StringFunctions.StemmedWord(temp); d.WordCount++; KeyValuePair <string, Document> kvp = new KeyValuePair <string, Document>(temp, d); if (!PossibleContent.ContainsKey(kvp)) { PossibleContent.Add(new KeyValuePair <string, Document>(temp, d), new WordDocumentMetadata()); if (!WordDocumentAppearances.ContainsKey(temp)) { WordDocumentAppearances.Add(temp, new WordMetadata { DocumentAppearences = 0, IDF = -1 }); } WordDocumentAppearances[temp].DocumentAppearences++; WordDocumentAppearances[temp].Docs.Add(d.Name); } PossibleContent[kvp].Frequency++; } } calculateTFIDF(); }
private void GetFilesReferencedBy(GumProjectSave gumProjectSave, TopLevelOrRecursive topLevelOrRecursive, List <string> listToFill, ProjectOrDisk projectOrDisk) { AppState.Self.GumProjectSave = gumProjectSave; foreach (var element in gumProjectSave.Screens) { AddFilesReferencedBy(topLevelOrRecursive, listToFill, element, projectOrDisk); } foreach (var element in gumProjectSave.Components) { AddFilesReferencedBy(topLevelOrRecursive, listToFill, element, projectOrDisk); } foreach (var element in gumProjectSave.StandardElements) { AddFilesReferencedBy(topLevelOrRecursive, listToFill, element, projectOrDisk); } StringFunctions.RemoveDuplicates(listToFill); }
/// <summary> /// This method will return a string containing the command text and its parameters. /// </summary> /// <param name="cmd">A valid SqlCommand object</param> public static string GetQueryString(SqlCommand cmd) { string strParamList = cmd.CommandText + " "; foreach (SqlParameter arg in cmd.Parameters) { if (arg.Value != null) { if (StringFunctions.IsNumeric(arg.Value.ToString())) { strParamList += arg.ParameterName + "=" + arg.Value + ",\n"; } else { strParamList += arg.ParameterName + "='" + arg.Value + "',\n"; } } } strParamList = StringFunctions.Shave(strParamList, 2); return(strParamList); }
/// <summary> /// Performs the playback of actions in this module. /// </summary> /// <remarks>You should not call this method directly, instead pass the module /// instance to the <see cref="TestModuleRunner.Run(ITestModule)"/> method /// that will in turn invoke this method.</remarks> void ITestModule.Run() { Mouse.DefaultMoveTime = 300; Keyboard.DefaultKeyPressTime = 100; Delay.SpeedFactor = 1.0; ITEM item = new ITEM(); item.invOrServNumber = StringFunctions.RandStr("A(9)"); //item.ItemPrices[0].currency = "Canadian Dollars"; item.ItemPrices.Add(new ITEM_PRICE("Canadian Dollars")); item.ItemPrices[0].priceList = "Regular"; item.ItemPrices[0].pricePerSellingUnit = Functions.RandCashAmount(); InventoryServicesLedger._SA_Create(item); InventoryServicesLedger._SA_Close(); // set to global this.varItem = item.invOrServNumber; }
public void AddCircle() { Circle circle = new Circle(); ShapeManager.AddCircle(circle); circle.Color = EditorProperties.CircleColor; circle.X = SpriteManager.Camera.X; circle.Y = SpriteManager.Camera.Y; float scale = (float)Math.Abs( 18 / SpriteManager.Camera.PixelsPerUnitAt(0)); circle.Radius = scale; EditorData.ShapeCollection.Circles.Add(circle); circle.Name = "Circle" + EditorData.Circles.Count; StringFunctions.MakeNameUnique <Circle>(circle, EditorData.Circles); }
public void AddSphere() { Sphere sphere = new Sphere(); ShapeManager.AddSphere(sphere); sphere.Color = EditorProperties.SphereColor; sphere.X = SpriteManager.Camera.X; sphere.Y = SpriteManager.Camera.Y; float scale = (float)Math.Abs( 18 / SpriteManager.Camera.PixelsPerUnitAt(0)); sphere.Radius = scale; EditorData.ShapeCollection.Spheres.Add(sphere); sphere.Name = "Sphere" + EditorData.Spheres.Count; StringFunctions.MakeNameUnique <Sphere>(sphere, EditorData.Spheres); }
private static void CreateGuidInAssemblyInfo(string unpackDirectory) { List <string> stringList = FileManager.GetAllFilesInDirectory(unpackDirectory, "cs"); foreach (string s in stringList) { if (s.ToLower().Contains("assemblyinfo.cs")) { string contents = FileManager.FromFileText(s); string newGuid = Guid.NewGuid().ToString(); string newLine = "[assembly: Guid(\"" + newGuid + "\")]"; StringFunctions.ReplaceLine( ref contents, "[assembly: Guid(", newLine); FileManager.SaveText(contents, s); } } }
public static VariableListSave GetVariableListRecursive(this StateSave stateSave, string variableName) { VariableListSave variableListSave = stateSave.GetVariableListSave(variableName); if (variableListSave == null) { // Is this thing the default? ElementSave parent = stateSave.ParentContainer; if (parent != null && stateSave != parent.DefaultState) { throw new NotImplementedException(); } else if (parent != null) { ElementSave baseElement = GetBaseElementFromVariable(variableName, parent); if (baseElement != null) { string nameInBase = variableName; if (StringFunctions.ContainsNoAlloc(variableName, '.')) { // this variable is set on an instance, but we're going into the // base type, so we want to get the raw variable and not the variable // as tied to an instance. nameInBase = variableName.Substring(nameInBase.IndexOf('.') + 1); } return(baseElement.DefaultState.GetVariableListRecursive(nameInBase)); } } return(null); } else { return(variableListSave); } }
private void CurrentList_DragDrop(object sender, DragEventArgs e) { new Thread(() => { timerTime = DateTime.Now; watch = new System.Threading.Timer(Tick, null, 0, 10); Thread.CurrentThread.IsBackground = true; string[] files = (string[])e.Data.GetData(DataFormats.FileDrop); foreach (string file in files) { if (file.EndsWith("ybn") || file.EndsWith("ymap")) { if (!StringFunctions.DoesItemExist(CurrentList, file)) { CurrentList.Items.Add(file); } else if (file.EndsWith("rpf")) { TimeLabel.Text = "Scanning RPFs and Extracting Files ..."; RpfFile rpf = new RpfFile(file, Path.GetDirectoryName(file)); try { rpf.ScanStructure(null, null); var fileTypes = new List <string>() { ".ybn", ".ymap" }; RPFFunctions.SearchRPF(rpf, file, CurrentList, fileTypes); } catch (Exception) { MessageBox.Show("Error can't read " + file + ".\nThis file has been skipped.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } } } } StringFunctions.SetCount(CurrentList, FilesAddedLabel, startButton); watch.Dispose(); }).Start(); }
public int LocateByName(string name) { for (int x = 0; x < base.Count; x++) { HaloPlayer p = (HaloPlayer) base[x]; string baseName = p.Name.ToUpper(); name = name.ToUpper(); // If the strings are equal, return the value if (baseName == name) { return(x); } // Do a LIKE comparison if (StringFunctions.Like(baseName, name, true)) { return(x); } } return(-1); }
public virtual async Task <IActionResult> GetAll([FromQuery(Name = "p")] int page = 1, [FromQuery(Name = "q")] string query = null) { PaginatedEntitiesResult <TEntityDto> entitiesResult = await this.entityManager.GetAllEntitiesPaginatedAsync <TEntity, TEntityDto>(page, query); AllEntitiesViewModel model = new AllEntitiesViewModel(); model.SingleEntityName = StringFunctions.SplitWordsByCapitalLetters(typeof(TEntity).Name); model.Title = typeof(TEntity).Name.ToLower().EndsWith("s") ? $"{model.SingleEntityName}es" : $"{model.SingleEntityName}s"; ViewData[BreadcrumbPageTitlePlaceholder] = model.Title; List <TableRowActionViewModel> actions = new List <TableRowActionViewModel>(); TableViewActionsInit(ref actions); model.Table = TableMapper.DtoMapper <TEntityDto>(entitiesResult, actions.ToArray()); model.Table.SetPaginationRedirection("Admin", this.GetType().Name.Replace("Controller", string.Empty), nameof(GetAll)); ViewData.Add("searchQuery", query); InitNavigationActionsIntoListPage(ref model); return(View("AbstractViews/GetAll", model)); }
public void AddAxisAlignedRectangle() { AxisAlignedRectangle rectangle = new AxisAlignedRectangle(); ShapeManager.AddAxisAlignedRectangle(rectangle); rectangle.Color = EditorProperties.AxisAlignedRectangleColor; rectangle.X = SpriteManager.Camera.X; rectangle.Y = SpriteManager.Camera.Y; float scale = (float)Math.Abs( 18 / SpriteManager.Camera.PixelsPerUnitAt(0)); rectangle.ScaleX = scale; rectangle.ScaleY = scale; EditorData.ShapeCollection.AxisAlignedRectangles.Add(rectangle); rectangle.Name = "AxisAlignedRectangle" + EditorData.AxisAlignedRectangles.Count; StringFunctions.MakeNameUnique <AxisAlignedRectangle>(rectangle, EditorData.AxisAlignedRectangles); }
public static void SetLocalFreeMoney() { string miscFolder = Path.Combine(Application.StartupPath, Config.MiscFolderName); if (!Directory.Exists(miscFolder)) { Directory.CreateDirectory(miscFolder); } string file = Path.Combine (miscFolder, Config.FreeMoneyFileName); if (File.Exists(file)) { using (StreamReader reader = new StreamReader(file, Encoding.UTF8)) { string line = reader.ReadLine(); decimal val = StringFunctions.ParseDecimal(line); FreeMoney = val; } } FreeMoneyWithShort = FreeMoney - LittleTable.GetShortSum(); }
private static AnimationChainSave Duplicate(AnimationChainSave whatToCopy, string requestedName = null) { AnimationChainSave newAcs = FileManager.CloneObject(whatToCopy); if (requestedName != null) { newAcs.Name = requestedName; } List <string> existingNames = ProjectManager.Self.AnimationChainListSave.AnimationChains.Select(item => item.Name).ToList(); newAcs.Name = StringFunctions.MakeStringUnique(newAcs.Name, existingNames, 2); ProjectManager.Self.AnimationChainListSave.AnimationChains.Add(newAcs); TreeViewManager.Self.RefreshTreeNode(newAcs); MainControl.Self.RaiseAnimationChainChanges(null, null); SelectedState.Self.SelectedChain = newAcs; return(newAcs); }
internal void FileTransferProgress(FileTransferProgressEventArgs e) { if (e.State == FileTransferState.Finished || e.State == FileTransferState.Error) { Finish(); return; } if (e.Total == 0) { return; } ViewModel.ProgressIsIndeterminate = false; ViewModel.ProgressPercentIndicatorVisibility = Visibility.Visible; ViewModel.ReceiveStatus = "Receiving..."; ViewModel.ProgressValue = (int)e.CurrentPart; ViewModel.ProgressMaximum = (int)e.Total; ViewModel.ProgressCaption = StringFunctions.GetSizeString(e.TotalBytesTransferred); }
public static TLine operator +=(char c) { string oldValue = value; int len = oldValue ? oldValue.Length : 0; value = new string(new char[len + 2 - 1]); if (oldValue) { value = oldValue; } value = StringFunctions.ChangeCharacter(value, len, c); value = StringFunctions.ChangeCharacter(value, len + 1, '\0'); if (oldValue) { oldValue = null; } return(this); }
/// <summary> /// Initializes a new instance of the LkDataCRUD class. /// </summary> /// <param name="crudOperationResult">The string result of the CRUD operation execution.</param> public LkDataCRUD(string crudOperationResult) : base(crudOperationResult) { this.TotalItems = StringFunctions.ExtractTotalRecords(crudOperationResult); string[] lstIdDicts = StringFunctions.ExtractRecordsIdDicts(crudOperationResult); string[] lstDictionaries = StringFunctions.ExtractRecordsDicts(crudOperationResult); string[] lstCalculatedDicts = StringFunctions.ExtractRecordsCalculatedDicts(crudOperationResult); this.LkRecords = new LkItems(lstIdDicts, lstDictionaries, lstCalculatedDicts); string[] lstRecords = StringFunctions.ExtractRecords(crudOperationResult); string[] lstRecordIds = StringFunctions.ExtractRecordIds(crudOperationResult); string[] lstOriginalRecords = StringFunctions.ExtractOriginalRecords(crudOperationResult); string[] lstRecordsCalculated = StringFunctions.ExtractRecordsCalculated(crudOperationResult); for (int i = 0; i < lstRecordIds.Length; i++) { string record = (lstRecords.Length == lstRecordIds.Length ? lstRecords[i] : ""); string originalRecord = (lstOriginalRecords.Length == lstRecordIds.Length ? lstOriginalRecords[i] : ""); string calculateds = (lstRecordsCalculated.Length == lstRecordIds.Length ? lstRecordsCalculated[i] : ""); LkItem lkRecord = new LkItem(lstRecordIds[i], record, calculateds, originalRecord); this.LkRecords.Add(lkRecord); } }
void _read(FileStream stream, long filePosition) { try { _fileName = stream.Name; // Resource._fileName: even though _process gets it, _isPnl needs it first if (!_isPnl) { _process(stream, filePosition); } else { BinaryReader br = new BinaryReader(stream); _offset = filePosition; // Resource._offset _type = ResourceType.Panl; // *.PNL files do not contain headers, just the raw data _name = StringFunctions.GetFileName(_fileName); DecodeResource(br.ReadBytes((int)stream.Length), false); } } catch (Exception x) { throw new LoadFileException(x); } _imageIndexer = new ImageIndexer(this); }
/// <summary> /// Saves a string of text to a file as an image, the format is determined by the file extension. /// Supported extensions are *.jpg,*.jpeg,*.gif,*.bmp,*.png,*.tiff /// </summary> public static void Save(string FileName, string Text, Font TextFont, Color TextColor, Color BackgroundColor, TextRenderingHint RenderingHint) { ImageFormat objFormat; switch (StringFunctions.AllAfter(FileName, ".").ToLower()) { case "jpg": case "jpeg": objFormat = ImageFormat.Jpeg; break; case "gif": objFormat = ImageFormat.Gif; break; case "bmp": objFormat = ImageFormat.Bmp; break; case "png": objFormat = ImageFormat.Png; break; case "tiff": objFormat = ImageFormat.Tiff; break; default: objFormat = ImageFormat.Jpeg; break; } Bitmap bmp = GetBitmap(Text, TextFont, TextColor, BackgroundColor, RenderingHint); FileStream fs = new FileStream(FileName, FileMode.Create); bmp.Save(fs, objFormat); bmp.Dispose(); fs.Close(); }
public static void TryApplyAutoName(IElement element, NamedObjectSave namedObject) { var isAutoNameEnabled = namedObject.Properties.GetValue <bool>(nameof(CollisionRelationshipViewModel.IsAutoNameEnabled)); if (isAutoNameEnabled) { var desiredName = GetAutoName(namedObject); bool nameExists = false; do { nameExists = element.AllNamedObjects .Any(item => item != namedObject && item.InstanceName == desiredName); if (nameExists) { if (StringFunctions.HasNumberAtEnd(desiredName)) { desiredName = StringFunctions.IncrementNumberAtEnd(desiredName); } else { desiredName = desiredName + "2"; } } } while (nameExists); if (desiredName != namedObject.InstanceName) { namedObject.InstanceName = desiredName; GlueCommands.Self.RefreshCommands.RefreshUi(element); GlueCommands.Self.GluxCommands.SaveGluxTask(); GlueCommands.Self.GenerateCodeCommands.GenerateElementCode(element); } } }
public void LogException(Log objLog, Exception objEx) { string sPad = string.Empty; try { sPad = sPad.PadLeft("yyyy.MM.dd HH:mm:ss.FFFFFFF".Length + 1, ' '); objLog.LogLevel = LogLevel.Errors; objLog.LogType = EventLogEntryType.Error; StringBuilder objStringBuilder = new StringBuilder(); objStringBuilder.Append("Exception " + StringFunctions.RemoveNonLoggableChars(objEx.ToString())); objStringBuilder.Append(" : Exception StackTrace = "); objStringBuilder.Append(StringFunctions.RemoveNonLoggableChars(objEx.StackTrace)); if (objEx.InnerException != null) { objStringBuilder.AppendLine(""); objStringBuilder.Append("Exception InnerException = "); objStringBuilder.Append(objEx.InnerException.ToString()); } objLog.AdditionalInfo = objStringBuilder.ToString(); Queue <Log> obj; Monitor.Enter(obj = this.mQueueLogs); try { this.mQueueLogs.Enqueue(objLog); } finally { Monitor.Exit(obj); } } catch { } finally { } }
private static void DuplicateStateClick() { // Is there a "custom" current state save, like an interpolation or animation? if (SelectedState.Self.CustomCurrentStateSave != null) { GumCommands.Self.GuiCommands.ShowMessage("Cannot duplicate state while a custom state is displaying. Are you creating or playing animations?"); return; } ////////End Early Out/////////////// StateSave newState = SelectedState.Self.SelectedStateSave.Clone(); newState.ParentContainer = SelectedState.Self.SelectedElement; if (SelectedState.Self.SelectedStateCategorySave == null) { int index = SelectedState.Self.SelectedElement.States.IndexOf(SelectedState.Self.SelectedStateSave); SelectedState.Self.SelectedElement.States.Insert(index + 1, newState); } else { int index = SelectedState.Self.SelectedStateCategorySave.States.IndexOf(SelectedState.Self.SelectedStateSave); SelectedState.Self.SelectedStateCategorySave.States.Insert(index + 1, newState); } while (SelectedState.Self.SelectedStateContainer.AllStates.Any(item => item != newState && item.Name == newState.Name)) { newState.Name = StringFunctions.IncrementNumberAtEnd(newState.Name); } StateTreeViewManager.Self.RefreshUI(SelectedState.Self.SelectedElement); SelectedState.Self.SelectedStateSave = newState; GumCommands.Self.FileCommands.TryAutoSaveCurrentElement(); }
//Calcuation Controller Action public void CalculateAction(List<CategoryViewModel> jCategory) { foreach (var group in jCategory) { foreach (var item in group.Functions) { if (item.Function == "Input") { item.Output = InputFunctions.Output(item.Type, item.Output); OutputList.Add(new OutputList { ID = Convert.ToString(item.ID), Field = item.Name, Value = item.Output, Group = group.Name }); } else { //Logic check at Column Level string colLogic = null; bool colLogicParse = true; if(group.Logic != null) { foreach (var bit in group.Logic) { var grouplastLogic = group.Logic.Last(); string grouplastLogicOperator = grouplastLogic.Operator; Logic Logic = new Logic(); colLogic = Logic.Output(jCategory, bit, group.ID, 0); Expression ex = new Expression(colLogic); try { colLogicParse = Convert.ToBoolean(ex.Evaluate()); } catch (Exception exception) { logger.Error(exception); throw new HttpException(exception.ToString()); } if (grouplastLogicOperator == "AND" && colLogicParse == false) { break; } else if (grouplastLogicOperator == "OR" && colLogicParse == true) { colLogicParse = true; break; } } } if (item.Parameter.Count > 0) { string logic = null; bool logicparse = true; string MathString = null; bool PowOpen = false; //Logic check at column level if (colLogicParse == true) { foreach (var bit in item.Logic) { var lastLogic = item.Logic.Last(); string lastLogicOperator = lastLogic.Operator; Logic Logic = new Logic(); logic = Logic.Output(jCategory, bit, group.ID, item.ID); Expression ex = new Expression(logic); try { logicparse = Convert.ToBoolean(ex.Evaluate()); } catch (Exception exception) { logger.Error(exception); throw new HttpException(exception.ToString()); } if (lastLogicOperator == "AND" && logicparse == false) { break; } else if (lastLogicOperator == "OR" && logicparse == true) { logicparse = true; break; } } } else { logicparse = false; } //Run code if logic if met at column and row level if (logicparse == true) { int paramCount = 1; foreach (var param in item.Parameter) { string jparameters = Newtonsoft.Json.JsonConvert.SerializeObject(param); logger.Debug("Column Name(" + group.ID + ") - " + group.Name + " || Row Name(" + item.ID +") - " + item.Name); if (item.Function == "Maths") { Maths Maths = new Maths(); Maths parameters = (Maths)javaScriptSerializer.Deserialize(jparameters, typeof(Maths)); MathString = Maths.Output(jparameters,jCategory,group.ID,item.ID,MathString,PowOpen); PowOpen = Maths.PowOpen(jparameters, PowOpen); if (paramCount == item.Parameter.Count) { Expression e = new Expression(MathString); var Calculation = e.Evaluate(); bool DeciParse; decimal CalculationDeci; string Rounding; DeciParse = decimal.TryParse(Convert.ToString(Calculation), out CalculationDeci); Rounding = Convert.ToString(parameters.Rounding); if (Rounding == null || Rounding == "") { Rounding = "2"; } if (DeciParse == true) { decimal Output = CalculationDeci; MathematicalFunctions MathematicalFunctions = new MathematicalFunctions(); try { Output = MathematicalFunctions.Rounding(Convert.ToString(parameters.RoundingType), Rounding, Output); } catch (Exception ex) { logger.Error(ex); throw new HttpException(ex.ToString()); } item.Output = Convert.ToString(Output); } else { item.Output = "0"; } } paramCount = paramCount + 1; } else if (item.Function == "ErrorsWarnings") { ErrorsWarnings Errors = new ErrorsWarnings(); ErrorsWarnings parameters = (ErrorsWarnings)javaScriptSerializer.Deserialize(jparameters, typeof(ErrorsWarnings)); item.Name = parameters.Type; item.Output = parameters.String1; } else if (item.Function == "Comments") { Comments Errors = new Comments(); Comments parameters = (Comments)javaScriptSerializer.Deserialize(jparameters, typeof(Comments)); item.Output = parameters.String1; } else if (item.Function == "Period") { DateFunctions DateFunctions = new DateFunctions(); Period Periods = new Period(); try { item.Output = Periods.Output(jparameters, jCategory, group.ID, item.ID); } catch (Exception ex) { logger.Error(ex); throw new HttpException(ex.ToString()); } } else if (item.Function == "Factors") { Factors Factors = new Factors(); Factors parameters = (Factors)javaScriptSerializer.Deserialize(jparameters, typeof(Factors)); try { item.Output = Factors.Output(jparameters, jCategory, group.ID, item.ID); } catch (Exception ex) { logger.Error(ex); throw new HttpException(ex.ToString()); } item.Type = parameters.OutputType; } else if (item.Function == "DateAdjustment") { Dates Dates = new Dates(); try { item.Output = Dates.Output(jparameters, jCategory, group.ID, item.ID); } catch (Exception ex) { logger.Error(ex); throw new HttpException(ex.ToString()); } } else if (item.Function == "DatePart") { DatePart DateParts = new DatePart(); try { item.Output = DateParts.Output(jparameters, jCategory, group.ID, item.ID); } catch (Exception ex) { logger.Error(ex); throw new HttpException(ex.ToString()); } } else if (item.Function == "MathsFunctions") { MathsFunctions MathsFunctions = new MathsFunctions(); try { item.Output = MathsFunctions.Output(jparameters, jCategory, group.ID, item.ID); } catch (Exception ex) { logger.Error(ex); throw new HttpException(ex.ToString()); } } else if (item.Function == "ArrayFunctions") { ArrayFunctions ArrayFunctions = new ArrayFunctions(); ArrayFunctions parameters = (ArrayFunctions)javaScriptSerializer.Deserialize(jparameters, typeof(ArrayFunctions)); try { item.Output = ArrayFunctions.Output(jparameters, jCategory, group.ID, item.ID); } catch (Exception ex) { logger.Error(ex); throw new HttpException(ex.ToString()); } if(parameters.Function == "Count") { item.Type = "Decimal"; } else { item.Type = parameters.LookupType; } } else if (item.Function == "StringFunctions") { StringFunctions StringFunctions = new StringFunctions(); StringFunctions parameters = (StringFunctions)javaScriptSerializer.Deserialize(jparameters, typeof(StringFunctions)); try { item.Output = StringFunctions.Output(jparameters, jCategory, group.ID, item.ID); } catch (Exception ex) { logger.Error(ex); throw new HttpException(ex.ToString()); } if(parameters.Type == "Len") { item.Type = "Decimal"; } else { item.Type = "String"; } } } //Expected results on the builder this sets the required ones if (item.ExpectedResult == null || item.ExpectedResult == "") { item.Pass = "******"; } else if (item.ExpectedResult == item.Output) { item.Pass = "******"; } else { item.Pass = "******"; } OutputList.Add(new OutputList { ID = Convert.ToString(item.ID), Field = item.Name, Value = item.Output, Group = group.Name }); } else { //Ignores the row if logic is not met dynamic LogicReplace = Config.VariableReplace(jCategory, item.Name, group.ID, item.ID); if(Convert.ToString(LogicReplace) == Convert.ToString(item.Name)) { item.Output = null; } else { item.Output = Convert.ToString(LogicReplace); } item.Pass = "******"; OutputList.Add(new OutputList { ID = Convert.ToString(item.ID), Field = item.Name, Value = item.Output, Group = group.Name }); } } } } } }