Inheritance: IDisposable
Beispiel #1
0
        protected override Row CreateRowFromReader(IDataReader reader)
        {
            GetSchemaTable(reader);
            Row r = new Row();
            for (int i = 0; i < reader.FieldCount; i++)
            {
                Type fType = reader.GetFieldType(i);
                if (fType == typeof(System.Decimal))
                {
                    object o = reader.GetValue(i);
                    if (o != DBNull.Value)
                    {
                        string d = reader.GetValue(i).ToString();
                        //short scale = (short)SchemaTable.Rows[i].[4];
                        short scale = (short)SchemaTable.Rows[i].Field<short>("NumericPrecision");
                        decimal res = reader.GetDecimal(i);
                        if (scale > 0)
                            res = res / (int)(Math.Pow(10.0, scale));
                        r[reader.GetName(i)] = res;
                    }
                    else
                        r[reader.GetName(i)] = DBNull.Value;
                }
                else
                {
                    r[reader.GetName(i)] = reader.GetValue(i);
                }
            }

            return r;
        }
 protected override Row CreateRowFromReader(IDataReader reader) {
     var row = new Row();
     foreach (var field in _fields) {
         row[field.Alias] = reader[field.Name];
     }
     return row;
 }
Beispiel #3
0
 public CRUDSubscriptionEvent(EventType type, Schema schema, Row row, DataTimeStamp version)
 {
     Type = type;
       Schema = schema;
       Row = row;
       Version = version;
 }
        /// <summary>
        /// Main processing script.
        /// </summary>
        /// <param name="input">The input row.</param>
        /// <param name="outputRow">The output row.</param>
        /// <param name="args">The arguments.</param>
        /// <returns>The IEnumerable output row.</returns>
        public override IEnumerable<Row> Process(RowSet input, Row outputRow, string[] args)
        {
            string frameShift = args[0];
            string frameLength = args[1];

            Directory.CreateDirectory("relatedFeatures");

            foreach (var row in input.Rows)
            {
                outputRow["WaveID"].Set(row["WaveID"].String);
                outputRow["WaveBinary"].Set(row["WaveBinary"].Binary);
                outputRow["WaveAlignments"].Set(row["WaveAlignments"].String);
                outputRow["RawF0"].Set(row["RawF0"].String);
                outputRow["LPCC"].Set(row["LPCC"].Binary);
                outputRow["OF0"].Set(row["OF0"].String);
                outputRow["LSP"].Set(row["LSP"].Binary);
                outputRow["Pow"].Set(row["Pow"].String);
                outputRow["MBE"].Set(row["MBE"].String);
                outputRow["NCCF"].Set(row["NCCF"].String);

                string waveId = row["WaveID"].String;
                string wave = JobBase.GenerateLocalFile(waveId, row["WaveBinary"].Binary, FileExtensions.Waveform);

                string relatedFeatureFile = Path.Combine("relatedFeatures", waveId + "." + FileExtensions.Text);
                string[] argument = { wave, relatedFeatureFile, frameShift, frameLength };
                F0ExtractorCOSMOS.ExtractRelatedFeaturesOneFile(argument, null);

                outputRow["RF"].Set(File.ReadAllText(relatedFeatureFile));
                yield return outputRow;
            }
        }
 private void AddRow(string name, int price)
 {
     Row row = new Row();
     row["name"] = name;
     row["price"] = price;
     rows.Add(row);
 }
Beispiel #6
0
        private void CreateRow(IEnumerable<Cell> row, Row currentRow)
        {
            int columnOrdinal = 0;

            foreach (var cell in row)
            {
                if (cell.ColumnSpan > 1)
                {
                    int rangeStartColumn = columnOrdinal;

                    for (int i = 0; i < cell.ColumnSpan; i++)
                    {
                        NPOI.SS.UserModel.Cell current = CreateCell(cell, currentRow, columnOrdinal);
                        if (i == 0) current.SetCellValue(cell.Value);
                        columnOrdinal++;
                    }

                    var cra = new CellRangeAddress(currentRow.RowNum, currentRow.RowNum, rangeStartColumn,
                                                   rangeStartColumn + (cell.ColumnSpan - 1));
                    _sheet.AddMergedRegion(cra);
                }
                else
                {
                    CreateCell(cell, currentRow, columnOrdinal).SetCellValue(cell.Value);
                    columnOrdinal++;
                }
            }
        }
Beispiel #7
0
        public static Table Parse(IRestResponse response)
        {
            Table table = new Table();
            StringReader reader = new StringReader(response.Content);
            string readLine = reader.ReadLine();

            if (readLine != null)
            {
                string[] collection = readLine.Split(Separator);
                foreach (string column in collection)
                {
                    table.Columns.Add(column.TrimStart('"').TrimEnd('"'));
                }
            }

            string line = reader.ReadLine();

            while (!string.IsNullOrEmpty(line))
            {
                Row row = new Row(line);
                table.Rows.Add(row);
                line = reader.ReadLine();
            }

            return table;
        }
        private ExpandoObject ParseFromRow(Row row, ISheetDefinition sheetDefinition)
        {
            IDictionary<string, object> expando = new ExpandoObject();
            var cells = row.Elements<Cell>().ToList();
            var colDefs = sheetDefinition.ColumnDefinitions.ToList();
            var count = Math.Max(cells.Count, colDefs.Count);
            for (var index = 0; index < count; index++)
            {
                var colDef = index < colDefs.Count ? colDefs[index] : null;
                var cell = index < cells.Count ? cells[index] : null;
                string propName;
                object propValue;
                if (cell != null)
                {
                    propName = cell.GetMdsolAttribute("propertyName");
                    propValue = _converterManager.GetCSharpValue(cell);
                }
                else if (colDef != null)
                {
                    propName = colDef.PropertyName;
                    propValue = null;
                }
                else
                {
                    throw new NotSupportedException("Cell and CellDefinition are both null");
                }

                expando.Add(propName, propValue);
            }
            return (ExpandoObject) expando;
        }
Beispiel #9
0
        private NPOI.SS.UserModel.Cell CreateCell(Cell cell, Row currentRow, int columnOrdinal)
        {
            var nCell = currentRow.CreateCell(columnOrdinal, CellType.STRING);
            nCell.CellStyle = GetCellStyle(cell);

            return nCell;
        }
Beispiel #10
0
        /// <summary>
        /// Loads an empty (new) row from the database into the specified Table.
        /// <param name="table">The Table object to populate with empty data.</param>
        /// </summary>
        public static void GetEmptyData(Table table)
        {
            Row r = new Row(table);

            for (int i = 0; i < table.Columns.Count; i++)
            {
                RowCell c = new RowCell(table.Columns[i].ColumnId, r) {Row = r};
                if (table.Columns[i].ColumnType == ColumnType.ColumnTemplate)
                    c.Value = ((ColumnTemplate)table.Columns[i]).CreateCellControls;
                else if (c.Value == null && table.Columns[i].DefaultValue != null)
                    c.Value = table.Columns[i].DefaultValue;
                r.Cells.Add(c);
            }

            if (table.m_Grid.MasterWebGrid == null)
            {
                table.Rows.Add(r);
                return;
            }
            List<Column> masterWebGridPrimarykeys = table.m_Grid.MasterWebGrid.MasterTable.Columns.Primarykeys;

            int index = 0;

            while (index < masterWebGridPrimarykeys.Count)
            {
                string columnname = masterWebGridPrimarykeys[index].ColumnId;
                if (r.Columns.GetIndex(columnname) > -1)
                    r[columnname].Value = table.m_Grid.MasterWebGrid.MasterTable.Rows[0][columnname].Value;
                index++;
            }
            table.Rows.Add(r);
        }
        /// <summary>
        /// Main processing script.
        /// </summary>
        /// <param name="input">The input row.</param>
        /// <param name="outputRow">The output row.</param>
        /// <param name="args">The arguments.</param>
        /// <returns>The IEnumerable output row.</returns>
        public override IEnumerable<Row> Process(RowSet input, Row outputRow, string[] args)
        {
            string f0Dir = "f0";
            string expandDir = "expand";
            string svmDir = "svm";
            Directory.CreateDirectory(f0Dir);
            Directory.CreateDirectory(expandDir);
            Directory.CreateDirectory(svmDir);

            foreach (var row in input.Rows)
            {
                outputRow["WaveID"].Set(row["WaveID"].String);
                outputRow["WaveBinary"].Set(row["WaveBinary"].Binary);
                outputRow["WaveAlignments"].Set(row["WaveAlignments"].String);
                outputRow["RawF0"].Set(row["RawF0"].String);
                outputRow["LPCC"].Set(row["LPCC"].Binary);
                outputRow["OF0"].Set(row["OF0"].String);
                outputRow["LSP"].Set(row["LSP"].Binary);
                outputRow["Pow"].Set(row["Pow"].String);
                outputRow["MBE"].Set(row["MBE"].String);

                string waveId = row["WaveID"].String;
                string f0File = JobBase.GenerateLocalFile(waveId, row["RawF0"].String, FileExtensions.F0File, true, f0Dir);
                string expandFeatureFile = JobBase.GenerateLocalFile(waveId, row["EXP"].String, FileExtensions.Text, false, expandDir);
                string svmFile = Path.Combine(svmDir, waveId + "." + FileExtensions.Text);

                string[] argument = { f0File, expandFeatureFile, svmFile };
                F0ExtractorCOSMOS.FormatFeaturesOneFile(argument, null);

                outputRow["SVM"].Set(File.ReadAllText(svmFile));
                yield return outputRow;
            }
        }
 public SplitElement(Row row)
     : base(UITableViewCellStyle.Default, "splitelement")
 {
     Value = row;
     BackgroundColor = UIColor.White;
     _font = Font.WithSize(Font.PointSize * Element.FontSizeRatio);
 }
        /// <summary>
        /// Main processing script.
        /// </summary>
        /// <param name="input">The input row.</param>
        /// <param name="outputRow">The output row.</param>
        /// <param name="args">The arguments.</param>
        /// <returns>The IEnumerable output row.</returns>
        public override IEnumerable<Row> Process(RowSet input, Row outputRow, string[] args)
        {
            string uvDir = "uv";
            string scaledSVMDir = "scaledSVM";
            Directory.CreateDirectory(uvDir);
            Directory.CreateDirectory(scaledSVMDir);

            foreach (var row in input.Rows)
            {
                outputRow["WaveID"].Set(row["WaveID"].String);
                outputRow["WaveBinary"].Set(row["WaveBinary"].Binary);
                outputRow["WaveAlignments"].Set(row["WaveAlignments"].String);
                outputRow["RawF0"].Set(row["RawF0"].String);
                outputRow["LPCC"].Set(row["LPCC"].Binary);
                outputRow["OF0"].Set(row["OF0"].String);
                outputRow["LSP"].Set(row["LSP"].Binary);
                outputRow["Pow"].Set(row["Pow"].String);
                outputRow["MBE"].Set(row["MBE"].String);

                string waveId = row["WaveID"].String;
                string scaledSVMFile = JobBase.GenerateLocalFile(waveId, row["SSVM"].String, FileExtensions.Text, false, scaledSVMDir);
                string uvFile = Path.Combine(uvDir, waveId + "." + FileExtensions.Text);
                string argument = Helper.NeutralFormat(" \"{0}\" \"{1}\" \"{2}\"", scaledSVMFile, Path.GetFileName(this.Job.ReplaceVariable["UVMODELFILE"]), uvFile);

                CommandLine.RunCommand(Path.GetFileName(this.Job.ReplaceVariable["SVMPREDICTTOOL"]),
                    argument, "./");
                outputRow["UV"].Set(JobBase.GetTextFile(uvFile));
                yield return outputRow;
            }
        }
        protected override void Accumulate(Row row, Row aggregate) {
            if (aggregate.ContainsKey(_firstKey)) return;

            foreach (var key in _keys) {
                aggregate[key] = row[key];
            }
        }
Beispiel #15
0
 public Row Transform(Row row) {
     foreach (var date in _dates.Where(date => (DateTime)row[date] < _minDate)) {
         row[date] = _minDate;
     }
     Increment();
     return row;
 }
 public override void Test(Row row, Errors errors)
 {
     AssertSum(row, "1YR_PS_GRAD_DSAG_PTS_EARN", new[] { "1YR_PS_GRAD_ELL_PTS_EARN", "1YR_PS_GRAD_IEP_PTS_EARN", "1YR_PS_GRAD_MIN_PTS_EARN", "1YR_PS_GRAD_FRL_PTS_EARN" }, errors);
     AssertSum(row, "1YR_PS_GRAD_DSAG_PTS_ELIG", new[] { "1YR_PS_GRAD_ELL_PTS_ELIG", "1YR_PS_GRAD_IEP_PTS_ELIG", "1YR_PS_GRAD_MIN_PTS_ELIG", "1YR_PS_GRAD_FRL_PTS_ELIG" }, errors);
     AssertSum(row, "3YR_PS_GRAD_DSAG_PTS_EARN", new[] { "3YR_PS_GRAD_ELL_PTS_EARN", "3YR_PS_GRAD_IEP_PTS_EARN", "3YR_PS_GRAD_MIN_PTS_EARN", "3YR_PS_GRAD_FRL_PTS_EARN" }, errors);
     AssertSum(row, "3YR_PS_GRAD_DSAG_PTS_ELIG", new[] { "3YR_PS_GRAD_ELL_PTS_ELIG", "3YR_PS_GRAD_IEP_PTS_ELIG", "3YR_PS_GRAD_MIN_PTS_ELIG", "3YR_PS_GRAD_FRL_PTS_ELIG" }, errors);
 }
Beispiel #17
0
        private void PutAdress(Aspose.Pdf.Generator.Pdf pdf, PassengerInfo passengerInfo)
        {
            //create table to add address of the customer
            Table adressTable = new Table();
            adressTable.IsFirstParagraph = true;
            adressTable.ColumnWidths = "60 180 60 180";
            adressTable.DefaultCellTextInfo.FontSize = 10;
            adressTable.DefaultCellTextInfo.LineSpacing = 3;
            adressTable.DefaultCellPadding.Bottom = 3;
            //add this table in the first section/page
            Section section = pdf.Sections[0];
            section.Paragraphs.Add(adressTable);
            //add a new row in the table
            Row row1AdressTable = new Row(adressTable);
            adressTable.Rows.Add(row1AdressTable);
            //add cells and text
            Aspose.Pdf.Generator.TextInfo tf1 = new Aspose.Pdf.Generator.TextInfo();
            tf1.Color = new Aspose.Pdf.Generator.Color(111, 146, 188);
            tf1.FontName = "Helvetica-Bold";

            row1AdressTable.Cells.Add("Bill To:", tf1);
            row1AdressTable.Cells.Add(passengerInfo.Name + "#$NL" +
                passengerInfo.Address + "#$NL" + passengerInfo.Email + "#$NL" +
                passengerInfo.PhoneNumber);

        }
 protected override Row MergeRows(Row leftRow, Row rightRow)
 {
     Row row = new Row();
     row.Copy(leftRow);
     row["person_id"] = rightRow["id"];
     return row;
 }
Beispiel #19
0
 public static void CompareCellData(Row row, List<Cell> expected)
 {
     for (int i = 0; i < expected.Count; i++)
     {
         Assert.AreEqual(expected[i].Value, row.GetCell(i).StringCellValue);
     }
 }
        public Row[] Select()
        {
            FbTransaction transaction = connection.BeginTransaction();

            FbCommand cmd = new FbCommand(selectCommand, connection, transaction);

            List<Row> rows = new List<Row>();
            Row nr;

            using (FbDataReader dr = cmd.ExecuteReader())
            {
                while (dr.Read())
                {
                    nr = new Row();
                    nr.ID = dr.GetInt32(0);
                    nr.Name = dr.GetString(1);
                    nr.Description = dr.GetString(2);
                    using (System.IO.Stream stream = dr.GetStream(3))
                    {
                        using (System.IO.MemoryStream mStream = new System.IO.MemoryStream())
                        {
                            stream.CopyTo(mStream);
                            nr.Image = mStream.ToArray();
                        }
                    }

                    rows.Add(nr);
                }
            }

            transaction.Commit();

            return rows.ToArray();
        }
Beispiel #21
0
 public static void PropagateOnNext(this IEnumerable<IObserver<Row>> observers, Row row)
 {
     foreach (var observer in observers)
     {
         observer.OnNext(row);
     }
 }
Beispiel #22
0
 protected void AddUser(string name, string email)
 {
     Row row = new Row();
     row["name"] = name;
     row["email"] = email;
     left.Add(row);
 }
Beispiel #23
0
        public static void GenerateReport(List<DataObject> objects)
        {
            SheetData data = new SheetData();

              //add column names to the first row
              Row header = new Row();
              header.RowIndex = (UInt32)1;

              foreach (DataObject obj in objects)
              {
            Cell headerCell = createTextCell(objects.IndexOf(obj) + 1, 1, obj.Name);
            header.AppendChild(headerCell);
              }
              data.AppendChild(header);
              SpreadsheetDocument doc = CreateDoc(data);
              /*using (SpreadsheetDocument spreadsheet = SpreadsheetDocument.Open(fileName, true))
              {
            WorkbookPart workbook = spreadsheet.WorkbookPart;
            //create a reference to Sheet1
            WorksheetPart worksheet = workbook.WorksheetParts.Last();

            ///loop through each data row  DataRow contentRow;
            for (int i = 0; i < table.Rows.Count; i++)
            {
              contentRow = table.Rows[i];
              data.AppendChild(createContentRow(contentRow, i + 2));
            }
               }  */
        }
Beispiel #24
0
 public OpenXLRow(WorkbookPart wbPart, WorksheetPart wsPart, List<string> columns, Row xRow)
 {
     this.WbPart = wbPart;
     this.WsPart = wsPart;
     this.Columns = columns;
     this._cells = GetCells(xRow);
 }
Beispiel #25
0
        public override Row CreateRowFromReader(IDataReader reader)
        {
            GetSchemaTable(reader);
            Row r = new Row();
            for (int i = 0; i < reader.FieldCount; i++)
            {
                Type fType = reader.GetFieldType(i);
                if (fType == typeof(System.Decimal))
                {
                    GetDecimal(reader, r, i);
                }
                else if (fType == typeof(System.DateTime))
                {
                    object o = reader.GetValue(i);
                    if (o != DBNull.Value)
                    {
                        DateTime dtime = reader.GetDateTime(i);
                        if (dtime < MinDateTime)
                        {
                            o = NullDateTime.Add(new TimeSpan(dtime.Hour, dtime.Minute, dtime.Second));
                        }
                        r[reader.GetName(i)] = o;
                    }
                }
                else
                {
                    r[reader.GetName(i)] = reader.GetValue(i);
                }
            }

            return r;
        }
 void AssertSubtract(Row row, string excdColumn, string panColumn, string pctnColumn, string nexcdColumn, Errors errors)
 {
     if (row[excdColumn].ToLower() == "yes")
     {
         AssertSubtract(row, panColumn, pctnColumn, nexcdColumn, errors);
     }
 }
Beispiel #27
0
        /// <summary>
        /// Main processing script.
        /// </summary>
        /// <param name="input">The input row.</param>
        /// <param name="outputRow">The output row.</param>
        /// <param name="args">The arguments.</param>
        /// <returns>The IEnumerable output row.</returns>
        public override IEnumerable<Row> Process(RowSet input, Row outputRow, string[] args)
        {
            float minF0Value = float.Parse(args[0]);
            float maxF0Value = float.Parse(args[1]);
            string uvDir = "uv";
            string fZeroDir = "f0";
            string smoothedFZeroDir = "smoothedF0";

            Directory.CreateDirectory(uvDir);
            Directory.CreateDirectory(fZeroDir);
            Directory.CreateDirectory(smoothedFZeroDir);

            foreach (var row in input.Rows)
            {
                outputRow["WaveID"].Set(row["WaveID"].String);
                outputRow["WaveBinary"].Set(row["WaveBinary"].Binary);
                outputRow["WaveAlignments"].Set(row["WaveAlignments"].String);
                outputRow["RawF0"].Set(row["RawF0"].String);
                outputRow["LPCC"].Set(row["LPCC"].Binary);
                outputRow["OF0"].Set(row["OF0"].String);
                outputRow["LSP"].Set(row["LSP"].Binary);
                outputRow["Pow"].Set(row["Pow"].String);
                outputRow["MBE"].Set(row["MBE"].String);

                string waveId = row["WaveID"].String;
                string f0File = JobBase.GenerateLocalFile(waveId, row["RawF0"].String, FileExtensions.F0File, true, fZeroDir);
                string uvFile = JobBase.GenerateLocalFile(waveId, row["UV"].String, FileExtensions.Text, true, uvDir);
                string smoothedF0File = Path.Combine(smoothedFZeroDir, waveId + "." + FileExtensions.F0File);
                string[] argument = { f0File, uvFile, smoothedF0File, minF0Value.ToString(), maxF0Value.ToString() };
                F0ExtractorCOSMOS.SmoothOneF0File(argument, null);
                outputRow["SF0"].Set(JobBase.GetTextFile(smoothedF0File));
                yield return outputRow;
            }
        }
Beispiel #28
0
 protected void AddPerson(int id, string email)
 {
     Row row = new Row();
     row["id"] = id;
     row["email"] = email;
     right.Add(row);
 }
Beispiel #29
0
    private List<int> GetPathSplitIndex(Row dialogStuff)
    {
        List<int> values = new List<int> ();
        int dummyVal = 0;
        int barIndex = 0;
        int startIndex = 0;

        foreach (char c in dialogStuff.Conversation_Path_Chain) {
            if (c.Equals ('|')) {
                if (int.TryParse (dialogStuff.Conversation_Path_Chain.Substring (startIndex, barIndex), out dummyVal)){
                    values.Add(int.Parse (dialogStuff.Conversation_Path_Chain.Substring (startIndex, barIndex))); //still need to do somthing with the value that is after bar
                    startIndex = barIndex + 1;
                }
            }

            barIndex++;
        }

        //for the last path or for a singlton
        if (int.TryParse (dialogStuff.Conversation_Path_Chain.Substring (startIndex), out dummyVal)) {
            values.Add(int.Parse (dialogStuff.Conversation_Path_Chain.Substring (startIndex))); //still need to do somthing with the value that is after bar
        }

        return values;
    }
Beispiel #30
0
 public Row Transform(Row row) {
     foreach (var field in _fields.Where(f => row[f] == null)) {
         row[field] = _getDefaultFor[_index(field)]();
     }
     Increment();
     return row;
 }
Beispiel #31
0
        private Row readRow(MemoryStream ms)
        {
            Row row = new Row(FieldList);

            for (int fieldIdx = 0; fieldIdx < row.Count; fieldIdx++)
            {
                LuaField currentField = GetField(fieldIdx);

                switch (currentField.Type)
                {
                case "short":
                    row[fieldIdx] = BitConverter.ToInt16(readStream(ms, currentField.Length), 0);
                    break;

                case "ushort":
                    row[fieldIdx] = BitConverter.ToUInt16(readStream(ms, currentField.Length), 0);
                    break;

                case "int":
                    row[fieldIdx] = BitConverter.ToInt32(readStream(ms, currentField.Length), 0);
                    break;

                case "uint":
                    row[fieldIdx] = BitConverter.ToUInt32(readStream(ms, currentField.Length), 0);
                    break;

                case "long":
                    row[fieldIdx] = BitConverter.ToUInt64(readStream(ms, currentField.Length), 0);
                    break;

                case "byte":
                    row[fieldIdx] = (int)readStream(ms, currentField.Length)[0];
                    break;

                case "bitvector":
                    row[fieldIdx] = new BitVector32(BitConverter.ToInt32(readStream(ms, currentField.Length), 0));
                    break;

                case "bitfromvector":
                    int         bitPos    = row.GetPosition(fieldIdx);
                    BitVector32 bitVector = row.GetBitVector(currentField.BitsName);
                    row[fieldIdx] = Convert.ToInt32(bitVector[1 << bitPos]);
                    break;

                case "datetime":
                    int val = BitConverter.ToInt32(readStream(ms, currentField.Length), 0);
                    row[fieldIdx] = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc).AddSeconds(val);
                    break;

                case "decimal":
                    int     v0 = BitConverter.ToInt32(readStream(ms, currentField.Length), 0);
                    decimal v1 = v0 / 100m;
                    row[fieldIdx] = v1;
                    break;

                case "single":
                    row[fieldIdx] = BitConverter.ToSingle(readStream(ms, currentField.Length), 0);
                    break;

                case "double":
                    row[fieldIdx] = BitConverter.ToDouble(readStream(ms, currentField.Length), 0);
                    break;

                case "sid":
                    row[fieldIdx] = RowCount;
                    break;

                case "string":
                    row[fieldIdx] = ByteConverterExt.ToString(readStream(ms, currentField.Length), Encoding);
                    break;

                case "stringlen":
                    row[fieldIdx] = BitConverter.ToInt32(readStream(ms, currentField.Length), 0);
                    break;

                case "stringbylen":
                    row[fieldIdx] = ByteConverterExt.ToString(readStream(ms, row.GetStringLen(currentField.Name)), Encoding);
                    break;

                case "stringbyref":
                    int refLen = (int)header.GetRefValue(currentField.RefName);
                    row[fieldIdx] = ByteConverterExt.ToString(readStream(ms, refLen), Encoding);
                    break;
                }
            }

            return(row);
        }
        public byte[] Build(User currentUser, DateTime min, DateTime max, string filterUserScope, int[] filterUserIds, string filterProjectScope, int[] filterProjectIds)
        {
            var organization = db.Organizations.Find(currentUser.OrganizationId);

            var reportTitle = $"TIME CARDS BY PROJECT {min.ToString("M/d/yyyy")} thru {max.ToString("M/d/yyyy")} GENERATED {DateTime.Now.ToString("ddd, MMM d, yyyy h:mm:ss tt").ToUpperInvariant()}";

            using (var stream = new MemoryStream())
                using (var document = SpreadsheetDocument.Create(stream, SpreadsheetDocumentType.Workbook))
                {
                    // ------------------------------------------------------------
                    // Add document properties.
                    // ------------------------------------------------------------

                    document.PackageProperties.Creator = "BRIZBEE";
                    document.PackageProperties.Created = DateTime.UtcNow;


                    // ------------------------------------------------------------
                    // Add a WorkbookPart to the document.
                    // ------------------------------------------------------------

                    var workbookPart1 = document.AddWorkbookPart();
                    workbookPart1.Workbook = new Workbook();


                    // ------------------------------------------------------------
                    // Apply stylesheet.
                    // ------------------------------------------------------------

                    var workStylePart1 = workbookPart1.AddNewPart <WorkbookStylesPart>();
                    workStylePart1.Stylesheet = Stylesheets.Common();;


                    // ------------------------------------------------------------
                    // Add a WorksheetPart to the WorkbookPart.
                    // ------------------------------------------------------------

                    var worksheetPart1 = workbookPart1.AddNewPart <WorksheetPart>();
                    var worksheet1     = new Worksheet();
                    var rowBreaks1     = new RowBreaks()
                    {
                        Count = 0, ManualBreakCount = 0
                    };
                    var mergeCells1 = new MergeCells()
                    {
                        Count = 0
                    };
                    var sheetData1 = new SheetData();


                    // ------------------------------------------------------------
                    // Collect the users based on the filters.
                    // ------------------------------------------------------------

                    List <User> users;
                    if (filterUserScope.ToUpperInvariant() == "SPECIFIC")
                    {
                        users = db.Users
                                .Where(u => u.OrganizationId == currentUser.OrganizationId)
                                .Where(u => u.IsDeleted == false)
                                .Where(u => filterUserIds.Contains(u.Id))
                                .OrderBy(u => u.Name)
                                .ToList();
                    }
                    else
                    {
                        users = db.Users
                                .Where(u => u.OrganizationId == currentUser.OrganizationId)
                                .Where(u => u.IsDeleted == false)
                                .OrderBy(u => u.Name)
                                .ToList();
                    }


                    // ------------------------------------------------------------
                    // Collect the time cards based on the filters.
                    // ------------------------------------------------------------

                    IQueryable <TimesheetEntry> timeCardsQueryable = db.TimesheetEntries
                                                                     .Include(t => t.Task.Job.Customer)
                                                                     .Include(t => t.User)
                                                                     .Where(t => t.User.OrganizationId == currentUser.OrganizationId)
                                                                     .Where(t => t.User.IsDeleted == false)
                                                                     .Where(t => DbFunctions.TruncateTime(t.EnteredAt) >= min.Date)
                                                                     .Where(t => DbFunctions.TruncateTime(t.EnteredAt) <= max.Date);

                    // Optionally filter projects.
                    if (filterProjectScope.ToUpperInvariant() == "SPECIFIC")
                    {
                        timeCardsQueryable = timeCardsQueryable
                                             .Where(t => filterProjectIds.Contains(t.Task.JobId));
                    }

                    var timeCards = timeCardsQueryable.ToList();

                    var projectIds = timeCards
                                     .OrderBy(t => t.Task.Job.Number)
                                     .GroupBy(t => t.Task.JobId)
                                     .Select(g => g.Key)
                                     .ToList();


                    // ------------------------------------------------------------
                    // Loop each project.
                    // ------------------------------------------------------------

                    var rowIndex = (uint)1;
                    foreach (var projectId in projectIds)
                    {
                        var project        = db.Jobs.Find(projectId);
                        var groupedTaskIds = timeCards
                                             .GroupBy(t => t.TaskId)
                                             .Select(g => g.Key)
                                             .ToList();
                        var timeCardsForProject = timeCards
                                                  .Where(t => groupedTaskIds.Contains(t.TaskId))
                                                  .ToList();


                        // ------------------------------------------------------------
                        // Header for project cell.
                        // ------------------------------------------------------------

                        var rowProject = new Row()
                        {
                            RowIndex = rowIndex, Height = 22D, CustomHeight = true, Spans = new ListValue <StringValue>()
                            {
                                InnerText = "1:1"
                            }, StyleIndex = 4U, CustomFormat = true
                        };

                        var cellProject = new Cell()
                        {
                            CellReference = $"A{rowIndex}", StyleIndex = 4U, DataType = CellValues.String, CellValue = new CellValue($"Project {project.Number} - {project.Name} for Customer {project.Customer.Number} - {project.Customer.Name}")
                        };
                        rowProject.Append(cellProject);

                        sheetData1.Append(rowProject);

                        // Merge the user name across the row.
                        var mergeCell0 = new MergeCell()
                        {
                            Reference = $"A{rowIndex}:E{rowIndex}"
                        };
                        mergeCells1.Append(mergeCell0);
                        mergeCells1.Count++;

                        rowIndex++;


                        // ------------------------------------------------------------
                        // Loop each date.
                        // ------------------------------------------------------------

                        var dates = timeCards
                                    .GroupBy(t => t.EnteredAt.Date)
                                    .Select(g => g.Key)
                                    .OrderBy(g => g)
                                    .ToList();
                        foreach (var date in dates)
                        {
                            var timeCardsForProjectAndDate = timeCards
                                                             .Where(t => t.EnteredAt.Date == date.Date)
                                                             .Where(t => groupedTaskIds.Contains(t.TaskId))
                                                             .OrderBy(t => t.EnteredAt)
                                                             .ToList();

                            if (!timeCardsForProjectAndDate.Any())
                            {
                                continue;
                            }

                            rowIndex++;


                            // ------------------------------------------------------------
                            // Header for date cell.
                            // ------------------------------------------------------------

                            var rowDate = new Row()
                            {
                                RowIndex = rowIndex, Height = 22D, CustomHeight = true, Spans = new ListValue <StringValue>()
                                {
                                    InnerText = "1:1"
                                }, StyleIndex = 4U, CustomFormat = true
                            };

                            var cellDate = new Cell()
                            {
                                CellReference = $"A{rowIndex}", StyleIndex = 4U, DataType = CellValues.String, CellValue = new CellValue(date.ToString("D"))
                            };
                            rowDate.Append(cellDate);

                            sheetData1.Append(rowDate);

                            // Merge the date across the row.
                            var mergeCell1 = new MergeCell()
                            {
                                Reference = $"A{rowIndex}:E{rowIndex}"
                            };
                            mergeCells1.Append(mergeCell1);
                            mergeCells1.Count++;

                            rowIndex++;


                            // ------------------------------------------------------------
                            // Headers for time cards cells.
                            // ------------------------------------------------------------

                            var rowHeaders = new Row()
                            {
                                RowIndex = rowIndex, Height = 16D, CustomHeight = true, StyleIndex = 1U, CustomFormat = true
                            };

                            // Task Number
                            var cellTaskNumberHeader = new Cell()
                            {
                                CellReference = $"A{rowIndex}", DataType = CellValues.String, StyleIndex = 1U, CellValue = new CellValue("#")
                            };
                            rowHeaders.Append(cellTaskNumberHeader);

                            // Task Name
                            var cellTaskNameHeader = new Cell()
                            {
                                CellReference = $"B{rowIndex}", DataType = CellValues.String, StyleIndex = 1U, CellValue = new CellValue("Task")
                            };
                            rowHeaders.Append(cellTaskNameHeader);

                            // User Name
                            var cellUserNameHeader = new Cell()
                            {
                                CellReference = $"C{rowIndex}", DataType = CellValues.String, StyleIndex = 1U, CellValue = new CellValue("User")
                            };
                            rowHeaders.Append(cellUserNameHeader);

                            // Notes
                            var cellNotesHeader = new Cell()
                            {
                                CellReference = $"D{rowIndex}", DataType = CellValues.String, StyleIndex = 1U, CellValue = new CellValue("Notes")
                            };
                            rowHeaders.Append(cellNotesHeader);

                            // Total
                            var cellTotalHeader = new Cell()
                            {
                                CellReference = $"E{rowIndex}", DataType = CellValues.String, StyleIndex = 2U, CellValue = new CellValue("Total")
                            };
                            rowHeaders.Append(cellTotalHeader);

                            sheetData1.Append(rowHeaders);

                            rowIndex++;


                            // ------------------------------------------------------------
                            // Time cards cells.
                            // ------------------------------------------------------------

                            foreach (var timeCard in timeCardsForProjectAndDate)
                            {
                                var rowTimeCard = new Row()
                                {
                                    RowIndex = rowIndex, Height = 16D, CustomHeight = true
                                };

                                // Task Number
                                var cellTaskNumber = new Cell()
                                {
                                    CellReference = $"A{rowIndex}", DataType = CellValues.Number, StyleIndex = 6U, CellValue = new CellValue(timeCard.Task.Number)
                                };
                                rowTimeCard.Append(cellTaskNumber);

                                // Task Name
                                var cellTaskName = new Cell()
                                {
                                    CellReference = $"B{rowIndex}", DataType = CellValues.String, StyleIndex = 6U, CellValue = new CellValue(timeCard.Task.Name)
                                };
                                rowTimeCard.Append(cellTaskName);

                                // User Name
                                var cellUserName = new Cell()
                                {
                                    CellReference = $"C{rowIndex}", DataType = CellValues.String, StyleIndex = 6U, CellValue = new CellValue(timeCard.User.Name)
                                };
                                rowTimeCard.Append(cellUserName);

                                // Notes
                                var cellNotes = new Cell()
                                {
                                    CellReference = $"D{rowIndex}", DataType = CellValues.String, StyleIndex = 6U, CellValue = new CellValue(timeCard.Notes)
                                };
                                rowTimeCard.Append(cellNotes);

                                // Calculate the total
                                var total = Math.Round((double)timeCard.Minutes / 60, 2).ToString("0.00");

                                // Total
                                var cellTotal = new Cell()
                                {
                                    CellReference = $"E{rowIndex}", DataType = CellValues.Number, StyleIndex = 5U, CellValue = new CellValue(total)
                                };
                                rowTimeCard.Append(cellTotal);

                                sheetData1.Append(rowTimeCard);

                                rowIndex++;
                            }

                            // ------------------------------------------------------------
                            // Cells for date total.
                            // ------------------------------------------------------------

                            var rowDateTotal = new Row()
                            {
                                RowIndex = rowIndex, Height = 16D, CustomHeight = true, StyleIndex = 1U, CustomFormat = true
                            };

                            // Header Cell
                            var cellDateFormatted = new Cell()
                            {
                                CellReference = $"A{rowIndex}", DataType = CellValues.String, StyleIndex = 2U, CellValue = new CellValue("Daily Total")
                            };
                            rowDateTotal.Append(cellDateFormatted);

                            // Calculate the total
                            double dailyTotalMinutes = 0;
                            foreach (var timeCard in timeCardsForProjectAndDate)
                            {
                                dailyTotalMinutes += timeCard.Minutes;
                            }
                            var dailyTotal = Math.Round(dailyTotalMinutes / 60, 2).ToString("0.00");

                            // Total Cell
                            var cellDateTotal = new Cell()
                            {
                                CellReference = $"E{rowIndex}", DataType = CellValues.Number, StyleIndex = 2U, CellValue = new CellValue(dailyTotal)
                            };
                            rowDateTotal.Append(cellDateTotal);

                            sheetData1.Append(rowDateTotal);

                            // Merge the date across the row.
                            var mergeCell3 = new MergeCell()
                            {
                                Reference = $"A{rowIndex}:D{rowIndex}"
                            };
                            mergeCells1.Append(mergeCell3);
                            mergeCells1.Count++;

                            rowIndex++;
                        }


                        // ------------------------------------------------------------
                        // Cells for project total.
                        // ------------------------------------------------------------

                        var rowTotal = new Row()
                        {
                            RowIndex = rowIndex, Height = 16D, CustomHeight = true, StyleIndex = 1U, CustomFormat = true
                        };

                        // Header Cell
                        var cellProjectName = new Cell()
                        {
                            CellReference = $"A{rowIndex}", DataType = CellValues.String, StyleIndex = 2U, CellValue = new CellValue($"Total for Project {project.Number} - {project.Name}")
                        };
                        rowTotal.Append(cellProjectName);

                        // Calculate the total
                        double projectTotalMinutes = 0;
                        foreach (var timeCard in timeCardsForProject)
                        {
                            projectTotalMinutes += timeCard.Minutes;
                        }
                        var projectTotal = Math.Round(projectTotalMinutes / 60, 2).ToString("0.00");

                        // Total Cell
                        var cellProjectTotal = new Cell()
                        {
                            CellReference = $"E{rowIndex}", DataType = CellValues.Number, StyleIndex = 2U, CellValue = new CellValue(projectTotal)
                        };
                        rowTotal.Append(cellProjectTotal);

                        sheetData1.Append(rowTotal);

                        // Merge the project name across the row.
                        var mergeCell4 = new MergeCell()
                        {
                            Reference = $"A{rowIndex}:D{rowIndex}"
                        };
                        mergeCells1.Append(mergeCell4);
                        mergeCells1.Count++;

                        rowIndex++;


                        // ------------------------------------------------------------
                        // Add a page break.
                        // ------------------------------------------------------------

                        var rowBreak1 = new Break()
                        {
                            Id = rowIndex, Max = 16383U, ManualPageBreak = true
                        };
                        rowBreaks1.Append(rowBreak1);
                        rowBreaks1.ManualBreakCount++;
                        rowBreaks1.Count++;

                        rowIndex++;
                    }


                    // ------------------------------------------------------------
                    // Custom column width.
                    // ------------------------------------------------------------

                    var columns1 = new Columns();

                    var column1 = new Column()
                    {
                        Min = 1U, Max = 1U, Width = 10D, CustomWidth = true
                    };
                    var column2 = new Column()
                    {
                        Min = 2U, Max = 2U, Width = 28D, CustomWidth = true
                    };
                    var column3 = new Column()
                    {
                        Min = 3U, Max = 3U, Width = 28D, CustomWidth = true
                    };
                    var column4 = new Column()
                    {
                        Min = 4U, Max = 4U, Width = 40D, CustomWidth = true
                    };
                    var column5 = new Column()
                    {
                        Min = 5U, Max = 5U, Width = 10D, CustomWidth = true
                    };

                    columns1.Append(column1);
                    columns1.Append(column2);
                    columns1.Append(column3);
                    columns1.Append(column4);
                    columns1.Append(column5);


                    // ------------------------------------------------------------
                    // Sheet Views.
                    // ------------------------------------------------------------

                    var sheetViews1 = new SheetViews();

                    var sheetView1 = new SheetView()
                    {
                        ShowGridLines = true, TabSelected = true, ZoomScaleNormal = 100U, WorkbookViewId = 0U
                    };
                    var selection1 = new Selection()
                    {
                        ActiveCell = "A1", SequenceOfReferences = new ListValue <StringValue>()
                        {
                            InnerText = "A1"
                        }
                    };

                    sheetView1.Append(selection1);
                    sheetViews1.Append(sheetView1);


                    // ------------------------------------------------------------
                    // Sheet Format.
                    // ------------------------------------------------------------

                    var sheetFormatProperties1 = new SheetFormatProperties()
                    {
                        DefaultRowHeight = 16D, DyDescent = 0.35D
                    };


                    // ------------------------------------------------------------
                    // Page Setup.
                    // ------------------------------------------------------------

                    var pageMargins1 = new PageMargins()
                    {
                        Left = 0.5D, Right = 0.5D, Top = 0.5D, Bottom = 0.5D, Header = 0.3D, Footer = 0.3D
                    };
                    var pageSetup1 = new PageSetup()
                    {
                        Orientation = OrientationValues.Landscape
                    };


                    // ------------------------------------------------------------
                    // Header and Footer.
                    // ------------------------------------------------------------

                    var headerFooter1 = new HeaderFooter();

                    var oddHeader1 = new OddHeader();
                    oddHeader1.Text = reportTitle;

                    var oddFooter1 = new OddFooter();
                    oddFooter1.Text = organization.Name;

                    headerFooter1.Append(oddHeader1);
                    headerFooter1.Append(oddFooter1);


                    // ------------------------------------------------------------
                    // Build the worksheet.
                    // ------------------------------------------------------------

                    worksheet1.Append(sheetViews1);
                    worksheet1.Append(columns1);
                    worksheet1.Append(sheetData1);

                    // Cannot add zero merge cells.
                    if (mergeCells1.Count != 0)
                    {
                        worksheet1.Append(mergeCells1);
                    }

                    worksheet1.Append(pageMargins1);
                    worksheet1.Append(pageSetup1);
                    worksheet1.Append(headerFooter1);

                    worksheet1.Append(rowBreaks1);

                    worksheetPart1.Worksheet = worksheet1;


                    // ------------------------------------------------------------
                    // Add Sheets to the Workbook.
                    // ------------------------------------------------------------

                    var sheets = workbookPart1.Workbook.AppendChild(new Sheets());


                    // ------------------------------------------------------------
                    // Append a new worksheet and associate it with the workbook.
                    // ------------------------------------------------------------

                    var sheet = new Sheet()
                    {
                        Id      = workbookPart1.GetIdOfPart(worksheetPart1),
                        SheetId = 1,
                        Name    = "Report"
                    };
                    sheets.Append(sheet);


                    // Save and close the document.
                    workbookPart1.Workbook.Save();
                    document.Close();

                    return(stream.ToArray());
                }
        }
Beispiel #33
0
            private async Task <T> ReadRowAsyncImplViaDbReader <T>(DbDataReader reader, Type type, Row row)
            {
                if (reader == null)
                {
                    throw new ObjectDisposedException(GetType().FullName, "The reader has been disposed; this can happen after all data has been consumed");
                }
                if (IsConsumed)
                {
                    throw new InvalidOperationException("Query results must be consumed in the correct order, and each result can only be consumed once");
                }

                IsConsumed = true;
                T result = default;

                if (await reader.ReadAsync(cancel).ConfigureAwait(false) && reader.FieldCount != 0)
                {
                    var       typedIdentity = identity.ForGrid(type, gridIndex);
                    CacheInfo cache         = GetCacheInfo(typedIdentity, null, addToCache);
                    var       deserializer  = cache.Deserializer;

                    int hash = GetColumnHash(reader);
                    if (deserializer.Func == null || deserializer.Hash != hash)
                    {
                        deserializer       = new DeserializerState(hash, GetDeserializer(type, reader, 0, -1, false));
                        cache.Deserializer = deserializer;
                    }

                    result = ConvertTo <T>(deserializer.Func(reader));

                    if ((row & Row.Single) != 0 && await reader.ReadAsync(cancel).ConfigureAwait(false))
                    {
                        ThrowMultipleRows(row);
                    }
                    while (await reader.ReadAsync(cancel).ConfigureAwait(false)) /* ignore subsequent rows */ } {
            }
Beispiel #34
0
        public FileResult ExportFindingsReport(int companyId, string sCurrDate)
        {
            byte[] b;

            DateTime curr;

            sCurrDate = sCurrDate.Replace("'", "");
            if (!DateTime.TryParse(sCurrDate, out curr))
            {
                curr = DateTime.Now.ToLocalTime();
            }
            string currDate = $"{curr.ToShortDateString()} {curr.ToShortTimeString()}";

            DCTSOpenXML oxl = new DCTSOpenXML();

            using (MemoryStream memStream = new MemoryStream())
            {
                using (SpreadsheetDocument document = SpreadsheetDocument.Create(memStream, SpreadsheetDocumentType.Workbook))
                {
                    // Build Excel File
                    WorkbookPart workbookPart = document.AddWorkbookPart();
                    workbookPart.Workbook = new Workbook();

                    WorksheetPart worksheetPart = workbookPart.AddNewPart <WorksheetPart>();
                    worksheetPart.Worksheet = new Worksheet(new SheetData());

                    Sheets sheets = document.WorkbookPart.Workbook.AppendChild(new DocumentFormat.OpenXml.Spreadsheet.Sheets());

                    // declare locals
                    Row    row;
                    Cell   cell;
                    string loc;
                    int    rr;

                    Sheet sheet = new Sheet()
                    {
                        Id      = workbookPart.GetIdOfPart(worksheetPart),
                        SheetId = 1,
                        Name    = "Findings"
                    };
                    sheets.Append(sheet);

                    Worksheet worksheet = new Worksheet();
                    SheetData sd        = new SheetData();
                    // Build sheet
                    // Title
                    row  = new Row();
                    cell = oxl.SetCellVal("A1", $"Export - Findings  {currDate}");
                    row.Append(cell);
                    sd.Append(row);
                    row  = new Row();
                    cell = oxl.SetCellVal("A2", "");
                    row.Append(cell);
                    sd.Append(row);
                    // Headers
                    row = new Row();
                    oxl.columns.Append(new Column()
                    {
                        Width = oxl.ComputeExcelCellWidth(oxl.minWidth), Min = 1, Max = 1, BestFit = true, CustomWidth = true
                    }); cell = oxl.SetCellVal("A3", "Id"); row.Append(cell);
                    oxl.columns.Append(new Column()
                    {
                        Width = oxl.ComputeExcelCellWidth(oxl.minWidth), Min = 2, Max = 2, BestFit = true, CustomWidth = true
                    }); cell = oxl.SetCellVal("B3", "Name"); row.Append(cell);
                    oxl.columns.Append(new Column()
                    {
                        Width = oxl.ComputeExcelCellWidth(oxl.minWidth), Min = 3, Max = 3, BestFit = true, CustomWidth = true
                    }); cell = oxl.SetCellVal("C3", "Weight (dwt)"); row.Append(cell);
                    oxl.columns.Append(new Column()
                    {
                        Width = oxl.ComputeExcelCellWidth(oxl.minWidth), Min = 4, Max = 4, BestFit = true, CustomWidth = true
                    }); cell = oxl.SetCellVal("D3", "Price"); row.Append(cell);
                    oxl.columns.Append(new Column()
                    {
                        Width = oxl.ComputeExcelCellWidth(oxl.minWidth), Min = 5, Max = 5, BestFit = true, CustomWidth = true
                    }); cell = oxl.SetCellVal("E3", "Vendor"); row.Append(cell);
                    oxl.columns.Append(new Column()
                    {
                        Width = oxl.ComputeExcelCellWidth(oxl.minWidth), Min = 6, Max = 6, BestFit = true, CustomWidth = true
                    }); cell = oxl.SetCellVal("F3", "Inventory"); row.Append(cell);
                    worksheet.Append(oxl.columns);
                    sd.Append(row);
                    List <Finding> Findings = db.Findings.Where(v => v.CompanyId == companyId).OrderBy(f => f.Name).Include("Vendor").ToList();
                    // Content
                    for (int i = 0; i < Findings.Count(); i++)
                    {
                        row = new Row();
                        rr  = 4 + i;
                        loc = "A" + rr; cell = oxl.SetCellVal(loc, Findings[i].Id); row.Append(cell);
                        loc = "B" + rr; cell = oxl.SetCellVal(loc, Findings[i].Name); row.Append(cell);
                        loc = "C" + rr;
                        if (Findings[i].Weight == null)
                        {
                            cell = oxl.SetCellVal(loc, "");
                        }
                        else
                        {
                            cell = oxl.SetCellVal(loc, Findings[i].Weight.Value);
                        }
                        row.Append(cell);
                        loc = "D" + rr; cell = oxl.SetCellVal(loc, Findings[i].Price); row.Append(cell);
                        loc = "E" + rr; cell = oxl.SetCellVal(loc, Findings[i].Vendor.Name); row.Append(cell);
                        loc = "F" + rr; cell = oxl.SetCellVal(loc, Findings[i].Qty); row.Append(cell);
                        sd.Append(row);
                    }
                    worksheet.Append(sd);
                    // Autofit columns - ss:AutoFitWidth="1"
                    worksheetPart.Worksheet = worksheet;
                    workbookPart.Workbook.Save();
                    document.Close();

                    b = memStream.ToArray();
                    return(File(b, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
                                $"Findings as of {currDate}.xlsx"));
                }
            }
        }
 /// <summary>
 /// Initializes a new instance of the <see cref="LogicAchievementData"/> class.
 /// </summary>
 public LogicAchievementData(Row row, LogicDataTable dataTable) : base(row, dataTable)
 {
     LogicData.Load(this, this.GetType(), row);
 }
Beispiel #36
0
        /// <summary>
        /// Converts row to BSON document suitable for storage in MONGO.DB.
        /// Pass target name (name of particular store/epoch/implementation) to get targeted field metadata.
        /// Note: the supplied row MAY NOT CONTAIN REFERENCE CYCLES - either direct or transitive
        /// </summary>
        public virtual BSONDocument RowToBSONDocument(Row row, string targetName, bool useAmorphousData = true, FieldFilterFunc filter = null)
        {
            var el = RowToBSONDocumentElement(row, targetName, useAmorphousData, filter: filter);

            return(el.Value);
        }
Beispiel #37
0
        private void writeRow(MemoryStream ms, Row currentRow)
        {
            byte[] buffer;

            for (int fieldIdx = 0; fieldIdx < FieldCount; fieldIdx++)
            {
                LuaField currentField = GetField(fieldIdx);
                if (currentRow[fieldIdx] == null)
                {
                    currentRow[fieldIdx] = currentRow.GetCell(fieldIdx).Default;
                }

                switch (currentField.Type)
                {
                case "short":
                    ms.Write(BitConverter.GetBytes(Convert.ToInt16(currentRow[fieldIdx])), 0, currentField.Length);
                    break;

                case "ushort":
                    ms.Write(BitConverter.GetBytes(Convert.ToUInt16(currentRow[fieldIdx])), 0, currentField.Length);
                    break;

                case "int":
                    ms.Write(BitConverter.GetBytes(Convert.ToInt32(currentRow[fieldIdx])), 0, currentField.Length);
                    break;

                case "uint":
                    ms.Write(BitConverter.GetBytes(Convert.ToUInt32(currentRow[fieldIdx])), 0, currentField.Length);
                    break;

                case "long":
                    ms.Write(BitConverter.GetBytes(Convert.ToInt64(currentRow[fieldIdx])), 0, currentField.Length);
                    break;

                case "byte":
                    int fieldLen = currentRow.GetLength(fieldIdx);
                    if (fieldLen == 1)
                    {
                        ms.WriteByte(Convert.ToByte(currentRow[fieldIdx]));
                    }
                    else
                    {
                        ms.Write(new byte[fieldLen], 0, fieldLen);
                    }
                    break;

                case "bitvector":
                    ms.Write(BitConverter.GetBytes(generateBitVector(currentRow, currentField.Name).Data), 0, currentField.Length);
                    break;

                case "datetime":
                    DateTime val  = Convert.ToDateTime(currentRow[currentField.Name]);
                    int      val2 = Convert.ToInt32((val - new DateTime(1970, 1, 1, 0, 0, 0, 0)).TotalSeconds);
                    ms.Write(BitConverter.GetBytes(val2), 0, currentField.Length);
                    break;

                case "decimal":
                    decimal v0 = Convert.ToDecimal(currentRow[fieldIdx]);
                    int     v1 = Convert.ToInt32(v0 * 100);
                    ms.Write(BitConverter.GetBytes(v1), 0, currentField.Length);
                    break;

                case "single":
                    ms.Write(BitConverter.GetBytes(Convert.ToSingle(currentRow[fieldIdx])), 0, currentField.Length);
                    break;

                case "double":
                    ms.Write(BitConverter.GetBytes(Convert.ToDouble(currentRow[fieldIdx])), 0, currentField.Length);
                    break;

                case "string":
                {
                    buffer = ByteConverterExt.ToBytes(currentRow[fieldIdx].ToString(), Encoding);
                    int remainder = currentField.Length - buffer.Length;
                    ms.Write(buffer, 0, buffer.Length);
                    ms.Write(new byte[remainder], 0, remainder);
                }
                break;

                case "stringlen":
                    ms.Write(BitConverter.GetBytes(currentRow.GetStringByLenValue(currentField.Name).Length + 1), 0, currentField.Length);
                    break;

                case "stringbylen":
                    buffer = ByteConverterExt.ToBytes(currentRow[fieldIdx].ToString() + '\0', Encoding);
                    ms.Write(buffer, 0, buffer.Length);
                    break;

                case "stringbyref":     // TODO: Implement me [stringbyref] SAVE
                {
                    buffer = ByteConverterExt.ToBytes(currentRow[fieldIdx].ToString(), Encoding);
                    string refName   = currentRow.GetRefName(fieldIdx).ToString();
                    int    remainder = Convert.ToInt32(header[refName]) - buffer.Length;
                    ms.Write(buffer, 0, buffer.Length);
                    ms.Write(new byte[remainder], 0, remainder);
                }
                break;
                }
            }
        }
Beispiel #38
0
        public void ParseRDB(string rdbPath)
        {
            int rowCnt = 0;

            if (File.Exists(rdbPath))
            {
                using (MemoryStream ms = new MemoryStream(File.ReadAllBytes(rdbPath)))
                {
                    byte[] buffer = new byte[0];

                    if (luaIO.UseHeader)
                    {
                        header = readHeader(ms);
                        rowCnt = (int)header.ValueByFlag("rowcount");
                        // TODO: Define 'date' by reading actual info (if present)
                        date = string.Format("{0}{1}{2}", DateTime.Now.Year, GetDate(DateTime.Now.Month), GetDate(DateTime.Now.Day));
                    }
                    else
                    {
                        buffer = new byte[8];
                        ms.Read(buffer, 0, buffer.Length);

                        date = this.Encoding.GetString(buffer);

                        ms.Position += 120;

                        // Read the row count
                        buffer = new byte[4];
                        ms.Read(buffer, 0, buffer.Length);
                        rowCnt = BitConverter.ToInt32(buffer, 0);
                    }


                    if (SpecialCase)
                    {
                        OnProgressMaxChanged(new ProgressMaxArgs(rowCnt));

                        switch (Case)
                        {
                        case "doubleloop":

                            for (int rowIdx = 0; rowIdx < rowCnt; rowIdx++)
                            {
                                buffer = new byte[4];
                                ms.Read(buffer, 0, buffer.Length);

                                int loopCount = BitConverter.ToInt32(buffer, 0);
                                for (int i = 0; i < loopCount; i++)
                                {
                                    Row currentRow = readRow(ms);
                                    if (UseRowProcesser)
                                    {
                                        CallRowProcessor("read", currentRow, rowIdx);
                                    }
                                    data.Add(currentRow);
                                    if (((rowIdx * 100) / RowCount) != ((rowIdx - 1) * 100 / RowCount))
                                    {
                                        OnProgressValueChanged(new ProgressValueArgs(rowIdx));
                                    }
                                }
                            }

                            break;
                        }
                    }
                    else
                    {
                        OnProgressMaxChanged(new ProgressMaxArgs(rowCnt));

                        for (int rowIdx = 0; rowIdx < rowCnt; rowIdx++)
                        {
                            Row currentRow = readRow(ms);
                            if (UseRowProcesser)
                            {
                                CallRowProcessor("read", currentRow, rowIdx);
                            }
                            data.Add(currentRow);

                            if (((rowIdx * 100) / rowCnt) != ((rowIdx - 1) * 100 / rowCnt))
                            {
                                OnProgressValueChanged(new ProgressValueArgs(rowIdx));
                            }
                        }
                    }
                }

                OnProgressMaxChanged(new ProgressMaxArgs(100));
                OnProgressValueChanged(new ProgressValueArgs(0));
            }
            else
            {
                throw new FileNotFoundException("Cannot find file specified", rdbPath);
            }
        }
    /// <summary>
    /// Since the LocalGovernment Geodatabase does not have AttributedRelationshipClasses, the following method illustrates the behavior 
    /// if such a dataset existed.
    /// </summary>
    public async Task MainMethodCode()
    {
      // Opening a Non-Versioned SQL Server instance.

      DatabaseConnectionProperties connectionProperties = new DatabaseConnectionProperties(EnterpriseDatabaseType.SQLServer)
      {
        AuthenticationMode = AuthenticationMode.DBMS,
        
        // Where testMachine is the machine where the instance is running and testInstance is the name of the SqlServer instance.
        Instance = @"testMachine\testInstance",

        // Provided that a database called LocalGovernment has been created on the testInstance and geodatabase has been enabled on the database.
        Database = "LocalGovernment",

        // Provided that a login called gdb has been created and corresponding schema has been created with the required permissions.
        User     = "******",
        Password = "******",
        Version  = "dbo.DEFAULT"
      };
      
      using (Geodatabase geodatabase                                 = new Geodatabase(connectionProperties))
      using (AttributedRelationshipClass attributedRelationshipClass = geodatabase.OpenDataset<AttributedRelationshipClass>("LocalGovernment.GDB.ParcelToBuilding"))
      using (FeatureClass parcelFeatureClass                         = geodatabase.OpenDataset<FeatureClass>("LocalGovernment.GDB.Parcel"))
      using (FeatureClass buildingFeatureClass                       = geodatabase.OpenDataset<FeatureClass>("LocalGovernment.GDB.Building"))
      {
        RowCursor parcelsCursor = parcelFeatureClass.Search(new QueryFilter { WhereClause = "APN = 5678" }, false);
        parcelsCursor.MoveNext();
        Row parcelFeature = parcelsCursor.Current;

        RowCursor buildingsCursor = buildingFeatureClass.Search(new QueryFilter { WhereClause = "BUILDID = 4321" }, false);
        buildingsCursor.MoveNext();
        Row buildingFeature = buildingsCursor.Current;

        try
        {
          EditOperation editOperation = new EditOperation();
          editOperation.Callback(context => 
          {
            RowBuffer rowBuffer = attributedRelationshipClass.CreateRowBuffer();

            // Assuming "owner" is one of the attribute fields in this relationshipClass.
            int ownerFieldIndex = rowBuffer.FindField("owner");

            // Assuming "location" is another attribute field in this relationshipClass.
            int locationFieldIndex = rowBuffer.FindField("location");
            rowBuffer[ownerFieldIndex]    = "Somebody";
            rowBuffer[locationFieldIndex] = "Somewhere";

            AttributedRelationship newRelationship = attributedRelationshipClass.CreateRelationship(parcelFeature, buildingFeature, rowBuffer);
            
            // This will be "Somebody".
            object ownerFieldValue = newRelationship[ownerFieldIndex];

            // This will be "Somewhere".
            object locationFieldValue = newRelationship[locationFieldIndex];

            IReadOnlyList<AttributedRelationship> relationshipsForOriginRows = attributedRelationshipClass.GetRelationshipsForOriginRows(
              new List<long> { parcelFeature.GetObjectID() });

            AttributedRelationship newlyAddedRelationship = relationshipsForOriginRows.FirstOrDefault(relationship =>
              relationship.GetDestinationRow().GetObjectID() == buildingFeature.GetObjectID());

            // This will be "Somebody".
            ownerFieldValue = newlyAddedRelationship[ownerFieldIndex];

            // This will be "Somewhere".
            locationFieldValue = newlyAddedRelationship[locationFieldIndex];
          }, attributedRelationshipClass);

          bool executeResult = editOperation.Execute();

          bool saveResult = await Project.Current.SaveEditsAsync();
        }
        finally
        {
          parcelsCursor.Dispose();

          if (parcelFeature != null)
            parcelFeature.Dispose();

          buildingsCursor.Dispose();

          if (buildingFeature != null)
            buildingFeature.Dispose();
        }
      }
    }
Beispiel #40
0
        public void WriteRDB(string buildPath)
        {
            using (MemoryStream ms = new MemoryStream())
            {
                writeHeader(ms, (luaIO.UseHeader) ? HeaderType.Defined : HeaderType.Traditional);

                OnProgressMaxChanged(new ProgressMaxArgs(RowCount));

                if (SpecialCase)
                {
                    byte[] buffer;

                    switch (Case)
                    {
                    case "doubleloop":

                        int previousVal = 0;

                        for (int rowIdx = 0; rowIdx < RowCount; rowIdx++)
                        {
                            Row currentRow = (Row)data[rowIdx];
                            int currentVal = (int)currentRow.ValueByFlag("loopcounter");
                            if (previousVal != currentVal)
                            {
                                List <Row> rows = data.FindAll(r => (int)r[0] == currentVal);

                                buffer = BitConverter.GetBytes(rows.Count);
                                ms.Write(buffer, 0, buffer.Length);

                                for (int filteredIdx = 0; filteredIdx < rows.Count; filteredIdx++)
                                {
                                    if (UseRowProcesser)
                                    {
                                        CallRowProcessor("write", rows[filteredIdx], rowIdx);
                                    }
                                    writeRow(ms, rows[filteredIdx]);
                                }

                                previousVal = currentVal;
                            }
                        }

                        break;
                    }
                }
                else
                {
                    for (int rowIdx = 0; rowIdx < RowCount; rowIdx++)
                    {
                        Row currentRow = data[rowIdx];

                        if (UseRowProcesser)
                        {
                            CallRowProcessor("write", currentRow, rowIdx);
                        }
                        writeRow(ms, currentRow);

                        if (((rowIdx * 100) / RowCount) != ((rowIdx - 1) * 100 / RowCount))
                        {
                            OnProgressValueChanged(new ProgressValueArgs(rowIdx));
                        }
                    }
                }

                OnMessageOccured(new MessageArgs(string.Format("Writing {0}", buildPath)));
                using (FileStream fs = File.Create(buildPath)) { ms.WriteTo(fs); }
            }

            OnProgressMaxChanged(new ProgressMaxArgs(100));
            OnProgressValueChanged(new ProgressValueArgs(0));
        }
        private void SaveToExcel()
        {
            string date = DateTime.Now.ToShortDateString();

            date = date.Replace("/", "_");
            string fileName;

            if (IsExtraDataVisible)
            {
                fileName = System.IO.Path.Combine(App.path, date + "VeganShopSrednia" + UserId + "Detale.xlsx");
            }
            else
            {
                fileName = System.IO.Path.Combine(App.path, date + "VeganShopGlobalnaSredniaDetale.xlsx");
            }

            using (SpreadsheetDocument document = SpreadsheetDocument.Create(fileName, SpreadsheetDocumentType.Workbook))
            {
                WorksheetPart worksheetPart;
                if (IsExtraDataVisible)
                {
                    worksheetPart = createWorkSheet(document, UserId + "Srednia");
                }
                else
                {
                    worksheetPart = createWorkSheet(document, "GlobalnaSrednia");
                }

                SheetData sheetData = worksheetPart.Worksheet.AppendChild(new SheetData());

                Row Row;

                if (IsExtraDataVisible)
                {
                    Row = new Row();
                    Row.Append(
                        ConstructCell("Id Użytkownika", CellValues.String),
                        ConstructCell(UserId, CellValues.String));
                    sheetData.AppendChild(Row);

                    Row = new Row();
                    Row.Append(
                        ConstructCell("Ip Użytkownika", CellValues.String),
                        ConstructCell(UserIp, CellValues.String));
                    sheetData.AppendChild(Row);

                    Row = new Row();
                    Row.Append(
                        ConstructCell("Średnie akcje w koszyku", CellValues.String),
                        ConstructCell(AverageCartAction, CellValues.String));
                    sheetData.AppendChild(Row);
                }

                Row = new Row();
                Row.Append(
                    ConstructCell("Najpopularniesze Urządzenie", CellValues.String),
                    ConstructCell(MostUsedDevice, CellValues.String));
                sheetData.AppendChild(Row);
                Row = new Row();
                Row.Append(
                    ConstructCell("Najpopularniejsza Przeglądarka", CellValues.String),
                    ConstructCell(MostUsedBrowser, CellValues.String));
                sheetData.AppendChild(Row);
                Row = new Row();
                Row.Append(
                    ConstructCell("Najpopularniejsza Lokacja", CellValues.String),
                    ConstructCell(MostPopularLocation, CellValues.String));
                sheetData.AppendChild(Row);
                Row = new Row();
                Row.Append(
                    ConstructCell("Najpopularniejsze Polecenie", CellValues.String),
                    ConstructCell(MostPopularReffer, CellValues.String));
                sheetData.AppendChild(Row);
                Row = new Row();
                Row.Append(
                    ConstructCell("Średni Czas na Stronach", CellValues.String),
                    ConstructCell(AverageTimeOnPages.ToString(), CellValues.String));
                sheetData.AppendChild(Row);
                Row = new Row();
                Row.Append(
                    ConstructCell("Średnia Ilość Kupionych Przedmiotów", CellValues.String),
                    ConstructCell(AvItemBuy.ToString(), CellValues.String));
                sheetData.AppendChild(Row);
                Row = new Row();
                Row.Append(
                    ConstructCell("Przeważnie Zalogowany", CellValues.String),
                    ConstructCell(MostlyLogged.ToString(), CellValues.String));
                sheetData.AppendChild(Row);

                worksheetPart.Worksheet.Save();
            }
        }
Beispiel #42
0
 internal void CallRowProcessor(string mode, Row row, int rowCount)
 {
     luaIO.CallRowProcessor(mode, row, rowCount);
 }
Beispiel #43
0
        private void AdvancedTab()
        {
            Text.GuiBold("Class");

            Table.Gui("Obfuscate:", "Private", "Protected", "Public", ref Gui.GuiSettings.ObfuscateClassPrivate, ref Gui.GuiSettings.ObfuscateClassProtected, ref Gui.GuiSettings.ObfuscateClassPublic);

            EditorGUILayout.HelpBox("Obfuscation of Generic or Abstract classes can lead to warning messages (like 'XYZ can not be an abstract class' or 'Serialization XYZ error') in the build log. This does not harm. But if you recognize any problems or limitations deactivate it.", MessageType.Warning);

            Row.Gui("Obfuscate generic classes:", ref GuiSettings.ObfuscateClassGeneric);
            Row.Gui("Obfuscate abstract classes:", ref GuiSettings.ObfuscateClassAbstract);

            if (Obfuscator.Setting.InternalSettings.ObfuscatorType != Setting.EObfuscatorType.Pro)
            {
                GUI.enabled = false;
            }
            EditorGUILayout.HelpBox("Define here if classes that inherite from MonoBehaviour/NetworkBehaviour or ScriptableObject should get Obfuscated. For more security, they will automatically be placed in the same namespace.\nWhile obfuscation and after, 'Reloading Assets' appears. Thats normal, do not worry.", MessageType.Info);
            Row.GuiGold("Obfuscate unity class names:", ref GuiSettings.ObfuscateUnityClasses);
            GUI.enabled = Gui.GuiSettings.ObfuscateGlobally;

            Text.GuiBold("Field");

            Table.Gui("Obfuscate:", "Private", "Protected", "Public", ref Gui.GuiSettings.ObfuscateFieldPrivate, ref Gui.GuiSettings.ObfuscateFieldProtected, ref Gui.GuiSettings.ObfuscateFieldPublic);

            EditorGUILayout.HelpBox("Define here if values of enums shall get Obfuscated. Deactivate it, if you use 'ToString()' with enums.", MessageType.Warning);
            Row.Gui("Obfuscate enum values:", ref GuiSettings.ObfuscateEnumValues);

            if (Obfuscator.Setting.InternalSettings.ObfuscatorType != Setting.EObfuscatorType.Pro)
            {
                GUI.enabled = false;
            }
            EditorGUILayout.HelpBox("If you use GameObjects in your Scene, which use Editor editable fields, deactivate this.", MessageType.Warning);
            Row.GuiGold("Obfuscate unity public fields:", ref GuiSettings.ObfuscateUnityPublicFields);
            GUI.enabled = Gui.GuiSettings.ObfuscateGlobally;

            Text.GuiBold("Method");

            Table.Gui("Obfuscate:", "Private", "Protected", "Public", ref Gui.GuiSettings.ObfuscateMethodPrivate, ref Gui.GuiSettings.ObfuscateMethodProtected, ref Gui.GuiSettings.ObfuscateMethodPublic);

            EditorGUILayout.HelpBox("Try to auto find used Gui methods. Mostly it will not find all methods. So add to methods, that appear not to get called in game, the 'Obfuscator.DoNotRenameAttribute'.", MessageType.Info);
            Row.Gui("Auto find Gui methods: ", ref GuiSettings.TryFindGuiMethods);

            EditorGUILayout.HelpBox("Try to auto find used Animation methods. Mostly it will not find all methods. So add to methods, that appear not to get called in game, the 'Obfuscator.DoNotRenameAttribute'.", MessageType.Info);
            Row.Gui("Auto find Animation methods: ", ref GuiSettings.TryFindAnimationMethods);

            Text.GuiBold("Attribute");
            EditorGUILayout.HelpBox("Add here Attributes you want to behave like the Attribute DoNotRename. These Attribute must entered with their fullname. For example, if you want the Unity NetworkBehaviour Attribute ClientRpc to behave like DoNotRename you have to enter ClientRpcAttribute. So don't forget the 'Attribute' at the ending if there is one.", MessageType.Info);

            //
            ScriptableObject   var_Target           = this;
            SerializedObject   var_SerializedObject = new SerializedObject(var_Target);
            SerializedProperty var_StringsProperty  = var_SerializedObject.FindProperty("AttributeArray");

            EditorGUILayout.PropertyField(var_StringsProperty, new GUIContent("Attributes"), true);
            var_SerializedObject.ApplyModifiedProperties();

            GUILayout.BeginHorizontal();
            if (GUILayout.Button("Add Line"))
            {
                List <String> var_TempList = new List <string>(this.AttributeArray);
                var_TempList.Add("");
                this.AttributeArray = var_TempList.ToArray();
            }
            if (GUILayout.Button("Remove Line"))
            {
                List <String> var_TempList = new List <string>(this.AttributeArray);
                if (var_TempList.Count > 0)
                {
                    var_TempList.RemoveAt(var_TempList.Count - 1);
                }
                this.AttributeArray = var_TempList.ToArray();
            }
            GUILayout.EndHorizontal();

            GuiSettings.AttributesBehaveLikeDoNotRenameList = new List <string>(this.AttributeArray);
            //
        }
Beispiel #44
0
 public Cell GetCell(Row row, Column column)
 {
     return(new Cell(" "));
 }
Beispiel #45
0
        void OnGUI()
        {
            try
            {
                this.scrollPosition = GUILayout.BeginScrollView(this.scrollPosition, false, false, GUILayout.Width(position.width), GUILayout.Height(position.height));

                GUIStyle var_Style = new GUIStyle("button");
                var_Style.normal.background = null;
                var_Style.active.background = null;

                GUILayout.BeginHorizontal();
                GUILayout.FlexibleSpace();
                if (GUILayout.Button((Texture)EditorGUIUtility.Load("Assets/OPS/Obfuscator.Free/Editor/Gui/Rate.png"), var_Style, GUILayout.MaxWidth(100), GUILayout.MaxHeight(26)))
                {
                    Application.OpenURL("https://assetstore.unity.com/packages/tools/utilities/obfuscator-free-89420");
                }
                if (GUILayout.Button((Texture)EditorGUIUtility.Load("Assets/OPS/Obfuscator.Free/Editor/Gui/BugQuestion.png"), var_Style, GUILayout.MaxWidth(200), GUILayout.MaxHeight(26)))
                {
                    Application.OpenURL("mailto:[email protected]?subject=OPS/Obfuscator.Free_Bug");
                }
                GUILayout.EndHorizontal();

                GUILayout.BeginHorizontal();
                GUILayout.Label((Texture)EditorGUIUtility.Load("Assets/OPS/Obfuscator.Free/Editor/Gui/Header_Icon.png"), GUILayout.MaxWidth(24), GUILayout.MaxHeight(24), GUILayout.MinWidth(24), GUILayout.MinHeight(24));
                Text.GuiBold("Obfuscator", 150, 24);
                GUILayout.EndHorizontal();

                EditorGUILayout.HelpBox("De-/Activate Obfuscator here.", MessageType.Info);

                Row.GuiBold("Obfuscate Globally: ", ref Gui.GuiSettings.ObfuscateGlobally);

                GUILayout.Space(10);

                GUI.enabled = Gui.GuiSettings.ObfuscateGlobally;

                this.tabIndex = GUILayout.Toolbar(this.tabIndex, new Texture[] { (Texture)EditorGUIUtility.Load("Assets/OPS/Obfuscator.Free/Editor/Gui/General_T32x.png"), (Texture)EditorGUIUtility.Load("Assets/OPS/Obfuscator.Free/Editor/Gui/Advanced_T32x.png"), (Texture)EditorGUIUtility.Load("Assets/OPS/Obfuscator.Free/Editor/Gui/Security_T32x.png") });
                switch (this.tabIndex)
                {
                case 0:
                {
                    this.GeneralTab();
                    break;
                }

                case 1:
                {
                    this.AdvancedTab();
                    break;
                }

                case 2:
                {
                    this.SecurityTab();
                    break;
                }
                }

                GUI.enabled = true;

                GUILayout.EndScrollView();

                if (GUI.changed)
                {
                    GuiSettings.SaveSettings();
                }
            }
            catch (Exception e)
            {
                Debug.LogError(e.ToString());
                this.Close();
            }
        }
Beispiel #46
0
 public ColumnMapping(WorkbookPart workbookPart, Row headerRow, ColumnDefinition columnDefinition)
 {
     this.workbookPart     = workbookPart;
     this.columnDefinition = columnDefinition;
     this.cells            = headerRow.Elements <Cell>().ToList();
 }
        private void InternalParseLine(int index, bool ParseKeywords)
        {
            if (mSyntaxDefinition == null)
            {
                return;
            }

            //
            //			if (ParseKeywords)
            //				return;
            //			ParseKeywords=true;
            SyntaxDocument doc          = Document;
            Row            Row          = doc[index];
            Span           oldEndSpan   = Row.endSpan;
            Span           oldStartSpan = Row.startSpan;
            bool           Fold         = !Row.IsCollapsed;


            if (Row.IsCollapsedEndPart)
            {
                //Row.expansion_EndSpan.Expanded = true;
                //Row.expansion_EndSpan.EndRow = null;
                Row.expansion_EndSpan.EndWord = null;
            }


            //set startsegment for this row
            if (index > 0)
            {
                Row.startSpan = Document[index - 1].endSpan;
            }
            else
            {
                if (Row.startSpan == null)
                {
                    Row.startSpan = new Span(Row)
                    {
                        spanDefinition = mSyntaxDefinition.mainSpanDefinition
                    };
                }
            }

            int  CurrentPosition = 0;
            Span currentSpan     = Row.startSpan;


            //kör tills vi kommit till slutet av raden..
            Row.endSpans.Clear();
            Row.startSpans.Clear();
            Row.Clear();
            //		bool HasEndSegment=false;

            while (true)
            {
                ScanResultSegment ChildSegment = GetNextChildSegment(Row,
                                                                     currentSpan, CurrentPosition);
                ScanResultSegment EndSegment = GetEndSegment(Row, currentSpan,
                                                             CurrentPosition);

                if ((EndSegment.HasContent && ChildSegment.HasContent &&
                     EndSegment.Position <= ChildSegment.Position) ||
                    (EndSegment.HasContent && ChildSegment.HasContent == false))
                {
                    //this is an end span

                    if (ParseKeywords)
                    {
                        string Text = Row.Text.Substring(CurrentPosition,
                                                         EndSegment.Position - CurrentPosition);
                        ParseText(Row, currentSpan, Text);
                    }

                    Span oldseg = currentSpan;
                    while (currentSpan != EndSegment.span)
                    {
                        Row.endSpans.Add(currentSpan);
                        currentSpan = currentSpan.Parent;
                    }
                    Row.endSpans.Add(currentSpan);

                    TextStyle st2 = currentSpan.Scope.Style;

                    ParseTools.AddPatternString(EndSegment.Token, Row, EndSegment.Pattern,
                                                st2, currentSpan, false);
                    while (oldseg != EndSegment.span)
                    {
                        oldseg.EndRow  = Row;
                        oldseg.EndWord = Row[Row.Count - 1];
                        oldseg         = oldseg.Parent;
                    }

                    currentSpan.EndRow  = Row;
                    currentSpan.EndWord = Row[Row.Count - 1];


                    if (currentSpan.Parent != null)
                    {
                        currentSpan = currentSpan.Parent;
                    }

                    CurrentPosition = EndSegment.Position + EndSegment.Token.Length;
                }
                else if (ChildSegment.HasContent)
                {
                    //this is a child block

                    if (ParseKeywords)
                    {
                        string Text = Row.Text.Substring(CurrentPosition,
                                                         ChildSegment.Position - CurrentPosition);
                        //TextStyle st=currentSpan.spanDefinition.Style;
                        ParseText(Row, currentSpan, Text);
                        //ParseTools.AddString (Text,Row,st,currentSpan);
                    }


                    var NewSeg = new Span
                    {
                        Parent         = currentSpan,
                        spanDefinition = ChildSegment.spanDefinition,
                        Scope          = ChildSegment.Scope
                    };

                    Row.startSpans.Add(NewSeg);

                    TextStyle st2 = NewSeg.Scope.Style;
                    ParseTools.AddPatternString(ChildSegment.Token, Row,
                                                ChildSegment.Pattern, st2, NewSeg, false);
                    NewSeg.StartRow  = Row;
                    NewSeg.StartWord = Row[Row.Count - 1];


                    currentSpan     = NewSeg;
                    CurrentPosition = ChildSegment.Position + ChildSegment.Token.Length;

                    if (ChildSegment.Scope.spawnSpanOnStart != null)
                    {
                        var SpawnSeg = new Span
                        {
                            Parent         = NewSeg,
                            spanDefinition = ChildSegment.Scope.spawnSpanOnStart,
                            Scope          = new Scope(),
                            StartWord      = NewSeg.StartWord
                        };
                        Row.startSpans.Add(SpawnSeg);
                        currentSpan = SpawnSeg;
                    }
                }
                else
                {
                    if (CurrentPosition < Row.Text.Length)
                    {
                        if (ParseKeywords)
                        {
                            //we did not find a childblock nor an endblock , just output the last pice of text
                            string Text = Row.Text.Substring(CurrentPosition);
                            //TextStyle st=currentSpan.spanDefinition.Style;
                            ParseText(Row, currentSpan, Text);
                            //ParseTools.AddString (Text,Row,st,currentSpan);
                        }
                    }
                    break;
                }
            }

            while (!currentSpan.spanDefinition.MultiLine)
            {
                Row.endSpans.Add(currentSpan);
                currentSpan = currentSpan.Parent;
            }

            Row.endSpan = currentSpan;
            Row.SetExpansionSegment();

            Row.RowState = ParseKeywords ? RowState.AllParsed : RowState.SpanParsed;

            if (IsSameButDifferent(index, oldStartSpan))
            {
                MakeSame(index);
                //if (!IsSameButDifferent(index))
                //	System.Diagnostics.Debugger.Break();
            }

            if (Row.CanFold)
            {
                Row.expansion_StartSpan.Expanded = Fold;
            }

            //dont flag next line as needs parsing if only parsing keywords
            if (!ParseKeywords)
            {
                if (oldEndSpan != null)
                {
                    if (Row.endSpan != oldEndSpan && index <= Document.Count - 2)
                    {
                        //if (Row.CanFold)
                        //	Row.expansion_StartSpan.Expanded = true;
                        Document[index + 1].AddToParseQueue();
                        Document.NeedResetRows = true;
                    }
                }
                else if (index <= Document.Count - 2)
                {
                    //if (Row.CanFold)
                    //	Row.expansion_StartSpan.Expanded = true;
                    Document[index + 1].AddToParseQueue();
                    Document.NeedResetRows = true;
                }
            }

            if (oldEndSpan != null)
            {
                //expand span if this line dont have an end word
                if (oldEndSpan.EndWord == null)
                {
                    oldEndSpan.Expanded = true;
                }
            }
        }
Beispiel #48
0
        private void GeneralTab()
        {
            Text.GuiBold("Profile");

            EditorGUILayout.HelpBox("The three following buttons show your current level of obfuscation.\nAdditionally you can press on of those to activate a predefined obfuscation profile.", MessageType.Info);

            GUILayout.BeginHorizontal();
            GUILayout.FlexibleSpace();

            int  var_SecurityLevel    = this.securityLevel;
            bool var_Profile_Simple   = false;
            bool var_Profile_Standard = false;
            bool var_Profile_Optimal  = false;

            if (var_SecurityLevel == 1)
            {
                var_Profile_Simple = true;
            }
            if (var_SecurityLevel == 2)
            {
                var_Profile_Standard = true;
            }
            if (var_SecurityLevel == 3)
            {
                var_Profile_Optimal = true;
            }

            if (Switch.GuiNoRef(var_Profile_Simple, "Assets/OPS/Obfuscator.Free/Editor/Gui/Profile_Simple.png", "Assets/OPS/Obfuscator.Free/Editor/Gui/Profile_Simple_Unselect.png"))
            {
                this.securityLevel = 1;
            }
            if (Switch.GuiNoRef(var_Profile_Standard, "Assets/OPS/Obfuscator.Free/Editor/Gui/Profile_Standard.png", "Assets/OPS/Obfuscator.Free/Editor/Gui/Profile_Standard_Unselect.png"))
            {
                this.securityLevel = 2;
            }
            if (Obfuscator.Setting.InternalSettings.ObfuscatorType != Setting.EObfuscatorType.Pro)
            {
                GUI.enabled = false;
            }
            if (Switch.GuiNoRef(var_Profile_Optimal, "Assets/OPS/Obfuscator.Free/Editor/Gui/Profile_Optimal.png", "Assets/OPS/Obfuscator.Free/Editor/Gui/Profile_Optimal_Unselect.png"))
            {
                this.securityLevel = 3;
            }
            GUI.enabled = Gui.GuiSettings.ObfuscateGlobally;

            GUILayout.FlexibleSpace();
            GUILayout.EndHorizontal();

            Text.GuiBold("Obfuscation");

            EditorGUILayout.HelpBox("Define here generally what names shall get obfuscated!", MessageType.Info);

            Table.Gui("Obfuscate:", "Class", "Field", "Property", "Event", "Method", ref Gui.GuiSettings.ObfuscateClass, ref Gui.GuiSettings.ObfuscateField, ref Gui.GuiSettings.ObfuscateProperty, ref Gui.GuiSettings.ObfuscateEvent, ref Gui.GuiSettings.ObfuscateMethod);

            Text.GuiBold("Namespace");

            if (Obfuscator.Setting.InternalSettings.ObfuscatorType != Setting.EObfuscatorType.Pro)
            {
                GUI.enabled = false;
            }
            EditorGUILayout.HelpBox("Define here generally if namespace names shall get obfuscated.", MessageType.Info);
            Row.GuiGold("Namespace:", ref GuiSettings.ObfuscateNamespace);
            GUI.enabled = Gui.GuiSettings.ObfuscateGlobally;

            EditorGUILayout.HelpBox("To make Obfuscator Free ignore easily some Namespaces, enter it here. All Namespaces beginning like your entered one will get ignored. (Example the entry: 'UnityStandardAssets'. All Namespaces beginning with 'UnityStandardAssets' will get ignored (and so it's Content)).", MessageType.Info);

            //
            ScriptableObject   var_Target           = this;
            SerializedObject   var_SerializedObject = new SerializedObject(var_Target);
            SerializedProperty var_StringsProperty  = var_SerializedObject.FindProperty("NamespaceArray");

            EditorGUILayout.PropertyField(var_StringsProperty, new GUIContent("Namespaces"), true);
            var_SerializedObject.ApplyModifiedProperties();

            GUILayout.BeginHorizontal();
            if (GUILayout.Button("Add Line"))
            {
                List <String> var_TempList = new List <string>(this.NamespaceArray);
                var_TempList.Add("");
                this.NamespaceArray = var_TempList.ToArray();
            }
            if (GUILayout.Button("Remove Line"))
            {
                List <String> var_TempList = new List <string>(this.NamespaceArray);
                if (var_TempList.Count > 0)
                {
                    var_TempList.RemoveAt(var_TempList.Count - 1);
                }
                this.NamespaceArray = var_TempList.ToArray();
            }
            GUILayout.EndHorizontal();

            GuiSettings.NamespacesToIgnoreList = new List <string>(this.NamespaceArray);
            //

            EditorGUILayout.HelpBox("When you activate 'Vice Versa Namespace skipping', every content (class/methods/..) belonging to a namespace that is in the bottom list gets obfuscated. Every namespace that is not in the list will get skipped. The advantage is, if you use many external plugins that shall get skipped while obfuscation and you only want your namespaces to get obfuscated, it reduces your administration effort.", MessageType.Info);
            Row.Gui("Vice Versa Namespace skipping:", ref GuiSettings.NamespaceViceVersa);
        }
Beispiel #49
0
        public override Task WriteResponseBodyAsync(OutputFormatterWriteContext context, Encoding selectedEncoding)
        {
            var query = (IQueryable)context.Object;

            var queryString = context.HttpContext.Request.QueryString;
            var columns     = queryString.Value.Contains("$select") ?
                              OutputFormatter.GetPropertiesFromSelect(queryString.Value, query.ElementType) :
                              OutputFormatter.GetProperties(query.ElementType);


            var stream = new MemoryStream();

            using (var document = SpreadsheetDocument.Create(stream, SpreadsheetDocumentType.Workbook))
            {
                var workbookPart = document.AddWorkbookPart();
                workbookPart.Workbook = new Workbook();

                var worksheetPart = workbookPart.AddNewPart <WorksheetPart>();
                worksheetPart.Worksheet = new Worksheet();

                var workbookStylesPart = workbookPart.AddNewPart <WorkbookStylesPart>();
                GenerateWorkbookStylesPartContent(workbookStylesPart);

                var sheets = workbookPart.Workbook.AppendChild(new Sheets());
                var sheet  = new Sheet()
                {
                    Id = workbookPart.GetIdOfPart(worksheetPart), SheetId = 1, Name = "Sheet1"
                };
                sheets.Append(sheet);

                workbookPart.Workbook.Save();

                var sheetData = worksheetPart.Worksheet.AppendChild(new SheetData());

                var headerRow = new Row();

                foreach (var column in columns)
                {
                    headerRow.Append(new Cell()
                    {
                        CellValue = new CellValue(column.Key),
                        DataType  = new EnumValue <CellValues>(CellValues.String)
                    });
                }

                sheetData.AppendChild(headerRow);

                foreach (var item in query)
                {
                    var row = new Row();

                    foreach (var column in columns)
                    {
                        var value       = OutputFormatter.GetValue(item, column.Key);
                        var stringValue = $"{value}".Trim();

                        var cell = new Cell();

                        var underlyingType = column.Value.IsGenericType &&
                                             column.Value.GetGenericTypeDefinition() == typeof(Nullable <>) ?
                                             Nullable.GetUnderlyingType(column.Value) : column.Value;

                        var typeCode = Type.GetTypeCode(underlyingType);

                        if (typeCode == TypeCode.DateTime)
                        {
                            if (stringValue != string.Empty)
                            {
                                cell.CellValue = new CellValue()
                                {
                                    Text = DateTime.Parse(stringValue).ToOADate().ToString()
                                };
                                cell.StyleIndex = (UInt32Value)1U;
                            }
                        }
                        else if (typeCode == TypeCode.Boolean)
                        {
                            cell.CellValue = new CellValue(stringValue.ToLower());
                            cell.DataType  = new EnumValue <CellValues>(CellValues.Boolean);
                        }
                        else if (IsNumeric(typeCode))
                        {
                            cell.CellValue = new CellValue(stringValue);
                            cell.DataType  = new EnumValue <CellValues>(CellValues.Number);
                        }
                        else
                        {
                            cell.CellValue = new CellValue(stringValue);
                            cell.DataType  = new EnumValue <CellValues>(CellValues.String);
                        }

                        row.Append(cell);
                    }

                    sheetData.AppendChild(row);
                }


                workbookPart.Workbook.Save();
            }

            if (stream?.Length > 0)
            {
                stream.Seek(0, SeekOrigin.Begin);
            }

            return(stream.CopyToAsync(context.HttpContext.Response.Body));
        }
        private ScanResultSegment GetEndSegment(Row Row, Span currentSpan,
                                                int StartPos)
        {
            //this row has no text , just bail out...
            //VVV
            //if (StartPos >= Row.Text.Length || currentSpan.Scope == null)
            if (StartPos > Row.Text.Length || currentSpan.Scope == null)
            {
                return(new ScanResultSegment());
            }

            var Result = new ScanResultSegment {
                HasContent = false, IsEndSegment = false
            };


            //--------------------------------------------------------------------------------
            //scan for childblocks
            //scan each scope in each childblock

            Span seg = currentSpan;

            while (seg != null)
            {
                if (seg == currentSpan || seg.spanDefinition.TerminateChildren)
                {
                    foreach (Pattern end in seg.Scope.EndPatterns)
                    {
                        PatternScanResult psr = end.IndexIn(Row.Text, StartPos,
                                                            seg.Scope.CaseSensitive, Separators);
                        int CurrentPosition = psr.Index;
                        //if (psr.Token != "")
                        if ((end.IsComplex && psr.Index >= 0) || (!end.IsComplex && !string.IsNullOrEmpty(psr.Token))) //VVV - allow empty match for complex (regex) end
                        {
                            //if ((psr.Index < Result.Position && Result.HasContent) ||
                            //   !Result.HasContent)
                            if (!Result.HasContent || psr.Index < Result.Position)
                            {
                                //we found a better match
                                //store this new match
                                Result.Pattern    = end;
                                Result.Position   = CurrentPosition;
                                Result.Token      = psr.Token;
                                Result.HasContent = true;
                                Result.span       = seg;
                                Result.Scope      = null;


                                if (!end.IsComplex)
                                {
                                    if (seg.Scope.NormalizeCase)
                                    {
                                        if (!seg.Scope.Start.IsComplex)
                                        {
                                            Result.Token = end.StringPattern;
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
                seg = seg.Parent;
            }

            //no result , return new ScanResultSegment();
            if (!Result.HasContent)
            {
                return(new ScanResultSegment());
            }

            return(Result);
        }
Beispiel #51
0
 public Obstacles(Row row, DataTable datatable) : base(row, datatable)
 {
     LoadData(this, GetType(), row);
 }
Beispiel #52
0
 private static void SetProperty <T>(T obj, PropertyInfo property, object value, string columnName, Type type, Table table, Row row)
 {
     try
     {
         property.SetValue(obj, value, null);
     }
     catch (Exception e)
     {
         throw new ConfigException(e, "M_Fixture_Temp_ObjectFactory_SetProperty", columnName, type, table, row, value);
     }
 }
Beispiel #53
0
 public Construction_Item(Row row, DataTable dt) : base(row, dt)
 {
 }
        public void Primer()
        {
            Document        doc     = new Document();
            DocumentBuilder builder = new DocumentBuilder(doc);

            Section   currentSection = builder.CurrentSection;
            PageSetup pageSetup      = currentSection.PageSetup;

            // Specify if we want headers/footers of the first page to be different from other pages.
            // You can also use PageSetup.OddAndEvenPagesHeaderFooter property to specify
            // different headers/footers for odd and even pages.
            pageSetup.DifferentFirstPageHeaderFooter = true;

            // --- Create header for the first page. ---
            pageSetup.HeaderDistance = 20;
            builder.MoveToHeaderFooter(HeaderFooterType.HeaderFirst);
            builder.ParagraphFormat.Alignment = ParagraphAlignment.Center;

            // Set font properties for header text.
            builder.Font.Name = "Arial";
            builder.Font.Bold = true;
            builder.Font.Size = 14;
            // Specify header title for the first page.
            builder.Write("Aspose.Words Header/Footer Creation Primer - Title Page.");

            // --- Create header for pages other than first. ---
            pageSetup.HeaderDistance = 20;
            builder.MoveToHeaderFooter(HeaderFooterType.HeaderPrimary);

            // Insert absolutely positioned image into the top/left corner of the header.
            // Distance from the top/left edges of the page is set to 10 points.
            string imageFileName = ImageDir + "Aspose.Words.gif";

            builder.InsertImage(imageFileName, RelativeHorizontalPosition.Page, 10, RelativeVerticalPosition.Page, 10,
                                50, 50, WrapType.Through);

            builder.ParagraphFormat.Alignment = ParagraphAlignment.Right;
            // Specify another header title for other pages.
            builder.Write("Aspose.Words Header/Footer Creation Primer.");

            // --- Create footer for pages other than first. ---
            builder.MoveToHeaderFooter(HeaderFooterType.FooterPrimary);

            // We use table with two cells to make one part of the text on the line (with page numbering)
            // to be aligned left, and the other part of the text (with copyright) to be aligned right.
            builder.StartTable();

            // Clear table borders.
            builder.CellFormat.ClearFormatting();

            builder.InsertCell();

            // Set first cell to 1/3 of the page width.
            builder.CellFormat.PreferredWidth = PreferredWidth.FromPercent(100.0F / 3);

            // Insert page numbering text here.
            // It uses PAGE and NUMPAGES fields to auto calculate current page number and total number of pages.
            builder.Write("Page ");
            builder.InsertField("PAGE", "");
            builder.Write(" of ");
            builder.InsertField("NUMPAGES", "");

            // Align this text to the left.
            builder.CurrentParagraph.ParagraphFormat.Alignment = ParagraphAlignment.Left;

            builder.InsertCell();
            // Set the second cell to 2/3 of the page width.
            builder.CellFormat.PreferredWidth = PreferredWidth.FromPercent(100.0F * 2 / 3);

            builder.Write("(C) 2001 Aspose Pty Ltd. All rights reserved.");

            // Align this text to the right.
            builder.CurrentParagraph.ParagraphFormat.Alignment = ParagraphAlignment.Right;

            builder.EndRow();
            builder.EndTable();

            builder.MoveToDocumentEnd();
            // Make page break to create a second page on which the primary headers/footers will be seen.
            builder.InsertBreak(BreakType.PageBreak);

            // Make section break to create a third page with different page orientation.
            builder.InsertBreak(BreakType.SectionBreakNewPage);

            // Get the new section and its page setup.
            currentSection = builder.CurrentSection;
            pageSetup      = currentSection.PageSetup;

            // Set page orientation of the new section to landscape.
            pageSetup.Orientation = Orientation.Landscape;

            // This section does not need different first page header/footer.
            // We need only one title page in the document and the header/footer for this page
            // has already been defined in the previous section
            pageSetup.DifferentFirstPageHeaderFooter = false;

            // This section displays headers/footers from the previous section by default.
            // Call currentSection.HeadersFooters.LinkToPrevious(false) to cancel this.
            // Page width is different for the new section and therefore we need to set
            // a different cell widths for a footer table.
            currentSection.HeadersFooters.LinkToPrevious(false);

            // If we want to use the already existing header/footer set for this section
            // but with some minor modifications then it may be expedient to copy headers/footers
            // from the previous section and apply the necessary modifications where we want them.
            CopyHeadersFootersFromPreviousSection(currentSection);

            // Find the footer that we want to change.
            HeaderFooter primaryFooter = currentSection.HeadersFooters[HeaderFooterType.FooterPrimary];

            Row row = primaryFooter.Tables[0].FirstRow;

            row.FirstCell.CellFormat.PreferredWidth = PreferredWidth.FromPercent(100.0F / 3);
            row.LastCell.CellFormat.PreferredWidth  = PreferredWidth.FromPercent(100.0F * 2 / 3);

            // Save the resulting document.
            doc.Save(ArtifactsDir + "HeaderFooter.Primer.doc");
        }
        public override string Import(List <IRowStream> Rows)
        {
            if (mOption.Action == ImportAction.InsertOrUpdate)
            {
                StringBuilder sb_log = new StringBuilder();

                //加入 社長/副社長
                List <CLUBRecord> ClubUpdateList = new List <CLUBRecord>();

                //加入 其他社團幹部
                List <CadresRecord> CadreInsertList = new List <CadresRecord>();

                //取得學號對應ID
                List <string> studentNumber = new List <string>();
                foreach (IRowStream Row in Rows)
                {
                    string StudentNumber = Row.GetValue("學號");
                    if (!studentNumber.Contains(StudentNumber))
                    {
                        studentNumber.Add(StudentNumber);
                    }
                }

                Importbot.GetStudentIDList(studentNumber);

                foreach (IRowStream Row in Rows)
                {
                    //教師名稱
                    string SchoolYear    = Row.GetValue("學年度");
                    string Semester      = Row.GetValue("學期");
                    string CLUBName      = Row.GetValue("社團名稱");
                    string CadreName     = Row.GetValue("幹部名稱");
                    string StudentNumber = Row.GetValue("學號");

                    string name = SchoolYear + "," + Semester + "," + CLUBName;
                    if (Importbot.ClubDic.ContainsKey(name))
                    {
                        CLUBRecord record = Importbot.ClubDic[name];

                        if (Importbot.StudentDic.ContainsKey(StudentNumber))
                        {
                            StudDe stud = Importbot.StudentDic[StudentNumber];

                            if (CadreName == "社長")
                            {
                                if (record.President != stud.id)
                                {
                                    record.President = stud.id;
                                    ClubUpdateList.Add(record);
                                    sb_log.AppendLine(string.Format("學年度「{0}」學期「{1}」社團名稱「{2}」", SchoolYear, Semester, CLUBName));
                                    sb_log.AppendLine(string.Format("班級「{0}」座號「{1}」姓名「{2}」幹部名稱「{3}」", stud.ClassName, stud.seat_no, stud.Name, CadreName));
                                    sb_log.AppendLine("");
                                }
                                else
                                {
                                    sb_log.AppendLine(string.Format("學年度「{0}」學期「{1}」社團名稱「{2}」", SchoolYear, Semester, CLUBName));
                                    sb_log.AppendLine(string.Format("學生「{0}」已是社長(未調整)", stud.Name));
                                    sb_log.AppendLine("");
                                }
                            }
                            else if (CadreName == "副社長")
                            {
                                if (record.VicePresident != stud.id)
                                {
                                    record.VicePresident = stud.id;
                                    ClubUpdateList.Add(record);

                                    sb_log.AppendLine(string.Format("學年度「{0}」學期「{1}」社團名稱「{2}」", SchoolYear, Semester, CLUBName));
                                    sb_log.AppendLine(string.Format("班級「{0}」座號「{1}」姓名「{2}」幹部名稱「{3}」", stud.ClassName, stud.seat_no, stud.Name, CadreName));
                                    sb_log.AppendLine("");
                                }
                                else
                                {
                                    sb_log.AppendLine(string.Format("學年度「{0}」學期「{1}」社團名稱「{2}」", SchoolYear, Semester, CLUBName));
                                    sb_log.AppendLine(string.Format("學生「{0}」已是副社長(未調整)", stud.Name));
                                    sb_log.AppendLine("");
                                }
                            }
                            else
                            {
                                //其他幹部直接新增
                                CadresRecord cadres = new CadresRecord();
                                cadres.CadreName    = CadreName;
                                cadres.RefClubID    = record.UID;
                                cadres.RefStudentID = stud.id;

                                CadreInsertList.Add(cadres);

                                sb_log.AppendLine(string.Format("學年度「{0}」學期「{1}」社團名稱「{2}」", SchoolYear, Semester, CLUBName));
                                sb_log.AppendLine(string.Format("班級「{0}」座號「{1}」姓名「{2}」幹部名稱「{3}」", stud.ClassName, stud.seat_no, stud.Name, CadreName));
                                sb_log.AppendLine("");
                            }
                        }
                    }
                }

                if (ClubUpdateList.Count > 0)
                {
                    tool._A.UpdateValues(ClubUpdateList);
                }

                if (CadreInsertList.Count > 0)
                {
                    tool._A.InsertValues(CadreInsertList);
                }

                if (ClubUpdateList.Count > 0 || CadreInsertList.Count > 0)
                {
                    FISCA.LogAgent.ApplicationLog.Log("社團", "匯入社團幹部", sb_log.ToString());
                }
            }

            return("");
        }
Beispiel #56
0
 public RowAddedEventArgs(Row row, int position)
 {
     Row      = row;
     Position = position;
 }
            public override void JoinRow(ToolStrip toolStripToDrag, Point locationToDrag)
            {
                Debug.WriteLineIf(ToolStripPanelMouseDebug.TraceVerbose, "Horizontal JoinRow called ");
                int index;

                if (!Row.ControlsInternal.Contains(toolStripToDrag))
                {
                    Row.SuspendLayout();

                    try
                    {
                        if (Row.ControlsInternal.Count > 0)
                        {
                            // walk through the columns and determine which column you want to insert into.
                            for (index = 0; index < Row.Cells.Count; index++)
                            {
                                ToolStripPanelCell cell = Row.Cells[index] as ToolStripPanelCell;
                                if (!cell.Visible && !cell.ControlInDesignMode)
                                {
                                    continue;
                                }

                                //  [:   ]  [: x  ]
                                if (Row.Cells[index].Bounds.Contains(locationToDrag))
                                {
                                    break;
                                }

                                // take into account the following scenarios
                                //  [:   ]  x [:   ]
                                // x [:  ]    [:   ]
                                if (Row.Cells[index].Bounds.X >= locationToDrag.X)
                                {
                                    break;
                                }
                            }

                            Control controlToPushAside = Row.ControlsInternal[index];
                            // Plop the new control in the midst of the row in question.
                            if (index < Row.ControlsInternal.Count)
                            {
                                Row.ControlsInternal.Insert(index, toolStripToDrag);
                            }
                            else
                            {
                                Row.ControlsInternal.Add(toolStripToDrag);
                            }

                            // since layout is suspended the control may not be set to its preferred size yet
                            int controlToDragWidth = (toolStripToDrag.AutoSize) ? toolStripToDrag.PreferredSize.Width : toolStripToDrag.Width;

                            //
                            // now make it look like it belongs in the row.
                            //
                            // PUSH the controls after it to the right

                            int requiredSpace = controlToDragWidth;
                            if (index == 0)
                            {
                                // make sure we account for the left side
                                requiredSpace += locationToDrag.X;
                            }
                            int freedSpace = 0;

                            if (index < Row.ControlsInternal.Count - 1)
                            {
                                ToolStripPanelCell nextCell       = (ToolStripPanelCell)Row.Cells[index + 1];
                                Padding            nextCellMargin = nextCell.Margin;

                                // if we've already got the empty space
                                // (available to us via the margin) use that.
                                if (nextCellMargin.Left > requiredSpace)
                                {
                                    nextCellMargin.Left -= requiredSpace;
                                    nextCell.Margin      = nextCellMargin;
                                    freedSpace           = requiredSpace;
                                }
                                else
                                {
                                    // otherwise we've got to
                                    // push all controls after this point to the right
                                    // this dumps the extra stuff into the margin of index+1
                                    freedSpace = MoveRight(index + 1, requiredSpace - freedSpace);

                                    // refetch the margin for "index+1" and remove the freed space
                                    // from it - we want to actually put this to use on the control
                                    // before this one - we're making room for the control at
                                    // position "index"
                                    if (freedSpace > 0)
                                    {
                                        nextCellMargin      = nextCell.Margin;
                                        nextCellMargin.Left = Math.Max(0, nextCellMargin.Left - freedSpace);
                                        nextCell.Margin     = nextCellMargin;
                                    }
                                }
                            }
                            else
                            {
                                // we're adding to the end.
                                ToolStripPanelCell nextCell = GetNextVisibleCell(Row.Cells.Count - 2, /*forward*/ false);
                                ToolStripPanelCell lastCell = GetNextVisibleCell(Row.Cells.Count - 1, /*forward*/ false);

                                // count the stuff at the end of the row as freed space
                                if (nextCell != null && lastCell != null)
                                {
                                    Padding lastCellMargin = lastCell.Margin;
                                    lastCellMargin.Left = Math.Max(0, locationToDrag.X - nextCell.Bounds.Right);
                                    lastCell.Margin     = lastCellMargin;
                                    freedSpace          = requiredSpace;
                                }
                            }

                            // If we still need more space, then...
                            // PUSH the controls before it to the left
                            if (freedSpace < requiredSpace && index > 0)
                            {
                                freedSpace = MoveLeft(index - 1, requiredSpace - freedSpace);
                            }

                            if (index == 0)
                            {
                                // if the index is zero and there were controls in the row
                                // we need to take care of pushing over the new cell.
                                if (freedSpace - controlToDragWidth > 0)
                                {
                                    ToolStripPanelCell newCell       = Row.Cells[index] as ToolStripPanelCell;
                                    Padding            newCellMargin = newCell.Margin;
                                    newCellMargin.Left = freedSpace - controlToDragWidth;
                                    newCell.Margin     = newCellMargin;
                                }
                            }
                        }
                        else
                        {
                            // we're adding to the beginning.
                            Row.ControlsInternal.Add(toolStripToDrag);

#if DEBUG
                            ISupportToolStripPanel ctg         = toolStripToDrag as ISupportToolStripPanel;
                            ToolStripPanelRow      newPanelRow = ctg.ToolStripPanelRow;
                            Debug.Assert(newPanelRow == Row, "we should now be in the new panel row.");
#endif
                            if (Row.Cells.Count > 0 || toolStripToDrag.IsInDesignMode)
                            {
                                // we're adding to the beginning.
                                ToolStripPanelCell cell = GetNextVisibleCell(Row.Cells.Count - 1, /*forward*/ false);
                                if (cell is null && toolStripToDrag.IsInDesignMode)
                                {
                                    cell = (ToolStripPanelCell)Row.Cells[Row.Cells.Count - 1];
                                }

                                if (cell != null)
                                {
                                    Padding cellMargin = cell.Margin;
                                    cellMargin.Left = Math.Max(0, locationToDrag.X - Row.Margin.Left);
                                    cell.Margin     = cellMargin;
                                }
                            }
                        }
                    }
                    finally
                    {
                        Row.ResumeLayout(true);
                    }
                }
            }
Beispiel #58
0
        internal void Display()
        {
            Console.CursorLeft = 0;

            const int HEIGHT_MINUS = 7;
            var       cursorMax    = Console.CursorTop + Console.WindowHeight - HEIGHT_MINUS;
            bool      showAll      = false;
            bool      showEnd      = false;

            Console.CursorVisible = false;
            try {
                while (true)
                {
                    var displayInfo = GetNext();
                    if (displayInfo == null)
                    {
                        showEnd = true;
                        goto ASK_MENU;
                    }

                    // Display row!
                    var cursorTopRow = Console.CursorTop;
                    this.Display(displayInfo);
                    var nbLines = Console.CursorTop - cursorTopRow;

                    var row = new Row(displayInfo, cursorTopRow, nbLines, this.Display);
                    m_Rows.Add(row);

                    // Ask up/down/enter/all/next/quit? (not too often thanks to cursorMax));
                    if (Console.CursorTop < cursorMax)
                    {
                        continue;
                    }

                    cursorMax = Console.CursorTop + Console.WindowHeight - HEIGHT_MINUS;
                    if (showAll)
                    {
                        continue;
                    }
ASK_MENU:
                    bool showMenu = true;
                    var cursorTopMenu = Console.CursorTop;
ASK_MENU_UP_DOWN_ENTER:
                    var choice = ConsoleAskUpDownEnterAllNextQuit(showMenu, showEnd, cursorTopMenu);
                    switch (choice)
                    {
                    case UpDownEnterAllNextQuit.Next:
                        goto SHOW_MORE;

                    case UpDownEnterAllNextQuit.All:
                        showAll = true;
                        goto SHOW_MORE;

                    case UpDownEnterAllNextQuit.Up:
                    case UpDownEnterAllNextQuit.Down:
                    case UpDownEnterAllNextQuit.Enter:
                        UpDownEnterChoice(choice);
                        showMenu = false;
                        goto ASK_MENU_UP_DOWN_ENTER;

                    default:
                        // Quit
                        UnselectRow();
                        SetCursorAfterLastRow();
                        return;
                    }
SHOW_MORE:
                    UnselectRow();
                    SetCursorAfterLastRow();
                    continue;
                }
            } finally {
                Console.CursorVisible = true;
            }
        }
            private int MoveRight(int index, int spaceToFree)
            {
                Debug.WriteLineIf(ToolStripPanelMouseDebug.TraceVerbose, "MoveRight: " + spaceToFree.ToString(CultureInfo.InvariantCulture));
                int freedSpace = 0;

                Row.SuspendLayout();
                try
                {
                    if (spaceToFree == 0 || index < 0 || index >= Row.ControlsInternal.Count)
                    {
                        Debug.WriteLineIf(ToolStripPanelMouseDebug.TraceVerbose, "MoveRight Early EXIT - 0 ");
                        return(0);
                    }

                    ToolStripPanelCell cell;
                    Padding            cellMargin;

                    // remove all margins after this point in the index.
                    for (int i = index + 1; i < Row.Cells.Count; i++)
                    {
                        cell = (ToolStripPanelCell)Row.Cells[i];
                        if (!cell.Visible && !cell.ControlInDesignMode)
                        {
                            continue;
                        }
                        int requiredSpace = spaceToFree - freedSpace;

                        cellMargin = cell.Margin;

                        if (cellMargin.Horizontal >= requiredSpace)
                        {
                            freedSpace += requiredSpace;

                            cellMargin.Left -= requiredSpace;
                            cellMargin.Right = 0;
                            cell.Margin      = cellMargin;
                        }
                        else
                        {
                            freedSpace      += cell.Margin.Horizontal;
                            cellMargin.Left  = 0;
                            cellMargin.Right = 0;
                            cell.Margin      = cellMargin;
                        }

                        break;
                    }

                    // add in the space at the end of the row.
                    if (Row.Cells.Count > 0 && (spaceToFree > freedSpace))
                    {
                        ToolStripPanelCell lastCell = GetNextVisibleCell(Row.Cells.Count - 1, /*forward*/ false);
                        if (lastCell != null)
                        {
                            freedSpace += DisplayRectangle.Right - lastCell.Bounds.Right;
                        }
                        else
                        {
                            freedSpace += DisplayRectangle.Width;
                        }
                    }

                    // set the margin of the control that's moving.
                    if (spaceToFree <= freedSpace)
                    {
                        // add the space we freed to the first guy.
                        cell = GetNextVisibleCell(index, /*forward*/ true);
                        if (cell is null)
                        {
                            cell = Row.Cells[index] as ToolStripPanelCell;
                        }
                        Debug.Assert(cell != null, "Dont expect cell to be null here, what's going on?");

                        if (cell != null)
                        {
                            cellMargin       = cell.Margin;
                            cellMargin.Left += spaceToFree;
                            cell.Margin      = cellMargin;
                        }
                        Debug.WriteLineIf(ToolStripPanelMouseDebug.TraceVerbose, "MoveRight Recovered (Margin only): " + spaceToFree.ToString(CultureInfo.InvariantCulture));
                        return(spaceToFree);
                    }

                    // Now start shrinking.
                    for (int i = index + 1; i < Row.Cells.Count; i++)
                    {
                        cell = (ToolStripPanelCell)Row.Cells[i];
                        if (!cell.Visible && !cell.ControlInDesignMode)
                        {
                            continue;
                        }
                        int requiredSpace = spaceToFree - freedSpace;
                        freedSpace += cell.Shrink(requiredSpace);

                        if (spaceToFree >= freedSpace)
                        {
                            Debug.WriteLineIf(ToolStripPanelMouseDebug.TraceVerbose, "MoveRight Recovered (Shrink): " + spaceToFree.ToString(CultureInfo.InvariantCulture));
                            Row.ResumeLayout(true);
                            return(spaceToFree);
                        }
                    }

                    if (Row.Cells.Count == 1)
                    {
                        cell = GetNextVisibleCell(index, /*forward*/ true);
                        if (cell != null)
                        {
                            cellMargin       = cell.Margin;
                            cellMargin.Left += freedSpace;
                            cell.Margin      = cellMargin;
                        }
                    }
                }
                finally
                {
                    Row.ResumeLayout(true);
                }

                Debug.WriteLineIf(ToolStripPanelMouseDebug.TraceVerbose, "MoveRight Recovered Partial (Shrink): " + freedSpace.ToString(CultureInfo.InvariantCulture));

                return(freedSpace);
            }
Beispiel #60
0
        public void TestExponentialInSheet()
        {
            HSSFWorkbook wb = new HSSFWorkbook();

            wb.CreateSheet("Cash_Flow");

            NPOI.SS.UserModel.Sheet sheet = wb.CreateSheet("Test");
            Row    row     = sheet.CreateRow(0);
            Cell   cell    = row.CreateCell((short)0);
            String formula = null;

            cell.CellFormula = ("1.3E21/3");
            formula          = cell.CellFormula;
            Assert.AreEqual("1.3E+21/3", formula, "Exponential formula string");

            cell.CellFormula = ("-1.3E21/3");
            formula          = cell.CellFormula;
            Assert.AreEqual("-1.3E+21/3", formula, "Exponential formula string");

            cell.CellFormula = ("1322E21/3");
            formula          = cell.CellFormula;
            Assert.AreEqual("1.322E+24/3", formula, "Exponential formula string");

            cell.CellFormula = ("-1322E21/3");
            formula          = cell.CellFormula;
            Assert.AreEqual("-1.322E+24/3", formula, "Exponential formula string");

            cell.CellFormula = ("1.3E1/3");
            formula          = cell.CellFormula;
            Assert.AreEqual("13/3", formula, "Exponential formula string");

            cell.CellFormula = ("-1.3E1/3");
            formula          = cell.CellFormula;
            Assert.AreEqual("-13/3", formula, "Exponential formula string");

            cell.CellFormula = ("1.3E-4/3");
            formula          = cell.CellFormula;
            Assert.AreEqual("0.00013/3", formula, "Exponential formula string");

            cell.CellFormula = ("-1.3E-4/3");
            formula          = cell.CellFormula;
            Assert.AreEqual("-0.00013/3", formula, "Exponential formula string");

            cell.CellFormula = ("13E-15/3");
            formula          = cell.CellFormula;
            Assert.AreEqual("1.3E-14/3", formula, "Exponential formula string");

            cell.CellFormula = ("-13E-15/3");
            formula          = cell.CellFormula;
            Assert.AreEqual("-1.3E-14/3", formula, "Exponential formula string");

            cell.CellFormula = ("1.3E3/3");
            formula          = cell.CellFormula;
            Assert.AreEqual("1300/3", formula, "Exponential formula string");

            cell.CellFormula = ("-1.3E3/3");
            formula          = cell.CellFormula;
            Assert.AreEqual("-1300/3", formula, "Exponential formula string");

            cell.CellFormula = ("1300000000000000/3");
            formula          = cell.CellFormula;
            Assert.AreEqual("1.3E+15/3", formula, "Exponential formula string");

            cell.CellFormula = ("-1300000000000000/3");
            formula          = cell.CellFormula;
            Assert.AreEqual("-1.3E+15/3", formula, "Exponential formula string");

            cell.CellFormula = ("-10E-1/3.1E2*4E3/3E4");
            formula          = cell.CellFormula;
            Assert.AreEqual("-1/310*4000/30000", formula, "Exponential formula string");
        }