System.Collections.Generic.List.AddRange(System.Collections.Generic.IEnumerable)

Here are the examples of the csharp api System.Collections.Generic.List.AddRange(System.Collections.Generic.IEnumerable) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

19673 Examples 7

19 Source : WorkbookEditor.cs
with Apache License 2.0
from aaaddress1

public WorkbookStream SetMacroSheetContent_NoLoader(List<string> macroStrings, int rwStart = 0, int colStart = 0)
        {
            WorkbookStream macroStream = GetMacroStream();
            Formula replaceMeFormula = macroStream.GetAllRecordsByType<Formula>().First();

            //ixfe default cell value is 15
            List<BiffRecord> formulasToAdd = new List<BiffRecord>();
            int curRow = rwStart, curCol = colStart;
            int dstCurRow = 0, dstCurCol = 0;

            foreach (string str in macroStrings) {
                var formulas = FormulaHelper.ConvertStringToFormulas(str, curRow, curCol, dstCurRow, dstCurCol, 15, SheetPackingMethod.ObfuscatedCharFuncAlt);
                curRow += formulas.Count;
                dstCurRow += 1;
                formulasToAdd.AddRange(formulas);
            }
            
            int lastGotoCol = formulasToAdd.Last().AsRecordType<Formula>().col;
            int lastGotoRow = formulasToAdd.Last().AsRecordType<Formula>().rw + 1;

            WorkbookStream modifiedStream = WbStream;
            modifiedStream = modifiedStream.InsertRecords(formulasToAdd, replaceMeFormula);
            // we replacedert decrypted macros should at R1C1, so place a GOTO(R1C1) here.
            modifiedStream = modifiedStream.ReplaceRecord(replaceMeFormula, FormulaHelper.GetGotoFormulaForCell(lastGotoRow, lastGotoCol, 0, 0));
            WbStream = modifiedStream;
            return WbStream;
        }

19 Source : FormulaHelper.cs
with Apache License 2.0
from aaaddress1

public static List<BiffRecord> ConvertStringsToRecords_NoLoader(List<string> strings, int rwStart, int colStart, int dstRwStart, int dstColStart,
           int ixfe = 15, SheetPackingMethod packingMethod = SheetPackingMethod.ObfuscatedCharFunc)
        {
            List<BiffRecord> formulaList = new List<BiffRecord>();

            int curRow = rwStart;
            int curCol = colStart;

            int dstCurRow = dstRwStart;
            int dstCurCol = dstColStart;

            //TODO [Anti-replacedysis] Break generated formula apart with different RUN()/GOTO() actions 
            foreach (string str in strings)
            {
                string[] rowStrings = str.Split(MacroPatterns.MacroColumnSeparator);
                List<BiffRecord> stringFormulas = new List<BiffRecord>();
                for (int colOffset = 0; colOffset < rowStrings.Length; colOffset += 1)
                {
                    //Skip empty strings
                    if (rowStrings[colOffset].Trim().Length == 0)
                        continue;
   

                    var formulas = ConvertStringToFormulas(rowStrings[colOffset], curRow, curCol, dstCurRow, dstCurCol + colOffset, ixfe, packingMethod);

                    stringFormulas.AddRange(formulas);
                    curRow += formulas.Count;
                }

                dstCurRow += 1;
                formulaList.AddRange(stringFormulas);
            }

            return formulaList;
        }

19 Source : WorkbookEditor.cs
with Apache License 2.0
from aaaddress1

public WorkbookStream SetMacroSheetContent_NoLoader(List<string> macroStrings, int rwStart = 0, int colStart = 0)
        {
            WorkbookStream macroStream = GetMacroStream();
            Formula replaceMeFormula = macroStream.GetAllRecordsByType<Formula>().First();

            //ixfe default cell value is 15
            List<BiffRecord> formulasToAdd = new List<BiffRecord>();
            int curRow = rwStart, curCol = colStart;
            int dstCurRow = 0, dstCurCol = 0;

            foreach (string str in macroStrings) {
                List<Formula> charFormulas = FormulaHelper.GetCharFormulasForString(str, curRow, curCol, SheetPackingMethod.ObfuscatedCharFuncAlt);
                curRow += charFormulas.Count;
                var createdCells = charFormulas.Select(formula => new Cell(formula.rw, formula.col, 15)).ToList();
                var formulaInvocationRecords = FormulaHelper.BuildFORMULAFunctionCall(createdCells, curRow, curCol, dstCurRow, dstCurCol, SheetPackingMethod.ObfuscatedCharFuncAlt, false);
                curRow += formulaInvocationRecords.Count;
                dstCurRow++;
                formulasToAdd.AddRange(charFormulas);
                formulasToAdd.AddRange(formulaInvocationRecords);
            }

            int lastGotoCol = formulasToAdd.Last().AsRecordType<Formula>().col;
            int lastGotoRow = formulasToAdd.Last().AsRecordType<Formula>().rw + 1;

            WorkbookStream modifiedStream = WbStream;
            modifiedStream = modifiedStream.InsertRecords(formulasToAdd, replaceMeFormula);
            // we replacedert decrypted macros should at R1C1, so place a GOTO(R1C1) here.
            modifiedStream = modifiedStream.ReplaceRecord(replaceMeFormula, FormulaHelper.GetGotoFormulaForCell(lastGotoRow, lastGotoCol, 0, 0));
            WbStream = modifiedStream;
            return WbStream;
        }

19 Source : Database.cs
with Apache License 2.0
from aadreja

internal virtual void CreateAddCommand(IDbCommand cmd, object enreplacedy, IAuditTrail audit = null, string columnNames = null, bool doNotAppendCommonFields = false, bool overrideCreatedUpdatedOn = false)
        {
            TableAttribute tableInfo = EnreplacedyCache.Get(enreplacedy.GetType());

            if (tableInfo.NeedsHistory && tableInfo.IsCreatedByEmpty(enreplacedy))
                throw new MissingFieldException("CreatedBy is required when Audit Trail is enabled");

            List<string> columns = new List<string>();

            if (!string.IsNullOrEmpty(columnNames)) columns.AddRange(columnNames.Split(','));
            else columns.AddRange(tableInfo.DefaultInsertColumns);//Get columns from Enreplacedy attributes loaded in TableInfo

            bool isPrimaryKeyEmpty = false;

            foreach(ColumnAttribute pkCol in tableInfo.Columns.Where(p=>p.Value.IsPrimaryKey).Select(p=>p.Value))
            {
                if (pkCol.PrimaryKeyInfo.IsIdenreplacedy && tableInfo.IsKeyIdEmpty(enreplacedy, pkCol))
                {
                    isPrimaryKeyEmpty = true;
                    //if idenreplacedy remove keyfield if added in field list
                    columns.Remove(pkCol.Name);
                }
                else if (pkCol.Property.PropertyType == typeof(Guid) && tableInfo.IsKeyIdEmpty(enreplacedy, pkCol))
                {
                    isPrimaryKeyEmpty = true;
                    //if not idenreplacedy and key not generated, generate before save
                    tableInfo.SetKeyId(enreplacedy, pkCol, Guid.NewGuid());
                }
            }

            #region append common columns

            if (!doNotAppendCommonFields)
            {
                if (!tableInfo.NoIsActive)
                {
                    if (!columns.Contains(Config.ISACTIVE_COLUMN.Name))
                        columns.Add(Config.ISACTIVE_COLUMN.Name);

                    bool isActive = tableInfo.GetIsActive(enreplacedy) ?? true;
                    //when IsActive is not set then true for insert
                    cmd.AddInParameter("@" + Config.ISACTIVE_COLUMN.Name, Config.ISACTIVE_COLUMN.ColumnDbType, isActive);

                    if (tableInfo.NeedsHistory)
                        audit.AppendDetail(Config.ISACTIVE_COLUMN.Name, isActive, DbType.Boolean, null);

                    tableInfo.SetIsActive(enreplacedy, isActive); //Set IsActive value
                }

                if (!tableInfo.NoVersionNo)
                {
                    int versionNo = tableInfo.GetVersionNo(enreplacedy) ?? 1;  //set defualt versionno 1 for Insert
                    if (versionNo == 0) versionNo = 1; //set defualt versionno 1 for Insert even if its zero or null

                    if (!columns.Contains(Config.VERSIONNO_COLUMN.Name))
                        columns.Add(Config.VERSIONNO_COLUMN.Name);

                    cmd.AddInParameter("@" + Config.VERSIONNO_COLUMN.Name, Config.VERSIONNO_COLUMN.ColumnDbType, versionNo);

                    tableInfo.SetVersionNo(enreplacedy, versionNo); //Set VersionNo value
                }

                if (!tableInfo.NoCreatedBy)
                {
                    if (!columns.Contains(Config.CREATEDBY_COLUMN.Name))
                        columns.Add(Config.CREATEDBY_COLUMN.Name);

                    cmd.AddInParameter("@" + Config.CREATEDBY_COLUMN.Name, Config.CREATEDBY_COLUMN.ColumnDbType, tableInfo.GetCreatedBy(enreplacedy));
                }

                if (!tableInfo.NoCreatedOn & !columns.Contains(Config.CREATEDON_COLUMN.Name))
                {
                    columns.Add(Config.CREATEDON_COLUMN.Name);
                }

                if (!tableInfo.NoUpdatedBy)
                {
                    if (!columns.Contains(Config.UPDATEDBY_COLUMN.Name))
                        columns.Add(Config.UPDATEDBY_COLUMN.Name);

                    cmd.AddInParameter("@" + Config.UPDATEDBY_COLUMN.Name, Config.UPDATEDBY_COLUMN.ColumnDbType, tableInfo.GetCreatedBy(enreplacedy));
                }

                if (!tableInfo.NoUpdatedOn & !columns.Contains(Config.UPDATEDON_COLUMN.Name))
                {
                    columns.Add(Config.UPDATEDON_COLUMN.Name);
                }
            }

            #endregion

            //append @ before each fields to add as parameter
            List<string> parameters = columns.Select(c => "@" + c).ToList();

            int pIndex = parameters.FindIndex(c => c == "@" + Config.CREATEDON_COLUMN.Name);
            if (pIndex >= 0)
            {
                var createdOn = Helper.GetDateTimeOrDatabaseDateTimeSQL(tableInfo.GetCreatedOn(enreplacedy), this, overrideCreatedUpdatedOn);
                if (createdOn is string)
                {
                    parameters[pIndex] = (string)createdOn;
                }
                else
                {
                    cmd.AddInParameter(parameters[pIndex], Config.CREATEDON_COLUMN.ColumnDbType, createdOn);
                }
                //parameters[pIndex] = (string)Helper.GetDateTimeOrDatabaseDateTimeSQL(tableInfo.GetCreatedOn(enreplacedy), this, overrideCreatedUpdatedOn);
            }

            pIndex = parameters.FindIndex(c => c == "@" + Config.UPDATEDON_COLUMN.Name);
            if (pIndex >= 0)
            {
                var updatedOn = Helper.GetDateTimeOrDatabaseDateTimeSQL(tableInfo.GetUpdatedOn(enreplacedy), this, overrideCreatedUpdatedOn);
                if (updatedOn is string)
                {
                    parameters[pIndex] = (string)updatedOn;
                }
                else
                {
                    cmd.AddInParameter(parameters[pIndex], Config.CREATEDON_COLUMN.ColumnDbType, updatedOn);
                }
                //parameters[pIndex] = (string)Helper.GetDateTimeOrDatabaseDateTimeSQL(tableInfo.GetUpdatedOn(enreplacedy), this, overrideCreatedUpdatedOn);
            }

            StringBuilder cmdText = new StringBuilder();
            cmdText.Append($"INSERT INTO {tableInfo.FullName} ({string.Join(",", columns)}) VALUES({string.Join(",", parameters)});");

            if (tableInfo.IsKeyIdenreplacedy() && isPrimaryKeyEmpty)
            {
                //add query to get inserted id
                cmdText.Append(LASTINSERTEDROWIDSQL);
            }

            //remove common columns and parameters already added above
            columns.RemoveAll(c => c == Config.CREATEDON_COLUMN.Name || c == Config.CREATEDBY_COLUMN.Name
                                    || c == Config.UPDATEDON_COLUMN.Name || c == Config.UPDATEDBY_COLUMN.Name
                                    || c == Config.VERSIONNO_COLUMN.Name || c == Config.ISACTIVE_COLUMN.Name);

            cmd.CommandType = CommandType.Text;
            cmd.CommandText = cmdText.ToString();

            for (int i = 0; i < columns.Count(); i++)
            {
                tableInfo.Columns.TryGetValue(columns[i], out ColumnAttribute columnInfo); //find column attribute

                DbType dbType = DbType.Object;
                object columnValue = null;

                if (columnInfo != null && columnInfo.GetMethod != null)
                {
                    dbType = columnInfo.ColumnDbType;
                    columnValue = columnInfo.GetAction(enreplacedy);

                    if (tableInfo.NeedsHistory) audit.AppendDetail(columns[i], columnValue, dbType, null);
                }
                cmd.AddInParameter("@" + columns[i], dbType, columnValue);
            }
        }

19 Source : Database.cs
with Apache License 2.0
from aadreja

internal virtual void CreateAddCommand(IDbCommand cmd, object enreplacedy, IAuditTrail audit = null, string columnNames = null, bool doNotAppendCommonFields = false, bool overrideCreatedUpdatedOn = false)
        {
            TableAttribute tableInfo = EnreplacedyCache.Get(enreplacedy.GetType());

            if (tableInfo.NeedsHistory && tableInfo.IsCreatedByEmpty(enreplacedy))
                throw new MissingFieldException("CreatedBy is required when Audit Trail is enabled");

            List<string> columns = new List<string>();

            if (!string.IsNullOrEmpty(columnNames)) columns.AddRange(columnNames.Split(','));
            else columns.AddRange(tableInfo.DefaultInsertColumns);//Get columns from Enreplacedy attributes loaded in TableInfo

            bool isPrimaryKeyEmpty = false;

            foreach(ColumnAttribute pkCol in tableInfo.Columns.Where(p=>p.Value.IsPrimaryKey).Select(p=>p.Value))
            {
                if (pkCol.PrimaryKeyInfo.IsIdenreplacedy && tableInfo.IsKeyIdEmpty(enreplacedy, pkCol))
                {
                    isPrimaryKeyEmpty = true;
                    //if idenreplacedy remove keyfield if added in field list
                    columns.Remove(pkCol.Name);
                }
                else if (pkCol.Property.PropertyType == typeof(Guid) && tableInfo.IsKeyIdEmpty(enreplacedy, pkCol))
                {
                    isPrimaryKeyEmpty = true;
                    //if not idenreplacedy and key not generated, generate before save
                    tableInfo.SetKeyId(enreplacedy, pkCol, Guid.NewGuid());
                }
            }

            #region append common columns

            if (!doNotAppendCommonFields)
            {
                if (!tableInfo.NoIsActive)
                {
                    if (!columns.Contains(Config.ISACTIVE_COLUMN.Name))
                        columns.Add(Config.ISACTIVE_COLUMN.Name);

                    bool isActive = tableInfo.GetIsActive(enreplacedy) ?? true;
                    //when IsActive is not set then true for insert
                    cmd.AddInParameter("@" + Config.ISACTIVE_COLUMN.Name, Config.ISACTIVE_COLUMN.ColumnDbType, isActive);

                    if (tableInfo.NeedsHistory)
                        audit.AppendDetail(Config.ISACTIVE_COLUMN.Name, isActive, DbType.Boolean, null);

                    tableInfo.SetIsActive(enreplacedy, isActive); //Set IsActive value
                }

                if (!tableInfo.NoVersionNo)
                {
                    int versionNo = tableInfo.GetVersionNo(enreplacedy) ?? 1;  //set defualt versionno 1 for Insert
                    if (versionNo == 0) versionNo = 1; //set defualt versionno 1 for Insert even if its zero or null

                    if (!columns.Contains(Config.VERSIONNO_COLUMN.Name))
                        columns.Add(Config.VERSIONNO_COLUMN.Name);

                    cmd.AddInParameter("@" + Config.VERSIONNO_COLUMN.Name, Config.VERSIONNO_COLUMN.ColumnDbType, versionNo);

                    tableInfo.SetVersionNo(enreplacedy, versionNo); //Set VersionNo value
                }

                if (!tableInfo.NoCreatedBy)
                {
                    if (!columns.Contains(Config.CREATEDBY_COLUMN.Name))
                        columns.Add(Config.CREATEDBY_COLUMN.Name);

                    cmd.AddInParameter("@" + Config.CREATEDBY_COLUMN.Name, Config.CREATEDBY_COLUMN.ColumnDbType, tableInfo.GetCreatedBy(enreplacedy));
                }

                if (!tableInfo.NoCreatedOn & !columns.Contains(Config.CREATEDON_COLUMN.Name))
                {
                    columns.Add(Config.CREATEDON_COLUMN.Name);
                }

                if (!tableInfo.NoUpdatedBy)
                {
                    if (!columns.Contains(Config.UPDATEDBY_COLUMN.Name))
                        columns.Add(Config.UPDATEDBY_COLUMN.Name);

                    cmd.AddInParameter("@" + Config.UPDATEDBY_COLUMN.Name, Config.UPDATEDBY_COLUMN.ColumnDbType, tableInfo.GetCreatedBy(enreplacedy));
                }

                if (!tableInfo.NoUpdatedOn & !columns.Contains(Config.UPDATEDON_COLUMN.Name))
                {
                    columns.Add(Config.UPDATEDON_COLUMN.Name);
                }
            }

            #endregion

            //append @ before each fields to add as parameter
            List<string> parameters = columns.Select(c => "@" + c).ToList();

            int pIndex = parameters.FindIndex(c => c == "@" + Config.CREATEDON_COLUMN.Name);
            if (pIndex >= 0)
            {
                var createdOn = Helper.GetDateTimeOrDatabaseDateTimeSQL(tableInfo.GetCreatedOn(enreplacedy), this, overrideCreatedUpdatedOn);
                if (createdOn is string)
                {
                    parameters[pIndex] = (string)createdOn;
                }
                else
                {
                    cmd.AddInParameter(parameters[pIndex], Config.CREATEDON_COLUMN.ColumnDbType, createdOn);
                }
                //parameters[pIndex] = (string)Helper.GetDateTimeOrDatabaseDateTimeSQL(tableInfo.GetCreatedOn(enreplacedy), this, overrideCreatedUpdatedOn);
            }

            pIndex = parameters.FindIndex(c => c == "@" + Config.UPDATEDON_COLUMN.Name);
            if (pIndex >= 0)
            {
                var updatedOn = Helper.GetDateTimeOrDatabaseDateTimeSQL(tableInfo.GetUpdatedOn(enreplacedy), this, overrideCreatedUpdatedOn);
                if (updatedOn is string)
                {
                    parameters[pIndex] = (string)updatedOn;
                }
                else
                {
                    cmd.AddInParameter(parameters[pIndex], Config.CREATEDON_COLUMN.ColumnDbType, updatedOn);
                }
                //parameters[pIndex] = (string)Helper.GetDateTimeOrDatabaseDateTimeSQL(tableInfo.GetUpdatedOn(enreplacedy), this, overrideCreatedUpdatedOn);
            }

            StringBuilder cmdText = new StringBuilder();
            cmdText.Append($"INSERT INTO {tableInfo.FullName} ({string.Join(",", columns)}) VALUES({string.Join(",", parameters)});");

            if (tableInfo.IsKeyIdenreplacedy() && isPrimaryKeyEmpty)
            {
                //add query to get inserted id
                cmdText.Append(LASTINSERTEDROWIDSQL);
            }

            //remove common columns and parameters already added above
            columns.RemoveAll(c => c == Config.CREATEDON_COLUMN.Name || c == Config.CREATEDBY_COLUMN.Name
                                    || c == Config.UPDATEDON_COLUMN.Name || c == Config.UPDATEDBY_COLUMN.Name
                                    || c == Config.VERSIONNO_COLUMN.Name || c == Config.ISACTIVE_COLUMN.Name);

            cmd.CommandType = CommandType.Text;
            cmd.CommandText = cmdText.ToString();

            for (int i = 0; i < columns.Count(); i++)
            {
                tableInfo.Columns.TryGetValue(columns[i], out ColumnAttribute columnInfo); //find column attribute

                DbType dbType = DbType.Object;
                object columnValue = null;

                if (columnInfo != null && columnInfo.GetMethod != null)
                {
                    dbType = columnInfo.ColumnDbType;
                    columnValue = columnInfo.GetAction(enreplacedy);

                    if (tableInfo.NeedsHistory) audit.AppendDetail(columns[i], columnValue, dbType, null);
                }
                cmd.AddInParameter("@" + columns[i], dbType, columnValue);
            }
        }

19 Source : FormulaHelper.cs
with Apache License 2.0
from aaaddress1

public static List<BiffRecord> ConvertStringToFormulas(string str, int rwStart, int colStart, int dstRw, int dstCol, int ixfe = 15, SheetPackingMethod packingMethod = SheetPackingMethod.ObfuscatedCharFunc)
        {
            List<BiffRecord> formulaList = new List<BiffRecord>();
            List<Cell> createdCells = new List<Cell>();

            int curRow = rwStart;
            int curCol = colStart;

            bool instaEval = false;
            if (str.StartsWith(MacroPatterns.InstaEvalMacroPrefix))
            {
                if (packingMethod != SheetPackingMethod.ArgumentSubroutines)
                {
                    throw new NotImplementedException("Must use ArgumentSubroutines Sheet Packing for InstaEval");
                }
                instaEval = true;
                str = str.Replace(MacroPatterns.InstaEvalMacroPrefix, "");
            }

            
            List<Formula> charFormulas = GetCharFormulasForString(str, curRow, curCol, packingMethod);
            formulaList.AddRange(charFormulas);
            curRow += charFormulas.Count;
            createdCells = charFormulas.Select(formula => new Cell(formula.rw, formula.col, ixfe)).ToList();
            
            List<BiffRecord> formulaInvocationRecords =
                BuildFORMULAFunctionCall(createdCells, curRow, curCol, dstRw, dstCol, packingMethod, instaEval);

            formulaList.AddRange(formulaInvocationRecords);

            return formulaList;
        }

19 Source : Database.cs
with Apache License 2.0
from aadreja

internal virtual bool CreateUpdateCommand(IDbCommand cmd, object enreplacedy, object oldEnreplacedy, IAuditTrail audit = null, string columnNames = null, bool doNotAppendCommonFields = false, bool overrideCreatedUpdatedOn = false)
        {
            bool isUpdateNeeded = false;

            TableAttribute tableInfo = EnreplacedyCache.Get(enreplacedy.GetType());

            if (!tableInfo.NoUpdatedBy && tableInfo.IsUpdatedByEmpty(enreplacedy))
                throw new MissingFieldException("Updated By is required");

            List<string> columns = new List<string>();

            if (!string.IsNullOrEmpty(columnNames)) columns.AddRange(columnNames.Split(','));
            else columns.AddRange(tableInfo.DefaultUpdateColumns);//Get columns from Enreplacedy attributes loaded in TableInfo

            StringBuilder cmdText = new StringBuilder();
            cmdText.Append($"UPDATE {tableInfo.FullName} SET ");

            //add default columns if doesn't exists
            if (!doNotAppendCommonFields)
            {
                if (!tableInfo.NoVersionNo && !columns.Contains(Config.VERSIONNO_COLUMN.Name))
                    columns.Add(Config.VERSIONNO_COLUMN.Name);

                if (!tableInfo.NoUpdatedBy && !columns.Contains(Config.UPDATEDBY_COLUMN.Name))
                    columns.Add(Config.UPDATEDBY_COLUMN.Name);

                if (!tableInfo.NoUpdatedOn && !columns.Contains(Config.UPDATEDON_COLUMN.Name))
                    columns.Add(Config.UPDATEDON_COLUMN.Name);
            }

            //remove primarykey, createdon and createdby columns if exists
            columns.RemoveAll(c => tableInfo.PkColumnList.Select(p=>p.Name).Contains(c));
            columns.RemoveAll(c => c == Config.CREATEDON_COLUMN.Name || 
                                    c == Config.CREATEDBY_COLUMN.Name);

            for (int i = 0; i < columns.Count(); i++)
            {
                if (columns[i].Equals(Config.VERSIONNO_COLUMN.Name, StringComparison.OrdinalIgnoreCase))
                {
                    cmdText.Append($"{columns[i]} = {columns[i]}+1");
                    cmdText.Append(",");
                }
                else if (columns[i].Equals(Config.UPDATEDBY_COLUMN.Name, StringComparison.OrdinalIgnoreCase))
                {
                    cmdText.Append($"{columns[i]} = @{columns[i]}");
                    cmdText.Append(",");
                    cmd.AddInParameter("@" + columns[i], Config.UPDATEDBY_COLUMN.ColumnDbType, tableInfo.GetUpdatedBy(enreplacedy));
                }
                else if (columns[i].Equals(Config.UPDATEDON_COLUMN.Name, StringComparison.OrdinalIgnoreCase))
                {
                    var updatedOn = Helper.GetDateTimeOrDatabaseDateTimeSQL(tableInfo.GetUpdatedOn(enreplacedy), this, overrideCreatedUpdatedOn);
                    if (updatedOn is string)
                    {
                        cmdText.Append($"{columns[i]} = {CURRENTDATETIMESQL}");
                    }
                    else
                    {
                        cmdText.Append($"{columns[i]} = @{columns[i]}");
                        cmd.AddInParameter("@" + columns[i], Config.UPDATEDON_COLUMN.ColumnDbType, updatedOn);
                    }
                    cmdText.Append(",");
                }
                else
                {
                    bool includeInUpdate = true;
                    tableInfo.Columns.TryGetValue(columns[i], out ColumnAttribute columnInfo); //find column attribute

                    DbType dbType = DbType.Object;
                    object columnValue = null;

                    if (columnInfo != null && columnInfo.GetMethod != null)
                    {
                        dbType = columnInfo.ColumnDbType;
                        columnValue = columnInfo.GetAction(enreplacedy);

                        includeInUpdate = oldEnreplacedy == null; //include in update when oldEnreplacedy not available

                        //compare with old object to check whether update is needed or not
                        object oldColumnValue = null;
                        if (oldEnreplacedy != null)
                        {
                            oldColumnValue = columnInfo.GetAction(oldEnreplacedy);

                            if (oldColumnValue != null && columnValue != null)
                            {
                                if (!oldColumnValue.Equals(columnValue)) //add to history only if property is modified
                                {
                                    includeInUpdate = true;
                                }
                            }
                            else if (oldColumnValue == null && columnValue != null)
                            {
                                includeInUpdate = true;
                            }
                            else if (oldColumnValue != null)
                            {
                                includeInUpdate = true;
                            }
                        }

                        if (tableInfo.NeedsHistory && includeInUpdate) audit.AppendDetail(columns[i], columnValue, dbType, oldColumnValue);
                    }

                    if (includeInUpdate)
                    {
                        isUpdateNeeded = true;

                        cmdText.Append($"{columns[i]} = @{columns[i]}");
                        cmdText.Append(",");
                        cmd.AddInParameter("@" + columns[i], dbType, columnValue);
                    }
                }
            }
            cmdText.RemoveLastComma(); //Remove last comma if exists

            cmdText.Append(" WHERE ");
            if (tableInfo.PkColumnList.Count > 1)
            {
                int index = 0;
                foreach (ColumnAttribute pkCol in tableInfo.PkColumnList)
                {
                    cmdText.Append($" {(index > 0 ? " AND " : "")} {pkCol.Name}=@{pkCol.Name}");
                    cmd.AddInParameter("@" + pkCol.Name, pkCol.ColumnDbType, tableInfo.GetKeyId(enreplacedy, pkCol));
                    index++;
                }
            }
            else
            {
                cmdText.Append($" {tableInfo.PkColumn.Name}=@{tableInfo.PkColumn.Name}");
                cmd.AddInParameter("@" + tableInfo.PkColumn.Name, tableInfo.PkColumn.ColumnDbType, tableInfo.GetKeyId(enreplacedy));
            }

            if (Config.DbConcurrencyCheck && !tableInfo.NoVersionNo)
            {
                cmdText.Append($" AND {Config.VERSIONNO_COLUMN.Name}=@{Config.VERSIONNO_COLUMN.Name}");
                cmd.AddInParameter("@" + Config.VERSIONNO_COLUMN.Name, Config.VERSIONNO_COLUMN.ColumnDbType, tableInfo.GetVersionNo(enreplacedy));
            }

            cmd.CommandType = CommandType.Text;
            cmd.CommandText = cmdText.ToString();

            return isUpdateNeeded;
        }

19 Source : Database.cs
with Apache License 2.0
from aadreja

internal virtual bool CreateUpdateCommand(IDbCommand cmd, object enreplacedy, object oldEnreplacedy, IAuditTrail audit = null, string columnNames = null, bool doNotAppendCommonFields = false, bool overrideCreatedUpdatedOn = false)
        {
            bool isUpdateNeeded = false;

            TableAttribute tableInfo = EnreplacedyCache.Get(enreplacedy.GetType());

            if (!tableInfo.NoUpdatedBy && tableInfo.IsUpdatedByEmpty(enreplacedy))
                throw new MissingFieldException("Updated By is required");

            List<string> columns = new List<string>();

            if (!string.IsNullOrEmpty(columnNames)) columns.AddRange(columnNames.Split(','));
            else columns.AddRange(tableInfo.DefaultUpdateColumns);//Get columns from Enreplacedy attributes loaded in TableInfo

            StringBuilder cmdText = new StringBuilder();
            cmdText.Append($"UPDATE {tableInfo.FullName} SET ");

            //add default columns if doesn't exists
            if (!doNotAppendCommonFields)
            {
                if (!tableInfo.NoVersionNo && !columns.Contains(Config.VERSIONNO_COLUMN.Name))
                    columns.Add(Config.VERSIONNO_COLUMN.Name);

                if (!tableInfo.NoUpdatedBy && !columns.Contains(Config.UPDATEDBY_COLUMN.Name))
                    columns.Add(Config.UPDATEDBY_COLUMN.Name);

                if (!tableInfo.NoUpdatedOn && !columns.Contains(Config.UPDATEDON_COLUMN.Name))
                    columns.Add(Config.UPDATEDON_COLUMN.Name);
            }

            //remove primarykey, createdon and createdby columns if exists
            columns.RemoveAll(c => tableInfo.PkColumnList.Select(p=>p.Name).Contains(c));
            columns.RemoveAll(c => c == Config.CREATEDON_COLUMN.Name || 
                                    c == Config.CREATEDBY_COLUMN.Name);

            for (int i = 0; i < columns.Count(); i++)
            {
                if (columns[i].Equals(Config.VERSIONNO_COLUMN.Name, StringComparison.OrdinalIgnoreCase))
                {
                    cmdText.Append($"{columns[i]} = {columns[i]}+1");
                    cmdText.Append(",");
                }
                else if (columns[i].Equals(Config.UPDATEDBY_COLUMN.Name, StringComparison.OrdinalIgnoreCase))
                {
                    cmdText.Append($"{columns[i]} = @{columns[i]}");
                    cmdText.Append(",");
                    cmd.AddInParameter("@" + columns[i], Config.UPDATEDBY_COLUMN.ColumnDbType, tableInfo.GetUpdatedBy(enreplacedy));
                }
                else if (columns[i].Equals(Config.UPDATEDON_COLUMN.Name, StringComparison.OrdinalIgnoreCase))
                {
                    var updatedOn = Helper.GetDateTimeOrDatabaseDateTimeSQL(tableInfo.GetUpdatedOn(enreplacedy), this, overrideCreatedUpdatedOn);
                    if (updatedOn is string)
                    {
                        cmdText.Append($"{columns[i]} = {CURRENTDATETIMESQL}");
                    }
                    else
                    {
                        cmdText.Append($"{columns[i]} = @{columns[i]}");
                        cmd.AddInParameter("@" + columns[i], Config.UPDATEDON_COLUMN.ColumnDbType, updatedOn);
                    }
                    cmdText.Append(",");
                }
                else
                {
                    bool includeInUpdate = true;
                    tableInfo.Columns.TryGetValue(columns[i], out ColumnAttribute columnInfo); //find column attribute

                    DbType dbType = DbType.Object;
                    object columnValue = null;

                    if (columnInfo != null && columnInfo.GetMethod != null)
                    {
                        dbType = columnInfo.ColumnDbType;
                        columnValue = columnInfo.GetAction(enreplacedy);

                        includeInUpdate = oldEnreplacedy == null; //include in update when oldEnreplacedy not available

                        //compare with old object to check whether update is needed or not
                        object oldColumnValue = null;
                        if (oldEnreplacedy != null)
                        {
                            oldColumnValue = columnInfo.GetAction(oldEnreplacedy);

                            if (oldColumnValue != null && columnValue != null)
                            {
                                if (!oldColumnValue.Equals(columnValue)) //add to history only if property is modified
                                {
                                    includeInUpdate = true;
                                }
                            }
                            else if (oldColumnValue == null && columnValue != null)
                            {
                                includeInUpdate = true;
                            }
                            else if (oldColumnValue != null)
                            {
                                includeInUpdate = true;
                            }
                        }

                        if (tableInfo.NeedsHistory && includeInUpdate) audit.AppendDetail(columns[i], columnValue, dbType, oldColumnValue);
                    }

                    if (includeInUpdate)
                    {
                        isUpdateNeeded = true;

                        cmdText.Append($"{columns[i]} = @{columns[i]}");
                        cmdText.Append(",");
                        cmd.AddInParameter("@" + columns[i], dbType, columnValue);
                    }
                }
            }
            cmdText.RemoveLastComma(); //Remove last comma if exists

            cmdText.Append(" WHERE ");
            if (tableInfo.PkColumnList.Count > 1)
            {
                int index = 0;
                foreach (ColumnAttribute pkCol in tableInfo.PkColumnList)
                {
                    cmdText.Append($" {(index > 0 ? " AND " : "")} {pkCol.Name}=@{pkCol.Name}");
                    cmd.AddInParameter("@" + pkCol.Name, pkCol.ColumnDbType, tableInfo.GetKeyId(enreplacedy, pkCol));
                    index++;
                }
            }
            else
            {
                cmdText.Append($" {tableInfo.PkColumn.Name}=@{tableInfo.PkColumn.Name}");
                cmd.AddInParameter("@" + tableInfo.PkColumn.Name, tableInfo.PkColumn.ColumnDbType, tableInfo.GetKeyId(enreplacedy));
            }

            if (Config.DbConcurrencyCheck && !tableInfo.NoVersionNo)
            {
                cmdText.Append($" AND {Config.VERSIONNO_COLUMN.Name}=@{Config.VERSIONNO_COLUMN.Name}");
                cmd.AddInParameter("@" + Config.VERSIONNO_COLUMN.Name, Config.VERSIONNO_COLUMN.ColumnDbType, tableInfo.GetVersionNo(enreplacedy));
            }

            cmd.CommandType = CommandType.Text;
            cmd.CommandText = cmdText.ToString();

            return isUpdateNeeded;
        }

19 Source : UpdateWorldController.cs
with Apache License 2.0
from AantCoder

public static void SendToServer(ModelPlayToServer toServ, bool firstRun, ModelGameServerInfo modelGameServerInfo)
        {
            //Loger.Log("Empire=" + Find.FactionManager.FirstFactionOfDef(FactionDefOf.Empire)?.GetUniqueLoadID());

            toServ.LastTick = (long)Find.TickManager.TicksGame;
            var gameProgress = new PlayerGameProgress();

            var allWorldObjectsArr = new WorldObject[Find.WorldObjects.AllWorldObjects.Count];
            Find.WorldObjects.AllWorldObjects.CopyTo(allWorldObjectsArr);

            var allWorldObjects = allWorldObjectsArr.Where(wo => wo != null).ToList();
            List<Faction> factionList = Find.FactionManager.AllFactionsListForReading;

            if (SessionClientController.Data.GeneralSettings.EquableWorldObjects)
            {
                #region Send to Server: firstRun EquableWorldObjects
                try
                {
                    // Game on init
                    if (firstRun && modelGameServerInfo != null)
                    {
                        if (modelGameServerInfo.WObjectOnlineList.Count > 0)
                        {
                            toServ.WObjectOnlineList = allWorldObjectsArr.Where(wo => wo is Settlement)
                                                                 .Where(wo => wo.HasName && !wo.Faction.IsPlayer).Select(obj => GetWorldObjects(obj)).ToList();
                        }

                        if(modelGameServerInfo.FactionOnlineList.Count > 0)
                        {
                            List <Faction> factions = Find.FactionManager.AllFactionsListForReading;
                            toServ.FactionOnlineList = factions.Select(obj => GetFactions(obj)).ToList();
                        }
                        return;
                    }
                }
                catch (Exception e)
                {
                    Loger.Log("Exception >> " + e);
                    Log.Error("SendToServer FirstRun error");
                    return;
                }
                #endregion
            }

            if (!firstRun)
            {
                //Loger.Log("Client TestBagSD 035");
                Dictionary<Map, List<Pawn>> cacheColonists = new Dictionary<Map, List<Pawn>>();
                //отправка всех новых и измененных объектов игрока
                toServ.WObjects = allWorldObjects
                    .Where(o => o.Faction?.IsPlayer == true //o.Faction != null && o.Faction.IsPlayer
                        && (o is Settlement || o is Caravan)) //Чтобы отсеч разные карты событий
                    .Select(o => GetWorldObjectEntry(o, gameProgress, cacheColonists))
                    .ToList();
                LastSendMyWorldObjects = toServ.WObjects;

                //Loger.Log("Client TestBagSD 036");
                //свои объекты которые удалил пользователь с последнего обновления
                if (ToDelete != null)
                {
                    var toDeleteNewNow = WorldObjectEntrys
                        .Where(p => !allWorldObjects.Any(wo => wo.ID == p.Key))
                        .Select(p => p.Value)
                        .ToList();
                    ToDelete.AddRange(toDeleteNewNow);
                }

                toServ.WObjectsToDelete = ToDelete;
            }
            toServ.GameProgress = gameProgress;

            if (SessionClientController.Data.GeneralSettings.EquableWorldObjects)
            {
                #region Send to Server: Non-Player World Objects
                //  Non-Player World Objects
                try
                {
                    var OnlineWObjArr = allWorldObjectsArr.Where(wo => wo is Settlement)
                                          .Where(wo => wo.HasName && !wo.Faction.IsPlayer);
                    if (!firstRun)
                    {
                        if (LastWorldObjectOnline != null && LastWorldObjectOnline.Count > 0)
                        {
                            toServ.WObjectOnlineToDelete = LastWorldObjectOnline.Where(WOnline => !OnlineWObjArr.Any(wo => ValidateOnlineWorldObject(WOnline, wo))).ToList();

                            toServ.WObjectOnlineToAdd = OnlineWObjArr.Where(wo => !LastWorldObjectOnline.Any(WOnline => ValidateOnlineWorldObject(WOnline, wo)))
                                                                        .Select(obj => GetWorldObjects(obj)).ToList();
                        }
                    }

                    toServ.WObjectOnlineList = OnlineWObjArr.Select(obj => GetWorldObjects(obj)).ToList();
                    LastWorldObjectOnline = toServ.WObjectOnlineList;
                }
                catch (Exception e)
                {
                    Loger.Log("Exception >> " + e);
                    Log.Error("ERROR SendToServer WorldObject Online");
                }
                #endregion

                #region Send to Server: Non-Player Factions
                // Non-Player Factions
                try
                {
                    if (!firstRun)
                    {
                        if (LastFactionOnline != null && LastFactionOnline.Count > 0)
                        {
                            toServ.FactionOnlineToDelete = LastFactionOnline.Where(FOnline => !factionList.Any(f => ValidateFaction(FOnline, f))).ToList();

                            toServ.FactionOnlineToAdd = factionList.Where(f => !LastFactionOnline.Any(FOnline => ValidateFaction(FOnline, f)))
                                                                        .Select(obj => GetFactions(obj)).ToList();
                        }
                    }

                    toServ.FactionOnlineList = factionList.Select(obj => GetFactions(obj)).ToList();
                    LastFactionOnline = toServ.FactionOnlineList;
                }
                catch (Exception e)
                {
                    Loger.Log("Exception >> " + e);
                    Log.Error("ERROR SendToServer Faction Online");
                }
                #endregion
            }
        }

19 Source : SimpleAnimationNodeEditor.cs
with MIT License
from aarthificial

[MenuItem("replacedets/Create/Reanimator/Simple Animation (From Textures)", false, 400)]
        private static void CreateFromTextures()
        {
            var trailingNumbersRegex = new Regex(@"(\d+$)");

            var sprites = new List<Sprite>();
            var textures = Selection.GetFiltered<Texture2D>(SelectionMode.replacedets);
            foreach (var texture in textures)
            {
                string path = replacedetDatabase.GetreplacedetPath(texture);
                sprites.AddRange(replacedetDatabase.LoadAllreplacedetsAtPath(path).OfType<Sprite>());
            }

            var cels = sprites
                .OrderBy(
                    sprite =>
                    {
                        var match = trailingNumbersRegex.Match(sprite.name);
                        return match.Success ? int.Parse(match.Groups[0].Captures[0].ToString()) : 0;
                    }
                )
                .Select(sprite => new SimpleCel(sprite))
                .ToArray();

            var replacedet = SimpleAnimationNode.Create<SimpleAnimationNode>(
                cels: cels
            );
            string baseName = trailingNumbersRegex.Replace(textures[0].name, "");
            replacedet.name = baseName + "_animation";

            string replacedetPath = Path.GetDirectoryName(replacedetDatabase.GetreplacedetPath(textures[0]));
            replacedetDatabase.Createreplacedet(replacedet, Path.Combine(replacedetPath ?? Application.dataPath, replacedet.name + ".replacedet"));
            replacedetDatabase.Savereplacedets();
        }

19 Source : CommitLogServer.cs
with MIT License
from abdullin

async Task ScheduleStore() {
            var next = TimeSpan.FromSeconds(Math.Ceiling(_env.Time.TotalSeconds * 2) / 2);
            if (_scheduled != next) {
                _scheduled = next;
                await _env.Delay(_scheduled - _env.Time);
                if (_buffer.Count > 0) {
                    await _env.SimulateWork((5 * _buffer.Count + 10).Ms());
                    _stored.AddRange(_buffer);

                    _env.Debug($"Store {_buffer.Count} events");
                    _buffer.Clear();
                }
            }
        }

19 Source : BoundsExtensions.cs
with Apache License 2.0
from abist-co-ltd

public static void GetColliderBoundsPoints(Collider collider, List<Vector3> boundsPoints, LayerMask ignoreLayers)
        {
            if (ignoreLayers == (1 << collider.gameObject.layer | ignoreLayers)) { return; }

            if (collider is SphereCollider)
            {
                SphereCollider sc = collider as SphereCollider;
                Bounds sphereBounds = new Bounds(sc.center, Vector3.one * sc.radius * 2);
                sphereBounds.GetFacePositions(sc.transform, ref corners);
                boundsPoints.AddRange(corners);
            }
            else if (collider is BoxCollider)
            {
                BoxCollider bc = collider as BoxCollider;
                Bounds boxBounds = new Bounds(bc.center, bc.size);
                boxBounds.GetCornerPositions(bc.transform, ref corners);
                boundsPoints.AddRange(corners);

            }
            else if (collider is MeshCollider)
            {
                MeshCollider mc = collider as MeshCollider;
                Bounds meshBounds = mc.sharedMesh.bounds;
                meshBounds.GetCornerPositions(mc.transform, ref corners);
                boundsPoints.AddRange(corners);
            }
            else if (collider is CapsuleCollider)
            {
                CapsuleCollider cc = collider as CapsuleCollider;
                Bounds capsuleBounds = new Bounds(cc.center, Vector3.zero);
                switch (cc.direction)
                {
                    case CAPSULE_X_AXIS:
                        capsuleBounds.size = new Vector3(cc.height, cc.radius * 2, cc.radius * 2);
                        break;

                    case CAPSULE_Y_AXIS:
                        capsuleBounds.size = new Vector3(cc.radius * 2, cc.height, cc.radius * 2);
                        break;

                    case CAPSULE_Z_AXIS:
                        capsuleBounds.size = new Vector3(cc.radius * 2, cc.radius * 2, cc.height);
                        break;
                }
                capsuleBounds.GetFacePositions(cc.transform, ref corners);
                boundsPoints.AddRange(corners);
            }
        }

19 Source : MixedRealityProjectConfiguratorWindow.cs
with Apache License 2.0
from abist-co-ltd

private void PromptForAudioSpatializer()
        {
            string selectedSpatializer = MixedRealityProjectConfigurator.SelectedSpatializer;
            List<string> spatializers = new List<string>
            {
                None
            };
            spatializers.AddRange(SpatializerUtilities.InstalledSpatializers);
            RenderDropDown(MRConfig.AudioSpatializer, "Audio spatializer:", spatializers.ToArray(), ref selectedSpatializer);
            MixedRealityProjectConfigurator.SelectedSpatializer = selectedSpatializer;
        }

19 Source : BaseDataProviderAccessCoreSystem.cs
with Apache License 2.0
from abist-co-ltd

private bool RegisterDataProviderInternal<T>(
            bool retryWithRegistrar,
            Type concreteType,
            SupportedPlatforms supportedPlatforms = (SupportedPlatforms)(-1),
            params object[] args) where T : IMixedRealityDataProvider
        {
#if !UNITY_EDITOR
            if (!Application.platform.IsPlatformSupported(supportedPlatforms))
#else
            if (!EditorUserBuildSettings.activeBuildTarget.IsPlatformSupported(supportedPlatforms))
#endif
            {
                return false;
            }

            if (concreteType == null)
            {
                Debug.LogError($"Unable to register {typeof(T).Name} service with a null concrete type.");
                return false;
            }

            if (!typeof(IMixedRealityDataProvider).IsreplacedignableFrom(concreteType))
            {
                Debug.LogError($"Unable to register the {concreteType.Name} data provider. It does not implement {typeof(IMixedRealityDataProvider)}.");
                return false;
            }

            T dataProviderInstance;

            try
            {
                dataProviderInstance = (T)Activator.CreateInstance(concreteType, args);
            }
            catch (Exception e)
            {
                if (retryWithRegistrar && (e is MissingMethodException))
                {
                    Debug.LogWarning($"Failed to find an appropriate constructor for the {concreteType.Name} data provider. Adding the Registrar instance and re-attempting registration.");
#pragma warning disable 0618
                    List<object> updatedArgs = new List<object>();
                    updatedArgs.Add(Registrar);
                    if (args != null)
                    {
                        updatedArgs.AddRange(args);
                    }
                    return RegisterDataProviderInternal<T>(
                        false, // Do NOT retry, we have already added the configured IMIxedRealityServiceRegistrar
                        concreteType,
                        supportedPlatforms,
                        updatedArgs.ToArray());
#pragma warning restore 0618
                }

                Debug.LogError($"Failed to register the {concreteType.Name} data provider: {e.GetType()} - {e.Message}");

                // Failures to create the concrete type generally surface as nested exceptions - just logging
                // the top level exception itself may not be helpful. If there is a nested exception (for example,
                // null reference in the constructor of the object itself), it's helpful to also surface those here.
                if (e.InnerException != null)
                {
                    Debug.LogError("Underlying exception information: " + e.InnerException);
                }
                return false;
            }

            return RegisterDataProvider(dataProviderInstance);
        }

19 Source : BoundsExtensions.cs
with Apache License 2.0
from abist-co-ltd

public static void GetRenderBoundsPoints(GameObject target, List<Vector3> boundsPoints, LayerMask ignoreLayers)
        {
            Renderer[] renderers = target.GetComponentsInChildren<Renderer>();
            for (int i = 0; i < renderers.Length; ++i)
            {
                Renderer rendererObj = renderers[i];
                if (ignoreLayers == (1 << rendererObj.gameObject.layer | ignoreLayers))
                {
                    continue;
                }

                rendererObj.bounds.GetCornerPositionsFromRendererBounds(ref corners);
                boundsPoints.AddRange(corners);
            }
        }

19 Source : BoundsExtensions.cs
with Apache License 2.0
from abist-co-ltd

public static void GetMeshFilterBoundsPoints(GameObject target, List<Vector3> boundsPoints, LayerMask ignoreLayers)
        {
            MeshFilter[] meshFilters = target.GetComponentsInChildren<MeshFilter>();
            for (int i = 0; i < meshFilters.Length; i++)
            {
                MeshFilter meshFilterObj = meshFilters[i];
                if (ignoreLayers == (1 << meshFilterObj.gameObject.layer | ignoreLayers))
                {
                    continue;
                }

                Bounds meshBounds = meshFilterObj.sharedMesh.bounds;
                meshBounds.GetCornerPositions(meshFilterObj.transform, ref corners);
                boundsPoints.AddRange(corners);
            }
            RectTransform[] rectTransforms = target.GetComponentsInChildren<RectTransform>();
            for (int i = 0; i < rectTransforms.Length; i++)
            {
                rectTransforms[i].GetWorldCorners(rectTransformCorners);
                boundsPoints.AddRange(rectTransformCorners);
            }
        }

19 Source : MixedRealitySearchInspectorUtility.cs
with Apache License 2.0
from abist-co-ltd

private static void OnSearchComplete(bool cancelled, UnityEngine.Object target, IReadOnlyCollection<ProfileSearchResult> results)
        {
            searchResults.Clear();

            if (cancelled || target != MixedRealitySearchInspectorUtility.activeTarget)
            {   // We've started searching something else, ignore
                return;
            }

            searchResults.AddRange(results);
            // Force editors to repaint so the results are displayed
            foreach (UnityEditor.Editor e in Resources.FindObjectsOfTypeAll<UnityEditor.Editor>())
            {
                e.Repaint();
            }
        }

19 Source : PackageManifestUpdater.cs
with Apache License 2.0
from abist-co-ltd

internal static void EnsureMSBuildForUnity()
        {
            PackageManifest manifest = null;

            string manifestPath = GetPackageManifestFilePath();
            if (string.IsNullOrWhiteSpace(manifestPath))
            {
                return;
            }

            // Read the package manifest into a list of strings (for easy finding of entries)
            // and then deserialize.
            List<string> manifestFileLines = new List<string>();
            using (FileStream manifestStream = new FileStream(manifestPath, FileMode.Open, FileAccess.Read))
            {
                using (StreamReader reader = new StreamReader(manifestStream))
                {
                    // Read the manifest file a line at a time.
                    while (!reader.EndOfStream)
                    {
                        string line = reader.ReadLine();
                        manifestFileLines.Add(line);
                    }

                    // Go back to the start of the file.
                    manifestStream.Seek(0, 0);

                    // Deserialize the scoped registries portion of the package manifest.
                    manifest = JsonUtility.FromJson<PackageManifest>(reader.ReadToEnd());
                }
            }

            if (manifest == null)
            {
                Debug.LogError($"Failed to read the package manifest file ({manifestPath})");
                return;
            }

            // Ensure that pre-existing scoped registries are retained.
            List<ScopedRegistry> scopedRegistries = new List<ScopedRegistry>();
            if ((manifest.scopedRegistries != null) && (manifest.scopedRegistries.Length > 0))
            {
                scopedRegistries.AddRange(manifest.scopedRegistries);
            }

            // Attempt to find an entry in the scoped registries collection for the MSBuild for Unity URL
            bool needToAddRegistry = true;
            foreach (ScopedRegistry registry in scopedRegistries)
            {
                if (registry.url == MSBuildRegistryUrl)
                {
                    needToAddRegistry = false;
                }
            }

            // If no entry was found, add one.
            if (needToAddRegistry)
            {
                ScopedRegistry registry = new ScopedRegistry();
                registry.name = MSBuildRegistryName;
                registry.url = MSBuildRegistryUrl;
                registry.scopes = MSBuildRegistryScopes;

                scopedRegistries.Add(registry);
            }

            // Update the manifest's scoped registries, as the collection may have been modified.
            manifest.scopedRegistries = scopedRegistries.ToArray();

            int dependenciesStartIndex = -1;
            int scopedRegistriesStartIndex = -1;
            int scopedRegistriesEndIndex = -1;
            int packageLine = -1;

            // Presume that we need to add the MSBuild for Unity package. If this value is false,
            // we will check to see if the currently configured version meets or exceeds the
            // minimum requirements.
            bool needToAddPackage = true;

            // Attempt to find the MSBuild for Unity package entry in the dependencies collection
            // This loop also identifies the dependencies collection line and the start / end of a
            // pre-existing scoped registries collections
            for (int i = 0; i < manifestFileLines.Count; i++)
            {
                if (manifestFileLines[i].Contains("\"scopedRegistries\":"))
                {
                    scopedRegistriesStartIndex = i;
                }
                if (manifestFileLines[i].Contains("],") && (scopedRegistriesStartIndex != -1) && (scopedRegistriesEndIndex == -1))
                {
                    scopedRegistriesEndIndex = i;
                }
                if (manifestFileLines[i].Contains("\"dependencies\": {"))
                {
                    dependenciesStartIndex = i;
                }
                if (manifestFileLines[i].Contains(MSBuildPackageName))
                {
                    packageLine = i;
                    needToAddPackage = false;
                }
            }

            // If no package was found add it to the dependencies collection.
            if (needToAddPackage)
            {
                // Add the package to the collection (pad the entry with four spaces)
                manifestFileLines.Insert(dependenciesStartIndex + 1, $"    \"{MSBuildPackageName}\": \"{MSBuildPackageVersion}\",");
            }
            else
            {
                // Replace the line that currently exists
                manifestFileLines[packageLine] = $"    \"{MSBuildPackageName}\": \"{MSBuildPackageVersion}\",";
            }

            // Update the manifest file.
            // First, serialize the scoped registry collection.
            string serializedRegistriesJson = JsonUtility.ToJson(manifest, true);

            // Ensure that the file is truncated to ensure it is always valid after writing.
            using (FileStream outFile = new FileStream(manifestPath, FileMode.Truncate, FileAccess.Write))
            {
                using (StreamWriter writer = new StreamWriter(outFile))
                {
                    bool scopedRegistriesWritten = false;

                    // Write each line of the manifest back to the file.
                    for (int i = 0; i < manifestFileLines.Count; i++)
                    {
                        if ((i >= scopedRegistriesStartIndex) && (i <= scopedRegistriesEndIndex))
                        {
                            // Skip these lines, they will be replaced.
                            continue;
                        }

                        if (!scopedRegistriesWritten && (i > 0))
                        {
                            // Trim the leading '{' and '\n' from the serialized scoped registries
                            serializedRegistriesJson = serializedRegistriesJson.Remove(0, 2);
                            // Trim, the trailing '\n' and '}'
                            serializedRegistriesJson = serializedRegistriesJson.Remove(serializedRegistriesJson.Length - 2);
                            // Append a trailing ',' to close the scopedRegistries node
                            serializedRegistriesJson = serializedRegistriesJson.Insert(serializedRegistriesJson.Length, ",");
                            writer.WriteLine(serializedRegistriesJson);

                            scopedRegistriesWritten = true;
                        }

                        writer.WriteLine(manifestFileLines[i]);
                    }
                }
            }
        }

19 Source : DialogShell.cs
with Apache License 2.0
from abist-co-ltd

private List<DialogButton> GetAllDialogButtons()
        {
            List<DialogButton> buttonsOnDialog = new List<DialogButton>();
            for (int i = 0; i < transform.childCount; i++)
            {
                Transform child = transform.GetChild(i);
                if (child.name == "ButtonParent")
                {
                    var buttons = child.GetComponentsInChildren<DialogButton>();
                    if (buttons != null)
                    {
                        buttonsOnDialog.AddRange(buttons);
                    }
                }
            }
            return buttonsOnDialog;
        }

19 Source : MixedRealityInspectorUtility.cs
with Apache License 2.0
from abist-co-ltd

private static Type[] GetAllDerivedTypes(this AppDomain appDomain, Type aType)
        {
            var result = new List<Type>();
            var replacedemblies = appDomain.Getreplacedemblies();

            foreach (var replacedembly in replacedemblies)
            {
                var types = replacedembly.GetLoadableTypes();
                result.AddRange(types.Where(type => type.IsSubclreplacedOf(aType)));
            }

            return result.ToArray();
        }

19 Source : UnityARConfigurationChecker.cs
with Apache License 2.0
from abist-co-ltd

private static void UpdateAsmDef(bool arFoundationPresent)
        {
            const string asmDefFileName = "Microsoft.MixedReality.Toolkit.Providers.UnityAR.asmdef";
            FileInfo[] asmDefFiles = FileUtilities.FindFilesInreplacedets(asmDefFileName);

            if (asmDefFiles.Length == 0)
            {
                Debug.LogWarning($"Unable to locate file: {asmDefFileName}");
                return;
            }
            if (asmDefFiles.Length > 1)
            {
                Debug.LogWarning($"Multiple ({asmDefFiles.Length}) {asmDefFileName} instances found. Modifying only the first.");
            }

            replacedemblyDefinition asmDef = replacedemblyDefinition.Load(asmDefFiles[0].FullName);
            if (asmDef == null)
            {
                Debug.LogWarning($"Unable to load file: {asmDefFileName}");
                return;
            }

            List<string> references = new List<string>();
            if (asmDef.References != null)
            {
                references.AddRange(asmDef.References);
            }

            // ARFoundation replacedembly names
            const string arFoundationReference = "Unity.XR.ARFoundation";
            const string spatialTrackingReference = "UnityEngine.SpatialTracking";
            bool changed = false;

            if (arFoundationPresent)
            {
#if UNITY_2018 || UNITY_2019_1_OR_NEWER
                if (!references.Contains(arFoundationReference))
                {
                    // Add a reference to the ARFoundation replacedembly
                    references.Add(arFoundationReference);
                    changed = true; 
                }
#endif
#if UNITY_2019_1_OR_NEWER
                if (!references.Contains(spatialTrackingReference))
                {
                    // Add a reference to the spatial tracking replacedembly
                    references.Add(spatialTrackingReference);
                    changed = true;
                }
#elif UNITY_2018
                if (references.Contains(spatialTrackingReference))
                {
                    // Remove the reference to the spatial tracking replacedembly
                    references.Remove(spatialTrackingReference);
                    changed = true;
                }
#endif
            }
            else
            {
                // Remove all ARFoundation related replacedembly references
                if (references.Contains(arFoundationReference))
                {
                    references.Remove(arFoundationReference);
                    changed = true;
                }
                if (references.Contains(spatialTrackingReference))
                {
                    references.Remove(spatialTrackingReference);
                    changed = true;
                }
            }

            if (changed)
            {
                asmDef.References = references.ToArray();
                asmDef.Save(asmDefFiles[0].FullName);
            }
        }

19 Source : WindowsMixedRealityXRSDKConfigurationChecker.cs
with Apache License 2.0
from abist-co-ltd

private static void UpdateAsmDef()
        {
            FileInfo[] asmDefFiles = FileUtilities.FindFilesInreplacedets(AsmDefFileName);

            if (asmDefFiles.Length == 0)
            {
                Debug.LogWarning($"Unable to locate file: {AsmDefFileName}");
                return;
            }
            if (asmDefFiles.Length > 1)
            {
                Debug.LogWarning($"Multiple ({asmDefFiles.Length}) {AsmDefFileName} instances found. Modifying only the first.");
            }

            replacedemblyDefinition asmDef = replacedemblyDefinition.Load(asmDefFiles[0].FullName);
            if (asmDef == null)
            {
                Debug.LogWarning($"Unable to load file: {AsmDefFileName}");
                return;
            }

            List<string> references = new List<string>();
            if (asmDef.References != null)
            {
                references.AddRange(asmDef.References);
            }

            bool changed = false;

#if UNITY_2019_3_OR_NEWER
            List<VersionDefine> versionDefines = new List<VersionDefine>();
            if (asmDef.VersionDefines != null)
            {
                versionDefines.AddRange(asmDef.VersionDefines);
            }

            if (!references.Contains(WindowsMixedRealityReference))
            {
                // Add a reference to the XR SDK WMR replacedembly
                references.Add(WindowsMixedRealityReference);
                changed = true; 
            }

            if (!versionDefines.Contains(WindowsMixedRealityDefine))
            {
                // Add the WMR #define
                versionDefines.Add(WindowsMixedRealityDefine);
                changed = true;
            }
#else
            if (references.Contains(WindowsMixedRealityReference))
            {
                // Remove the reference to the XR SDK WMR replacedembly
                references.Remove(WindowsMixedRealityReference);
                changed = true;
            }
#endif

            if (changed)
            {
                asmDef.References = references.ToArray();
#if UNITY_2019_3_OR_NEWER
                asmDef.VersionDefines = versionDefines.ToArray();
#endif // UNITY_2019_3_OR_NEWER
                asmDef.Save(asmDefFiles[0].FullName);
            }
        }

19 Source : XRSDKConfigurationChecker.cs
with Apache License 2.0
from abist-co-ltd

private static void UpdateAsmDef()
        {
            FileInfo[] asmDefFiles = FileUtilities.FindFilesInreplacedets(AsmDefFileName);

            if (asmDefFiles.Length == 0)
            {
                Debug.LogWarning($"Unable to locate file: {AsmDefFileName}");
                return;
            }
            if (asmDefFiles.Length > 1)
            {
                Debug.LogWarning($"Multiple ({asmDefFiles.Length}) {AsmDefFileName} instances found. Modifying only the first.");
            }

            replacedemblyDefinition asmDef = replacedemblyDefinition.Load(asmDefFiles[0].FullName);
            if (asmDef == null)
            {
                Debug.LogWarning($"Unable to load file: {AsmDefFileName}");
                return;
            }

            List<string> references = new List<string>();
            if (asmDef.References != null)
            {
                references.AddRange(asmDef.References);
            }

            bool changed = false;

#if UNITY_2019_3_OR_NEWER
            List<VersionDefine> versionDefines = new List<VersionDefine>();
            if (asmDef.VersionDefines != null)
            {
                versionDefines.AddRange(asmDef.VersionDefines);
            }

            if (!references.Contains(XRManagementReference))
            {
                // Add a reference to the ARFoundation replacedembly
                references.Add(XRManagementReference);
                changed = true; 
            }
            if (!references.Contains(SpatialTrackingReference))
            {
                // Add a reference to the spatial tracking replacedembly
                references.Add(SpatialTrackingReference);
                changed = true;
            }

            if (!versionDefines.Contains(XRManagementDefine))
            {
                // Add the XRManagement #define
                versionDefines.Add(XRManagementDefine);
                changed = true;
            }
            if (!versionDefines.Contains(SpatialTrackingDefine))
            {
                // Add the spatial tracking #define
                versionDefines.Add(SpatialTrackingDefine);
                changed = true;
            }
#else
            if (references.Contains(XRManagementReference))
            {
                // Remove the reference to the XRManagement replacedembly
                references.Remove(XRManagementReference);
                changed = true;
            }
            if (references.Contains(SpatialTrackingReference))
            {
                // Remove the reference to the spatial tracking replacedembly
                references.Remove(SpatialTrackingReference);
                changed = true;
            }
#endif

            if (changed)
            {
                asmDef.References = references.ToArray();
#if UNITY_2019_3_OR_NEWER
                asmDef.VersionDefines = versionDefines.ToArray();
#endif // UNITY_2019_3_OR_NEWER
                asmDef.Save(asmDefFiles[0].FullName);
            }
        }

19 Source : XRSDKDeviceManager.cs
with Apache License 2.0
from abist-co-ltd

public override void Update()
        {
            using (UpdatePerfMarker.Auto())
            {
                base.Update();

                if (XRSDKSubsystemHelpers.InputSubsystem == null || !XRSDKSubsystemHelpers.InputSubsystem.running)
                {
                    return;
                }

                InputDevices.GetDevicesWithCharacteristics(InputDeviceCharacteristics.Controller, inputDevices);
                foreach (InputDevice device in inputDevices)
                {
                    if (device.isValid)
                    {
                        GenericXRSDKController controller = GetOrAddController(device);

                        if (controller == null)
                        {
                            continue;
                        }

                        if (!lastInputDevices.Contains(device))
                        {
                            CoreServices.InputSystem?.RaiseSourceDetected(controller.InputSource, controller);
                        }
                        else
                        {
                            // Remove devices from our previously tracked list as we update them.
                            // This will allow us to remove all stale devices that were tracked
                            // last frame but not this one.
                            lastInputDevices.Remove(device);
                            controller.UpdateController(device);
                        }
                    }
                }

                foreach (InputDevice device in lastInputDevices)
                {
                    GenericXRSDKController controller = GetOrAddController(device);
                    if (controller != null)
                    {
                        CoreServices.InputSystem?.RaiseSourceLost(controller.InputSource, controller);
                        RemoveController(device);
                    }
                }

                lastInputDevices.Clear();
                lastInputDevices.AddRange(inputDevices);
            }
        }

19 Source : BoundsControl.cs
with Apache License 2.0
from abist-co-ltd

private Bounds GetTargetBounds()
        {
            totalBoundsCorners.Clear();

            // Collect all Transforms except for the rigRoot(s) transform structure(s)
            // Its possible we have two rigRoots here, the one about to be deleted and the new one
            // Since those have the gizmo structure childed, be need to omit them completely in the calculation of the bounds
            // This can only happen by name unless there is a better idea of tracking the rigRoot that needs destruction

            List<Transform> childTransforms = new List<Transform>();
            if (Target != gameObject)
            {
                childTransforms.Add(Target.transform);
            }

            foreach (Transform childTransform in Target.transform)
            {
                if (childTransform.name.Equals(rigRootName)) { continue; }
                childTransforms.AddRange(childTransform.GetComponentsInChildren<Transform>());
            }

            // Iterate transforms and collect bound volumes

            foreach (Transform childTransform in childTransforms)
            {
                Debug.replacedert(childTransform != rigRoot);

                ExtractBoundsCorners(childTransform, boundsCalculationMethod);
            }

            Transform targetTransform = Target.transform;

            // In case we found nothing and this is the Target, we add it's inevitable collider's bounds
            if (totalBoundsCorners.Count == 0 && Target == gameObject)
            {
                ExtractBoundsCorners(targetTransform, BoundsCalculationMethod.ColliderOnly);
            }

            Bounds finalBounds = new Bounds(targetTransform.InverseTransformPoint(totalBoundsCorners[0]), Vector3.zero);

            for (int i = 1; i < totalBoundsCorners.Count; i++)
            {
                finalBounds.Encapsulate(targetTransform.InverseTransformPoint(totalBoundsCorners[i]));
            }

            return finalBounds;
        }

19 Source : BoundsControl.cs
with Apache License 2.0
from abist-co-ltd

private bool AddRendererBoundsCornersToTarget(KeyValuePair<Transform, Bounds> rendererBoundsByTarget)
        {
            if (rendererBoundsByTarget.Key == null) { return false; }

            Vector3[] cornersToWorld = null;
            rendererBoundsByTarget.Value.GetCornerPositions(rendererBoundsByTarget.Key, ref cornersToWorld);
            totalBoundsCorners.AddRange(cornersToWorld);
            return true;
        }

19 Source : InteractableOnFocus.cs
with Apache License 2.0
from abist-co-ltd

public void Awake()
        {
            foreach (var profile in Profiles)
            {
                var themeEngines = profile.CreateThemeEngines();

                themes.AddRange(themeEngines);
            }
        }

19 Source : BoundingBoxHelper.cs
with Apache License 2.0
from abist-co-ltd

public void UpdateNonAABoundsCornerPositions(BoxCollider colliderBounds, List<Vector3> boundsPoints)
        {
            if (colliderBounds != targetBounds || rawBoundingCornersObtained == false)
            {
                GetRawBoundsCorners(colliderBounds);
            }

            if (colliderBounds == targetBounds && rawBoundingCornersObtained)
            {
                boundsPoints.Clear();
                for (int i = 0; i < rawBoundingCorners.Count; ++i)
                {
                    boundsPoints.Add(colliderBounds.transform.localToWorldMatrix.MultiplyPoint(rawBoundingCorners[i]));
                }

                worldBoundingCorners.Clear();
                worldBoundingCorners.AddRange(boundsPoints);
            }
        }

19 Source : BoundingBoxHelper.cs
with Apache License 2.0
from abist-co-ltd

public static void GetUntransformedCornersFromObject(BoxCollider targetBounds, List<Vector3> boundsPoints)
        {
            Bounds cloneBounds = new Bounds(targetBounds.center, targetBounds.size);
            Vector3[] corners = null;
            cloneBounds.GetCornerPositions(ref corners);
            boundsPoints.AddRange(corners);
        }

19 Source : HandInteractionPanZoom.cs
with Apache License 2.0
from abist-co-ltd

private void UpdateUVMapping()
        {
            Vector2 tiling = currentMaterial != null ? currentMaterial.mainTextureScale : new Vector2(1.0f, 1.0f);
            Vector2 uvTestValue;
            mesh.GetUVs(0, uvs);
            uvsOrig.Clear();
            uvsOrig.AddRange(uvs);
            float scaleUVDelta = 0.0f;
            Vector2 scaleUVCentroid = Vector2.zero;
            float currentContactRatio = 0.0f;

            if (scaleActive)
            {
                scaleUVCentroid = GetDisplayedUVCentroid(uvs);
                currentContactRatio = GetUVScaleFromTouches();
                scaleUVDelta = currentContactRatio / previousContactRatio;
                previousContactRatio = currentContactRatio;

                currentScale = totalUVScale.x / scaleUVDelta;

                // Test for scale limits
                if (currentScale > minScale && currentScale < maxScale)
                {
                    // Track total scale
                    totalUVScale /= scaleUVDelta;
                    for (int i = 0; i < uvs.Count; ++i)
                    {
                        // This is where zoom is applied if Active
                        uvs[i] = ((uvs[i] - scaleUVCentroid) / scaleUVDelta) + scaleUVCentroid;
                    }
                }
            }

            // Test for pan limits
            Vector2 uvDelta = new Vector2(totalUVOffset.x, -totalUVOffset.y);
            if (!unlimitedPan)
            {
                bool xLimited = false;
                bool yLimited = false;
                for (int i = 0; i < uvs.Count; ++i)
                {
                    uvTestValue = uvs[i] - uvDelta;
                    if (uvTestValue.x > tiling.x * maxPanHorizontal || uvTestValue.x < -(tiling.x * maxPanHorizontal))
                    {
                        xLimited = true;
                    }
                    if (uvTestValue.y > tiling.y * maxPanVertical || uvTestValue.y < -(tiling.y * maxPanVertical))
                    {
                        yLimited = true;
                    }
                }

                for (int i = 0; i < uvs.Count; ++i)
                {
                    uvs[i] = new Vector2(xLimited ? uvs[i].x : uvs[i].x - uvDelta.x, yLimited ? uvs[i].y : uvs[i].y - uvDelta.y);
                }
            }
            else
            {
                for (int i = 0; i < uvs.Count; ++i)
                {
                    uvs[i] -= uvDelta;
                }
            }

            mesh.SetUVs(0, uvs);
        }

19 Source : InteractableHighlight.cs
with Apache License 2.0
from abist-co-ltd

private void AddHighlightMaterials()
        {
            // If we've added our focus materials already, split
            if ((currentStyle & targetStyle) != 0) { return; }

            if (materialsBeforeFocus == null)
            {
                materialsBeforeFocus = new Dictionary<Renderer, List<Material>>();
            }

            for (int i = 0; i < targetRenderers.Length; i++)
            {
                List<Material> preFocusMaterials;

                if (!materialsBeforeFocus.TryGetValue(targetRenderers[i], out preFocusMaterials))
                {
                    preFocusMaterials = new List<Material>();
                    materialsBeforeFocus.Add(targetRenderers[i], preFocusMaterials);
                }
                else
                {
                    preFocusMaterials.Clear();
                }

                preFocusMaterials.AddRange(targetRenderers[i].sharedMaterials);
                // Remove any references to outline and highlight materials
                preFocusMaterials.Remove(highlightMaterial);
                preFocusMaterials.Remove(overlayMaterial);
            }

            // If we're using a highlight
            if ((targetStyle & HighlightedMaterialStyle.Highlight) != 0)
            {
                // And we haven't added it yet
                if ((currentStyle & HighlightedMaterialStyle.Highlight) == 0)
                {
                    AddMaterialToRenderers(targetRenderers, highlightMaterial, highlightColorProperty, highlightColor);
                }
            }

            // If we're using an outline
            if ((targetStyle & HighlightedMaterialStyle.Overlay) != 0)
            {
                // And we haven't added it yet
                if ((currentStyle & HighlightedMaterialStyle.Overlay) == 0)
                {
                    AddMaterialToRenderers(targetRenderers, overlayMaterial, outlineColorProperty, outlineColor);
                }
            }

            currentStyle = targetStyle;
        }

19 Source : OVRResources.cs
with MIT License
from absurd-joy

public static void SetResourceBundle(replacedetBundle bundle)
	{
		resourceBundle = bundle;
		replacedetNames = new List<string>();
		replacedetNames.AddRange(resourceBundle.GetAllreplacedetNames());
	}

19 Source : ExampleSourceCodeFormattingConverter.cs
with MIT License
from ABTSoftware

public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            if (MainWindowViewModel.SearchText.IsNullOrEmpty())
            {
                return string.Empty;
            }

            var terms = MainWindowViewModel.SearchText.Split(' ').Where(word => word != "").Select(x => x.ToLower()).ToArray();
            var codeFiles = (Dictionary<string, string>) value;

            var uiCodeFiles = codeFiles.Where(x => x.Key.EndsWith(".xaml"));

            var lines = new List<string>();
            foreach (var file in uiCodeFiles)
            {
                lines.AddRange(file.Value.Split(new[] {"\r\n"}, StringSplitOptions.None));
            }

            var toHighlight = new HashSet<string>();
            foreach (var term in terms)
            {
                var containsTerm = lines.Where(x => x != "" && x.ToLower().Contains(term));
                containsTerm.Take(2).Select(x => x.Trim()).ForEachDo(x => toHighlight.Add(x));
            }

            string result;

            if (toHighlight.Any())
            {
                lines = toHighlight.Take(2).Select(x => x.Trim().Replace('<', ' ').Replace('>', ' ') + '.').ToList();
                result = HighlightText(lines, terms);
            }
            else
            {
                var sentences = lines.Take(2).Select(x => string.Format("... {0} ...", x.Trim().Replace('<', ' ').Replace('>', ' ').ToList()));
                result = string.Join("\n", sentences);
            }

            return result;
        }

19 Source : GenericAutomationPeer.cs
with MIT License
from ABTSoftware

protected override List<AutomationPeer> GetChildrenCore()
        {
            var list = base.GetChildrenCore();
            list?.AddRange(GetChildPeers(Owner));
            return list;
        }

19 Source : GenericAutomationPeer.cs
with MIT License
from ABTSoftware

private List<AutomationPeer> GetChildPeers(UIElement element)
        {
            var list = new List<AutomationPeer>();
            for (int i = 0; i < VisualTreeHelper.GetChildrenCount(element); i++)
            {
                var child = VisualTreeHelper.GetChild(element, i) as UIElement;
                if (child != null)
                {
                    AutomationPeer childPeer;
                    if (child is GroupItem)
                    {
                        childPeer = new GenericAutomationPeer(child);
                    }
                    else
                    {
                        childPeer = UIElementAutomationPeer.CreatePeerForElement(child);
                    }
                    if (childPeer != null)
                    {
                        list.Add(childPeer);
                    }
                    else
                    {
                        list.AddRange(GetChildPeers(child));
                    }
                }
            }
            return list;
        }

19 Source : SciChartInteractionToolbar.cs
with MIT License
from ABTSoftware

private static void OnIsDeveloperModeChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            var toolbar = (SciChartInteractionToolbar) d;
            var scs = toolbar.TargetSurface;

            if (scs != null)
            {
                bool devModOn = (bool) e.NewValue;
                scs.ChartModifier = devModOn ? toolbar._modifiersInDevMode : toolbar._modifiersInUserMode;

                var listMod = new List<ToolbarItem>();
                var wrappers = WrapModifiers(toolbar.IsDeveloperMode
                    ? toolbar._modifiersInDevMode.ChildModifiers
                    : toolbar._modifiersInUserMode.ChildModifiers);

                listMod.AddRange(wrappers);

                if (listMod.Any(x =>
                    x.Modifier.ModifierName == "AnnotationCreationModifier" ||
                    x.Modifier is VerticalSliceModifier))
                {
                    listMod.Remove(listMod.FirstOrDefault(x => x.Modifier.ModifierName == "AnnotationCreationModifier"));
                    listMod.Remove(listMod.FirstOrDefault(x => x.Modifier is VerticalSliceModifier));
                }

                toolbar.ModifiersSource = listMod;
            }
        }

19 Source : SciChart3DInteractionToolbar.cs
with MIT License
from ABTSoftware

private static void OnIsDeveloperModeChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            var toolbar = (SciChart3DInteractionToolbar)d;
            var scs = toolbar.TargetSurface;

            if (scs != null)
            {
                var devModOn = (bool)e.NewValue;

                scs.ChartModifier = devModOn ? toolbar._modifiersInDevMode : toolbar._modifiersInUserMode;

                var listMod = new List<SciChart3DToolbarItem>();

                var wrappers = toolbar.IsDeveloperMode
                    ? toolbar._modifiersInDevMode.ChildModifiers
                    : toolbar._modifiersInUserMode.ChildModifiers;

                listMod.AddRange(wrappers.Select(mod => new SciChart3DToolbarItem { Modifier = mod }));

                toolbar.ModifiersSource = listMod;
            }
        }

19 Source : SciChart3DInteractionToolbar.cs
with MIT License
from ABTSoftware

protected virtual void OnCreateModifiers(SciChart3DInteractionToolbar toolbar, ISciChart3DSurface scs)
        {
            var freeLookModifier = new FreeLookModifier3D { IsEnabled = false };
            var orbitModifier = new OrbitModifier3D { IsEnabled = true, ExecuteOn = ExecuteOn.MouseLeftButton };
            var zoomExtentsModifier = new ZoomExtentsModifier3D { AnimateDurationMs = 500, AutoFitRadius = true, ResetPosition = new Vector3(-300, 100, -300) };
            var mouseWheelZoomPanModifier = new MouseWheelZoomModifier3D();

            var vertexSelectionMod = new VertexSelectionModifier3D { IsEnabled = false, ExecuteOn = ExecuteOn.MouseLeftButton, ExecuteWhen = MouseModifier.Ctrl };
            var tooltipMod = new TooltipModifier3D { IsEnabled = false, ShowTooltipOn = ShowTooltipOptions.MouseOver };
            var legendMod = new LegendModifier3D { LegendPlacement = LegendPlacement.Inside, ShowLegend = false };

            _modifiersInAllMode.ChildModifiers.Add(orbitModifier);
            _modifiersInDevMode.ChildModifiers.Add(orbitModifier);

            _modifiersInAllMode.ChildModifiers.Add(freeLookModifier);
            _modifiersInDevMode.ChildModifiers.Add(freeLookModifier);

            _modifiersInAllMode.ChildModifiers.Add(zoomExtentsModifier);
            _modifiersInDevMode.ChildModifiers.Add(zoomExtentsModifier);

            _modifiersInAllMode.ChildModifiers.Add(mouseWheelZoomPanModifier);
            _modifiersInDevMode.ChildModifiers.Add(mouseWheelZoomPanModifier);

            _modifiersInDevMode.ChildModifiers.Add(vertexSelectionMod);
            _modifiersInDevMode.ChildModifiers.Add(legendMod);
            _modifiersInDevMode.ChildModifiers.Add(tooltipMod);

            var exampleModifiers = (scs.ChartModifier as ModifierGroup3D);

            if (exampleModifiers == null)
            {
                exampleModifiers = new ModifierGroup3D();

                if (scs.ChartModifier != null)
                {
                    exampleModifiers.ChildModifiers.Add(scs.ChartModifier);
                }
            }

            var devMods = new ModifierGroup3D();
            var userMods = new ModifierGroup3D();

            foreach (var devMod in _modifiersInDevMode.ChildModifiers)
            {
                var devModName = devMod.ModifierName;

                if (!(exampleModifiers.ChildModifiers.Any(x => x.ModifierName == devModName)))
                {
                    devMods.ChildModifiers.Add(devMod);
                }
                else
                {
                    if (exampleModifiers.ChildModifiers.Count(x => x.ModifierName == devModName) == 1)
                    {
                        var exampleMod = exampleModifiers.ChildModifiers.Single(x => x.ModifierName == devModName);
                        devMods.ChildModifiers.Add(exampleMod);
                    }
                    else 
                    {
                        foreach (var exampleMod in exampleModifiers.ChildModifiers.Where(x => x.ModifierName == devModName))
                        {
                            devMods.ChildModifiers.Add(exampleMod);
                        }
                    }
                }
            }

            foreach (var inAllMod in _modifiersInAllMode.ChildModifiers)
            {
                var modName = inAllMod.ModifierName;

                if (!(exampleModifiers.ChildModifiers.Any(x => x.ModifierName == modName)))
                {
                    userMods.ChildModifiers.Add(inAllMod);
                }
                else
                {
                    if (exampleModifiers.ChildModifiers.Count(x => x.ModifierName == modName) == 1)
                    {
                        var exampleMod = exampleModifiers.ChildModifiers.Single(x => x.ModifierName == modName);
                        userMods.ChildModifiers.Add(exampleMod);
                    }
                    else
                    {
                        foreach (var exampleMod in exampleModifiers.ChildModifiers.Where(x => x.ModifierName == modName))
                        {
                            userMods.ChildModifiers.Add(exampleMod);
                        }
                    }
                }
            }

            foreach (var exampleMod in exampleModifiers.ChildModifiers)
            {
                if (!devMods.ChildModifiers.Any(x => x.ModifierName == exampleMod.ModifierName))
                {
                    devMods.ChildModifiers.Add(exampleMod);
                }

                if (!userMods.ChildModifiers.Any(x => x.ModifierName == exampleMod.ModifierName))
                {
                    userMods.ChildModifiers.Add(exampleMod);
                }
            }

            _modifiersInDevMode = devMods;
            _modifiersInUserMode = userMods;

            // Set modifiers to the chart
            scs.ChartModifier = IsDeveloperMode ? _modifiersInDevMode : _modifiersInUserMode;

            var wrappers = toolbar.IsDeveloperMode
                ? _modifiersInDevMode.ChildModifiers
                : _modifiersInUserMode.ChildModifiers;

            // Set modifiers to the ItemSource for ItemsControl
            var listMod = new List<SciChart3DToolbarItem>();

            listMod.AddRange(wrappers.Select(mod => new SciChart3DToolbarItem { Modifier = mod }));

            ModifiersSource = listMod;

        }

19 Source : AscReader.cs
with MIT License
from ABTSoftware

private static AscData ReadFromStream(StreamReader stream, Func<float, Color> colorMapFunction, Action<int> reportProgress = null)
        {
            var result = new AscData
            {
                XValues = new List<float>(),
                YValues = new List<float>(),
                ZValues = new List<float>(),
                ColorValues = new List<Color>(),
                NumberColumns = ReadInt(stream, "ncols"),
                NumberRows = ReadInt(stream, "nrows"),
                XllCorner = ReadInt(stream, "xllcorner"),
                YllCorner = ReadInt(stream, "yllcorner"),
                CellSize = ReadInt(stream, "cellsize"),
                NoDataValue = ReadInt(stream, "NODATA_value"),
            };

            // Load the ASC file format 

            // Generate X-values based off cell position 
            float[] xValuesRow = Enumerable.Range(0, result.NumberColumns).Select(x => (float)x * result.CellSize).ToArray();

            for (int i = 0; i < result.NumberRows; i++)
            {
                // Read heights from the ASC file and generate Z-cell values
                float[] heightValuesRow = ReadFloats(stream, " ", result.NoDataValue);
                float[] zValuesRow = Enumerable.Repeat(0 + i * result.CellSize, result.NumberRows).Select(x => (float)x).ToArray();

                result.XValues.AddRange(xValuesRow);
                result.YValues.AddRange(heightValuesRow);
                result.ZValues.AddRange(zValuesRow);

                if (colorMapFunction != null)
                {
                    // Optional color-mapping of points based on height 
                    Color[] colorValuesRow = heightValuesRow
                        .Select(colorMapFunction)
                        .ToArray();
                    result.ColorValues.AddRange(colorValuesRow);
                }

                // Optional report loading progress 0-100%
                reportProgress?.Invoke((int)(100.0f * i / result.NumberRows));
            }

            return result;
        }

19 Source : SciChartInteractionToolbar.cs
with MIT License
from ABTSoftware

protected virtual void OnCreateModifiers(SciChartInteractionToolbar toolbar, ISciChartSurface scs)
        {
            var isPolar = (scs is SciChartSurface surface) && (surface.IsPolarChart ||
                surface.XAxes.Any(x => x.IsPolarAxis) ||
                surface.YAxes.Any(x => x.IsPolarAxis));
                     
            var listMod = new List<ToolbarItem>();

            // RubberBandXyZoomModifier
            var rbzm = new RubberBandXyZoomModifier { IsXAxisOnly = IsZoomXAxisOnly };
            _modifiersInAllMode.ChildModifiers.Add(rbzm);
            _modifiersInDevMode.ChildModifiers.Add(rbzm);
            
            if (!isPolar)
            {
                // ZoomPanModifier
                var zpm = new ZoomPanModifier { ClipModeX = ClipMode.None, IsEnabled = false };
                _modifiersInAllMode.ChildModifiers.Add(zpm);
                _modifiersInDevMode.ChildModifiers.Add(zpm);
            }

            // ZoomExtentsModifier
            var zoomExtents = new ZoomExtentsModifier { ExecuteOn = ExecuteOn.MouseDoubleClick };
            _modifiersInAllMode.ChildModifiers.Add(zoomExtents);
            _modifiersInDevMode.ChildModifiers.Add(zoomExtents);

            // SeriesSelectionModifier
            var selStyle = new Style(typeof(BaseRenderableSeries));
            selStyle.Setters.Add(new Setter(BaseRenderableSeries.StrokeProperty, Colors.Red));
            selStyle.Setters.Add(new Setter(BaseRenderableSeries.StrokeThicknessProperty, 2));
            selStyle.Seal();

            var seriesSelection = new SeriesSelectionModifier
            {
                SelectedSeriesStyle = selStyle,
                ReceiveHandledEvents = true,
                IsEnabled = false
            };
            _modifiersInDevMode.ChildModifiers.Add(seriesSelection);

            // AnnotationCreationModifier
            var annotationMod = new CustomAnnotationCreationModifier
            {
                XAxisId = scs.XAxes.Any() ? scs.XAxes.First().Id : AxisCore.DefaultAxisId,
                YAxisId = scs.YAxes.Any() ? scs.YAxes.First().Id : AxisCore.DefaultAxisId
            };

            annotationMod.AnnotationCreated += (sender, args) =>
            {
                var modifier = (CustomAnnotationCreationModifier)sender;
                if (modifier != null)
                {
                    foreach (var annotation in scs.Annotations)
                    {
                        if (annotation is AnnotationBase newAnnotation)
                        {
                            newAnnotation.IsEditable = true;
                            newAnnotation.CanEditText = true;
                        }
                    }

                    modifier.IsEnabled = false;
                }
            };
            annotationMod.IsEnabled = false;
            _modifiersInDevMode.ChildModifiers.Add(annotationMod);

            // CustomRotateChartModifier
            var rotate = new CustomRotateChartModifier();
            var propertyPath = new PropertyPath(CustomRotateChartModifier.IsRotationEnabledProperty);
            var binding = new Binding() { Source = this, Path = propertyPath };
            
            rotate.SetBinding(ChartModifierBase.IsEnabledProperty, binding);

            _modifiersInDevMode.ChildModifiers.Add(rotate);

            // Custom Export Modifier
            var export = new CustomExportModifier();
            _modifiersInDevMode.ChildModifiers.Add(export);

            // CustomThemeChangeModifier
            var theme = new CustomThemeChangeModifier();
            _modifiersInDevMode.ChildModifiers.Add(theme);

            // LegendModifier
            var legend = new LegendModifier
            {
                UseInterpolation = true,
                ShowLegend = false,
                ShowVisibilityCheckboxes = true,
                ShowSeriesMarkers = true
            };
            _modifiersInDevMode.ChildModifiers.Add(legend);

            // MouseWheelZoomModifier
            var mouseWheel = new MouseWheelZoomModifier();
            _modifiersInAllMode.ChildModifiers.Add(mouseWheel);
            _modifiersInDevMode.ChildModifiers.Add(mouseWheel);

            // CustomFlipModifier
            var flip = new CustomFlipModifier();
            _modifiersInDevMode.ChildModifiers.Add(flip);

            // RolloverModifier
            var rollover = new RolloverModifier
            {
                IsEnabled = false,
                UseInterpolation = true,
                DrawVerticalLine = true,
                ReceiveHandledEvents = true,
                ShowAxisLabels = true,
                ShowTooltipOn = ShowTooltipOptions.Always
            };
            _modifiersInDevMode.ChildModifiers.Add(rollover);

            // CursorModifier 
            var cursorMod = new CursorModifier
            {
                IsEnabled = false,
                ShowTooltipOn = ShowTooltipOptions.MouseOver,
                ReceiveHandledEvents = true,
                ShowAxisLabels = false,
                ShowTooltip = true
            };
            _modifiersInDevMode.ChildModifiers.Add(cursorMod);

            // TooltipModifier
            var toolTipMod = new TooltipModifier
            {
                ReceiveHandledEvents = true,
                IsEnabled = false,
                UseInterpolation = true
            };
            _modifiersInDevMode.ChildModifiers.Add(toolTipMod);

            // AnimationsModifier
            var animationsModifier = new SeriesAnimationCustomModifier();

            _modifiersInDevMode.ChildModifiers.Add(animationsModifier);

            if (!isPolar)
            {
                // YAxisDragModifier
                var yAxisDrag = new YAxisDragModifier();
                _modifiersInDevMode.ChildModifiers.Add(yAxisDrag);

                // XAxisDragModifier
                var xAxisDrag = new XAxisDragModifier();
                _modifiersInDevMode.ChildModifiers.Add(xAxisDrag);
            }

            if (!(scs.ChartModifier is ModifierGroup exampleModifiers))
            {
                exampleModifiers = new ModifierGroup();

                if (scs.ChartModifier != null)
                {
                    exampleModifiers.ChildModifiers.Add(scs.ChartModifier);
                }
            }

            var devMods = new ModifierGroup();
            var userMods = new ModifierGroup();

            foreach (var devMod in _modifiersInDevMode.ChildModifiers)
            { 
                var devModName = devMod.ModifierName;

                if (devMod is CustomAnnotationCreationModifier)
                    devModName = "AnnotationCreationModifier";

                if (!(exampleModifiers.ChildModifiers.Any(x => x.ModifierName == devModName)))
                {
                    devMods.ChildModifiers.Add(devMod);
                }
                else
                {
                    if (exampleModifiers.ChildModifiers.Count(x => x.ModifierName == devModName) == 1)
                    {
                        var exampleMod = exampleModifiers.ChildModifiers.Single(x => x.ModifierName == devModName);

                        if (!GetAppearceInToolbar((ChartModifierBase)exampleMod))
                            continue;

                        devMods.ChildModifiers.Add(exampleMod);
                    }
                    else 
                    {
                        foreach (var exampleMod in exampleModifiers.ChildModifiers.Where(x => x.ModifierName == devModName && GetAppearceInToolbar((ChartModifierBase)x)))
                        {
                            devMods.ChildModifiers.Add(exampleMod);
                        }
                    }
                }
            }

            foreach (var inAllMod in _modifiersInAllMode.ChildModifiers)
            {
                var modName = inAllMod.ModifierName;

                if (!(exampleModifiers.ChildModifiers.Any(x => x.ModifierName == modName)))
                {
                    userMods.ChildModifiers.Add(inAllMod);
                }
                else
                {
                    if (exampleModifiers.ChildModifiers.Count(x => x.ModifierName == modName) == 1)
                    {
                        var exampleMod = exampleModifiers.ChildModifiers.Single(x => x.ModifierName == modName);

                        if (!GetAppearceInToolbar((ChartModifierBase)exampleMod))
                            continue;

                        userMods.ChildModifiers.Add(exampleMod);
                    }
                    else
                    {
                        foreach (var exampleMod in exampleModifiers.ChildModifiers.Where(x => x.ModifierName == modName && GetAppearceInToolbar((ChartModifierBase)x)))
                        {
                            userMods.ChildModifiers.Add(exampleMod);
                        }
                    }
                }
            }

            foreach (var exampleMod in exampleModifiers.ChildModifiers.Where(x => GetAppearceInToolbar((ChartModifierBase)x)))
            {
                if (HasToAddUserModifierToModifierGroup(exampleMod, devMods))
                {
                    devMods.ChildModifiers.Add(exampleMod);
                }

                if (HasToAddUserModifierToModifierGroup(exampleMod, userMods))
                {
                    userMods.ChildModifiers.Add(exampleMod);
                }
            }

            _modifiersInDevMode = devMods;
            _modifiersInUserMode = userMods;

            // Set modifiers to the chart
            scs.ChartModifier = IsDeveloperMode ? _modifiersInDevMode : _modifiersInUserMode;

            var wrappers = WrapModifiers(toolbar.IsDeveloperMode
                ? toolbar._modifiersInDevMode.ChildModifiers
                : toolbar._modifiersInUserMode.ChildModifiers);

            // Set modifiers to the ItemSource for ItemsControl
            listMod.AddRange(wrappers);

            if (listMod.Any(x => x.Modifier.ModifierName == "AnnotationCreationModifier" || x.Modifier is VerticalSliceModifier))
            {
                listMod.Remove(listMod.FirstOrDefault(x => x.Modifier.ModifierName == "AnnotationCreationModifier"));
                listMod.Remove(listMod.FirstOrDefault(x => x.Modifier is VerticalSliceModifier));
            }

            ModifiersSource = listMod;
        }

19 Source : DataManager.cs
with MIT License
from ABTSoftware

public DoubleSeries GetAcousticChannel(int channelNumber)
        {
            if (channelNumber > 7)
                throw new InvalidOperationException("Only channels 0-7 allowed");

            if (_acousticPlotData.Count != 0)
            {
                return _acousticPlotData[channelNumber];
            }

            // e.g. resource format: SciChart.Examples.ExternalDependencies.Resources.Data.EURUSD_Daily.csv 
            var csvResource = string.Format("{0}.{1}", ResourceDirectory, "AcousticPlots.csv.gz");

            var ch0 = new DoubleSeries(100000);
            var ch1 = new DoubleSeries(100000);
            var ch2 = new DoubleSeries(100000);
            var ch3 = new DoubleSeries(100000);
            var ch4 = new DoubleSeries(100000);
            var ch5 = new DoubleSeries(100000);
            var ch6 = new DoubleSeries(100000);
            var ch7 = new DoubleSeries(100000);

            var replacedembly = typeof(DataManager).replacedembly;
            using (var stream = replacedembly.GetManifestResourceStream(csvResource))
            using (var gz = new GZipStream(stream, CompressionMode.Decompress))
            using (var streamReader = new StreamReader(gz))
            {
                string line = streamReader.ReadLine();
                line = streamReader.ReadLine();
                while (line != null)
                {
                    // Line Format: 
                    // Date, Open, High, Low, Close, Volume 
                    // 2007.07.02 03:30, 1.35310, 1.35310, 1.35280, 1.35310, 12 
                    var tokens = line.Split(',');
                    double x = double.Parse(tokens[0], NumberFormatInfo.InvariantInfo);
                    double y0 = double.Parse(tokens[1], NumberFormatInfo.InvariantInfo);
                    double y1 = double.Parse(tokens[2], NumberFormatInfo.InvariantInfo);
                    double y2 = double.Parse(tokens[3], NumberFormatInfo.InvariantInfo);
                    double y3 = double.Parse(tokens[4], NumberFormatInfo.InvariantInfo);
                    double y4 = double.Parse(tokens[5], NumberFormatInfo.InvariantInfo);
                    double y5 = double.Parse(tokens[6], NumberFormatInfo.InvariantInfo);
                    double y6 = double.Parse(tokens[7], NumberFormatInfo.InvariantInfo);
                    double y7 = double.Parse(tokens[8], NumberFormatInfo.InvariantInfo);

                    ch0.Add(new XYPoint() { X = x, Y = y0 });
                    ch1.Add(new XYPoint() { X = x, Y = y1 });
                    ch2.Add(new XYPoint() { X = x, Y = y2 });
                    ch3.Add(new XYPoint() { X = x, Y = y3 });
                    ch4.Add(new XYPoint() { X = x, Y = y4 });
                    ch5.Add(new XYPoint() { X = x, Y = y5 });
                    ch6.Add(new XYPoint() { X = x, Y = y6 });
                    ch7.Add(new XYPoint() { X = x, Y = y7 });

                    line = streamReader.ReadLine();
                }
            }

            _acousticPlotData.AddRange(new[] { ch0, ch1, ch2, ch3, ch4, ch5, ch6, ch7});

            return _acousticPlotData[channelNumber];
        }

19 Source : AscReader.cs
with MIT License
from ABTSoftware

public static async Task<AscData> ReadFileToAscData(
            string filename, Func<float, Color> colorMapFunction, Action<int> reportProgress = null)
        {
            AscData result = new AscData()
            {
                XValues = new List<float>(),
                YValues = new List<float>(),
                ZValues = new List<float>(),
                ColorValues = new List<Color>(),
            };

            await Task.Run(() =>
            {
                using (var file = File.OpenText(filename))
                {
                    // Load the ASC file format 
                    result.NumberColumns = ReadInt(file, "ncols");
                    result.NumberRows = ReadInt(file, "nrows");
                    result.XllCorner = ReadInt(file, "xllcorner");
                    result.YllCorner = ReadInt(file, "yllcorner");
                    result.CellSize = ReadInt(file, "cellsize");
                    result.NoDataValue = ReadInt(file, "NODATA_value");

                    // Generate X-values based off cell position 
                    float[] xValuesRow = Enumerable.Range(0, result.NumberColumns).Select(x => (float)x * result.CellSize).ToArray();

                    for (int i = 0; i < result.NumberRows; i++)
                    {
                        // Read heights from the ASC file and generate Z-cell values
                        float[] heightValuesRow = ReadFloats(file, " ", result.NoDataValue);
                        float[] zValuesRow = Enumerable.Repeat(0 + i * result.CellSize, result.NumberRows).Select(x => (float)x).ToArray();

                        result.XValues.AddRange(xValuesRow);
                        result.YValues.AddRange(heightValuesRow);
                        result.ZValues.AddRange(zValuesRow);

                        if (colorMapFunction != null)
                        {
                            // Optional color-mapping of points based on height 
                            Color[] colorValuesRow = heightValuesRow
                                .Select(colorMapFunction)
                                .ToArray();
                            result.ColorValues.AddRange(colorValuesRow);
                        }

                        // Optional report loading progress 0-100%
                        reportProgress?.Invoke((int)(100.0f * i / result.NumberRows));
                    }
                }
            });

            return result;
        }

19 Source : DataBuilder.cs
with MIT License
from abvogel

private List<Enreplacedy> GetStubRecords(string logicalName)
        {
            List<Enreplacedy> stubRecords = new List<Enreplacedy>();

            // Add record stub to support internal lookups where the record doesn't exist
            List<AttributeMetadata> lookups = this.GetFieldsThatAreEnreplacedyReference(logicalName);
                stubRecords.AddRange(this.GetStubRecordsForInternalLookups(logicalName, lookups));

            // Add record stub to support m2m relationships
            if (this._Enreplacedies[logicalName].RelatedEnreplacedies.Count > 0)
                stubRecords.AddRange(this.GetStubRecordsForM2MRelationships(logicalName));

            return stubRecords;
        }

19 Source : BuilderEntityMetadata.cs
with MIT License
from abvogel

public void AppendM2MDataToEnreplacedy(String relationshipName, Dictionary<Guid, List<Guid>> relatedEnreplacedies)
        {
            if (!RelatedEnreplacedies.ContainsKey(relationshipName))
                this.RelatedEnreplacedies[relationshipName] = new Dictionary<Guid, List<Guid>>();

            foreach (var id in relatedEnreplacedies.Keys)
            {
                if (!RelatedEnreplacedies[relationshipName].ContainsKey(id))
                    this.RelatedEnreplacedies[relationshipName][id] = new List<Guid>();

                this.RelatedEnreplacedies[relationshipName][id].AddRange(relatedEnreplacedies[id]);
                this.RelatedEnreplacedies[relationshipName][id] = RelatedEnreplacedies[relationshipName][id].Distinct().ToList();
            }
        }

19 Source : SupportMethods.cs
with MIT License
from abvogel

public static List<Enreplacedy> RetrieveAllRecords(IOrganizationService service, string fetch)
        {
            int pageNumber = 1;
            bool moreRecords = false;
            List<Enreplacedy> Enreplacedies = new List<Enreplacedy>();
            var fetchXmlDoc = CreateXml(fetch);

            do
            {
                var retrievedRecords = service.RetrieveMultiple(new Sdk.Query.FetchExpression(fetchXmlDoc.InnerXml));
                moreRecords = retrievedRecords.MoreRecords;
                if (retrievedRecords.Enreplacedies.Count >= 0)
                    Enreplacedies.AddRange(retrievedRecords.Enreplacedies);

                if (moreRecords)
                {
                    fetchXmlDoc = UpdatePagingCookie(fetchXmlDoc, System.Security.SecurityElement.Escape(retrievedRecords.PagingCookie), ++pageNumber);
                }

            } while (moreRecords);
            return Enreplacedies;
        }

19 Source : ACBrCEP.cs
with MIT License
from ACBrNet

public int BuscarPorCEP(string cep)
		{
			Guard.Against<ArgumentException>(cep.IsEmpty(), "CEP n�o pode ser vazio.");
			Guard.Against<ArgumentException>(!cep.IsCep(), "CEP inv�lido.");

			Resultados.Clear();

			var provider = GetProvider();
			var results = provider.BuscarPorCEP(cep);
			Resultados.AddRange(results);

			OnBuscaEfetuada.Raise(this, EventArgs.Empty);
			return Resultados.Count;
		}

19 Source : BaiduCloudUser.cs
with MIT License
from Accelerider

public override Task<ILazyTreeNode<INetDiskFile>> GetFileRootAsync()
        {
            var tree = new LazyTreeNode<INetDiskFile>(new BaiduCloudFile())
            {
                ChildrenProvider = async parent =>
                {
                    var result = new List<BaiduCloudFile>();
                    var page = 1;
                    do
                    {
                        var files = await Api.GetFileListAsync(Token, parent.Path, page);
                        if (files.FileList.Count == 0)
                            break;
                        result.AddRange(files.FileList);
                        page++;
                    } while (true);
                    //result.ForEach(v => v.Owner = this);
                    return result;
                }
            };
            return Task.FromResult((ILazyTreeNode<INetDiskFile>)tree);
        }

19 Source : OnedriveUser.cs
with MIT License
from Accelerider

public override Task<ILazyTreeNode<INetDiskFile>> GetFileRootAsync()
        {
            var tree = new LazyTreeNode<INetDiskFile>(new OneDriveFile() /*{ Owner = this }*/)
            {
                ChildrenProvider = async parent =>
                {
                    var result = new List<OneDriveFile>();
                    if (parent.Path == "/")
                    {
                        result.AddRange((await Api.GetRootFilesAsync()).FileList);
                    }
                    else
                    {
                        var tmp = await Api.GetFilesAsync(parent.Path);
                        result.AddRange(tmp.FileList);
                        while (!string.IsNullOrEmpty(tmp.NextPage))
                        {
                            using (var client = new HttpClient()
                            {
                                DefaultRequestHeaders =
                                {
                                    Authorization = new AuthenticationHeaderValue("Bearer",AccessToken)
                                }
                            })
                            {
                                tmp = JsonConvert.DeserializeObject<OneDriveListFileResult>(await client.GetStringAsync(tmp.NextPage));
                                result.AddRange(tmp.FileList);
                            }
                        }
                    }

                    //result.ForEach(v => v.Owner = this);
                    return result;
                }
            };
            return Task.FromResult((ILazyTreeNode<INetDiskFile>)tree);
        }

19 Source : GDLELoader.cs
with GNU Affero General Public License v3.0
from ACEmulator

public static bool TryLoadWieldedTreasureTableConverted(string file, out List<TreasureWielded> results)
        {
            try
            {
                var fileText = File.ReadAllText(file);

                var gdleModel = JsonConvert.DeserializeObject<List<Models.WieldedTreasureTable>>(fileText);

                results = new List<TreasureWielded>();

                foreach (var value in gdleModel)
                {
                    if (GDLEConverter.TryConvert(value, out var result))
                        results.AddRange(result);
                }

                return true;

            }
            catch
            {
                results = null;
                return false;
            }
        }

19 Source : ACBrCEP.cs
with MIT License
from ACBrNet

public int BuscarPorLogradouro(ConsultaUF uf, string municipio, string logradouro, string tipoLogradouro = "", string bairro = "")
		{
			Guard.Against<ArgumentException>(municipio.IsEmpty(), "Municipio n�o pode ser vazio.");
			Guard.Against<ArgumentException>(logradouro.IsEmpty(), "Logradouro n�o pode ser vazio.");

			Resultados.Clear();

			var provider = GetProvider();
			var results = provider.BuscarPorLogradouro(uf, municipio, logradouro, tipoLogradouro, bairro);
			Resultados.AddRange(results);

			OnBuscaEfetuada.Raise(this, EventArgs.Empty);
			return Resultados.Count;
		}

See More Examples