예제 #1
0
        public static List <SerialNumbers> GetSerialNumber(DateTime startDate, DateTime endDate)
        {
            List <SerialNumbers> retlist = new List <SerialNumbers>();

            SqlConnection conn = new SqlConnection();

            conn.ConnectionString = _ReadConnectionString;
            try
            {
                conn.Open();
                SqlCommand comm = new SqlCommand("sprocReturnsSerialNumber", conn);
                comm.CommandType = System.Data.CommandType.StoredProcedure;

                comm.Parameters.AddWithValue("@FirstDate", startDate);
                comm.Parameters.AddWithValue("@SecondDate", endDate);
                SqlDataReader dr = comm.ExecuteReader();

                while (dr.Read())
                {
                    SerialNumbers sn = new SerialNumbers();
                    sn.Fill(dr);
                    retlist.Add(sn);
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine(ex.Message);
            }
            finally
            {
                conn.Close();
            }
            return(retlist);
        }
 //!!!matrix: when combining Matrix's be sure the missing values are compatible
 internal void InternalCreateEmptyInstance(IEnumerable <string> rowKeySequence, IEnumerable <string> colKeySequence)
 {
     ColSerialNumbers = new SerialNumbers <string>(colKeySequence);
     _rowKeys         = rowKeySequence.ToList();
     _indexOfRowKey   = RowKeys.Select((key, index) => new { key, index }).ToDictionary(rowKeyAndIndex => rowKeyAndIndex.key, rowKeyAndIndex => rowKeyAndIndex.index);
     CreateEmptyRowKeyToStoreList();
 }
        internal void GetInstanceInternal(string denseStructFileName, ParallelOptions parallelOptions)
        {
            using (TextReader textReader = FileUtils.OpenTextStripComments(denseStructFileName))
            {
                //!!!similar code in mergedense method
                string header = textReader.ReadLine();
                ColSerialNumbers = ColSerialNumbersFromHeader(header, denseStructFileName);

                CounterWithMessages counterWithMessages = new CounterWithMessages("Reading " + denseStructFileName + " {0}", 1000, null, true);

                //We use ReadEachIndexedLine so that we can process the lines out of order (which is fastest) put still recover the original order of the rowKeys
                var indexRowKeyStructListQuery =
                    from lineAndIndex in FileUtils.ReadEachIndexedLine(textReader)//!!!05/18/2009 .AsParallel().WithDegreeOfParallelism(parallelOptions.DegreeOfParallelism)
                    select new { index = lineAndIndex.Value, rowKeyAndStructList = CreateRowKeyAndStructList(lineAndIndex.Key, denseStructFileName, counterWithMessages) };

                RowKeyToStoreList = new Dictionary <string, List <TStore> >(counterWithMessages.Index + 1);
                _indexOfRowKey    = new Dictionary <string, int>();
                foreach (var rowKeyAndStructList in indexRowKeyStructListQuery)
                {
                    RowKeyToStoreList.Add(rowKeyAndStructList.rowKeyAndStructList.Key, rowKeyAndStructList.rowKeyAndStructList.Value);
                    _indexOfRowKey.Add(rowKeyAndStructList.rowKeyAndStructList.Key, rowKeyAndStructList.index);
                }

                _rowKeys =
                    (from rowKeyAndIndex in _indexOfRowKey
                     orderby rowKeyAndIndex.Value
                     select rowKeyAndIndex.Key)
                    .ToList();
            }
        }
예제 #4
0
        public void Refresh()
        {
            loadSerialNumbers();
            validateSerialNumbers();

            IsActivated       = SerialNumbers.Any(p => p.IsValid);
            IsUnlimOrders     = SerialNumbers.Any(p => p.IsUnlimOrders);
            IsExtendedReports = SerialNumbers.Any(p => p.IsExtendedReports);
        }
 internal TokenBurnTransactionBody(Hashgraph.Asset asset) : this()
 {
     if (asset is null || asset == Hashgraph.Asset.None)
     {
         throw new ArgumentOutOfRangeException(nameof(asset), "The asset cannot be null or empty.");
     }
     Token = new TokenID(asset);
     SerialNumbers.Add(asset.SerialNum);
 }
예제 #6
0
 public void TestRecombine()
 {
     Assert.AreEqual(123, SerialNumbers.Recombine(new List <int> {
         1, 2, 3
     }));
     Assert.AreEqual(461235, SerialNumbers.Recombine(new List <int> {
         4, 6, 1, 2, 3, 5
     }));
 }
예제 #7
0
        //!!!similar to GetInstanceFromDenseStructFileNameInternal


        /// <summary>
        /// Get a instance from a file in a RowKeys format
        /// </summary>
        /// <param name="rowKeysStructFileName">The rowKeys file</param>
        /// <param name="parallelOptions">A ParallelOptions instance that configures the multithreaded behavior of this operation.</param>
        /// <param name="fileAccess">A FileAccess value that specifies the operations that can be performed on the file. Defaults to 'Read'</param>
        /// <param name="fileShare">A FileShare value specifying the type of access other threads have to the file. Defaults to 'Read'</param>
        protected void GetInstanceFromRowKeysStructFileNameInternal(string rowKeysStructFileName, ParallelOptions parallelOptions, FileAccess fileAccess = FileAccess.Read, FileShare fileShare = FileShare.Read)
        {
            lock (this)
            {
                string firstLineOrNull = FileUtils.ReadLine(rowKeysStructFileName);
                Helper.CheckCondition(null != firstLineOrNull, "Surprised by empty file. " + rowKeysStructFileName);
                Helper.CheckCondition(!firstLineOrNull.StartsWith(FileUtils.CommentHeader), "Comments are not supported in RowKeysAnsi and related files");


                RowKeyToFilePosition = new Dictionary <string, long>();
                FileAccess           = fileAccess;
                FileShare            = fileShare;


                using (TextReader textReader = File.OpenText(rowKeysStructFileName))
                {
                    string   colKeysLineOrNull = textReader.ReadLine();
                    string[] varAndColKeys     = colKeysLineOrNull.Split('\t');
                    if (!varAndColKeys[0].Equals("rowKey"))
                    {
                        throw new MatrixFormatException("Expect first row's first value to be 'rowKey'"); //!!!rowKey
                    }
                    ColSerialNumbers = new SerialNumbers <string>(varAndColKeys.Skip(1));
                    _rowKeys         = new List <string>();
                    if (null == colKeysLineOrNull)
                    {
                        throw new MatrixFormatException("Surprised by empty file. " + rowKeysStructFileName);
                    }


                    //!!!not really thread-safe
                    string denseStructFileNameInFile = textReader.ReadLine();
                    DenseStructFileName = Path.Combine(Path.GetDirectoryName(rowKeysStructFileName), denseStructFileNameInFile);

                    CounterWithMessages counterWithMessages = new CounterWithMessages("Reading rowKey file to find location of rows, #{0}", 10000, null);

                    string line = null;
                    while (null != (line = textReader.ReadLine()))
                    {
                        counterWithMessages.Increment();
                        string[] rowKeyAndPosition = line.Split('\t');
                        if (rowKeyAndPosition.Length != 2)
                        {
                            throw new MatrixFormatException("Expect rows to have two columns");
                        }
                        string rowKey   = rowKeyAndPosition[0];
                        long   position = long.Parse(rowKeyAndPosition[1]);
                        _rowKeys.Add(rowKey);
                        RowKeyToFilePosition.Add(rowKey, position);
                    }
                }
                Console.WriteLine("all lines read from " + rowKeysStructFileName);

                _indexOfRowKey = RowKeys.Select((key, index) => new { key, index }).ToDictionary(keyAndIndex => keyAndIndex.key, keyAndIndex => keyAndIndex.index);
                ValueTester(rowKeysStructFileName);
            }
        }
예제 #8
0
파일: DataProcess.cs 프로젝트: leeleonis/QD
        public static SerialNumbers SetSerialNumberData(SerialNumbers serialNumber, OrderSerialNumber SerialNumberDetail)
        {
            serialNumber.OrderID      = SerialNumberDetail.OrderID;
            serialNumber.ProductID    = SerialNumberDetail.ProductID.Trim();
            serialNumber.SerialNumber = SerialNumberDetail.SerialNumber.Trim();
            serialNumber.OrderItemID  = SerialNumberDetail.OrderItemID;
            serialNumber.KitItemID    = SerialNumberDetail.KitItemID;

            return(serialNumber);
        }
예제 #9
0
 void saveSerialNumbers()
 {
     try
     {
         File.WriteAllLines(SnPath, SerialNumbers.Select(p => p.Value).ToArray());
     }
     catch
     {
     }
 }
        private static SerialNumbers <string> ColSerialNumbersFromHeader(string headerOrNull, string denseFileNameForErrorMessage)
        {
            //Helper.CheckCondition(null != headerOrNull, "input file must contain a first line. " + denseFileNameForErrorMessage);
            MatrixFormatException.CheckCondition(null != headerOrNull, "input file must contain a first line. " + denseFileNameForErrorMessage);
            string[] columns = headerOrNull.Split('\t');
            //Helper.CheckCondition(columns.Length > 0 && columns[0] == "var", "The first column in the file should be 'var'. " + denseFileNameForErrorMessage);
            MatrixFormatException.CheckCondition(columns.Length > 0 && (columns[0] == "var" || columns[0] == "row"), "The first column in the file should be 'var'. " + denseFileNameForErrorMessage);
            SerialNumbers <string> inputSerialNumbers = new SerialNumbers <string>(columns.Skip(1));

            return(inputSerialNumbers);
        }
예제 #11
0
        void removeSerialNumber(string value)
        {
            var sn = SerialNumbers.FirstOrDefault(p => p.Value == value);

            if (sn == null)
            {
                return;
            }
            SerialNumbers.Remove(sn);
            saveSerialNumbers();
        }
예제 #12
0
        private CredentialsResponse Commit(CredentialsResponse response, long delta, IEnumerable <GroupElement> serialNumbers)
        {
            // Register the serial numbers to prevent credential reuse.
            foreach (var serialNumber in serialNumbers)
            {
                SerialNumbers.Add(serialNumber);
            }
            Balance += delta;

            return(response);
        }
        internal static SerialNumbers <string> ColKeysInFilePattern(string denseStructFilePattern)
        {
            var cidQuery =
                from fileName in FileUtils.GetFiles(denseStructFilePattern, /*zeroIsOK*/ false)
                from colKey in ColKeysInFile(fileName)
                orderby colKey
                select colKey;

            SerialNumbers <string> colSerialNumbers = new SerialNumbers <string>(cidQuery);

            return(colSerialNumbers);
        }
예제 #14
0
 public void TestBreak()
 {
     CollectionAssert.AreEquivalent((ICollection) new List <int> {
         1, 2, 3
     }, (ICollection)SerialNumbers.Break(3, 123));
     CollectionAssert.AreEquivalent((ICollection) new List <int> {
         0, 2, 3, 5
     }, (ICollection)SerialNumbers.Break(4, 235));
     CollectionAssert.AreEquivalent((ICollection) new List <int> {
         4, 6, 1, 2, 3, 5
     }, (ICollection)SerialNumbers.Break(6, 461235));
 }
 internal TokenBurnTransactionBody(Hashgraph.Address asset, IEnumerable <long> serialNumbers) : this()
 {
     if (serialNumbers is null)
     {
         throw new ArgumentOutOfRangeException(nameof(serialNumbers), "The list of serial numbers must not be null.");
     }
     Token = new TokenID(asset);
     SerialNumbers.AddRange(serialNumbers);
     if (SerialNumbers.Count == 0)
     {
         throw new ArgumentOutOfRangeException(nameof(serialNumbers), "The list of serial numbers must not be empty.");
     }
 }
예제 #16
0
        public void TestGenerate()
        {
            SerialNumbers sn = new SerialNumbers(6);
            IList <int>   ev = new List <int> {
                416235
            };

            CollectionAssert.AreEquivalent((ICollection)ev, (ICollection)sn.GenerateNeighbours(461235));
            ev = new List <int> {
                142635, 412365, 416235
            };
            CollectionAssert.AreEquivalent((ICollection)ev, (ICollection)sn.GenerateNeighbours(412635));
        }
예제 #17
0
 void addSerialNumber(string value)
 {
     if (value.IsNullOrEmpty())
     {
         return;
     }
     if (SerialNumbers.Any(p => p.Value == value))
     {
         return;
     }
     SerialNumbers.Add(new SerialNumber(value));
     saveSerialNumbers();
 }
예제 #18
0
        public InstrumentSettingsGroup(long refId, string equipmentCode, IEnumerable <string> serialNumbers, Instrument instrument)
        {
            RefId = refId;

            EquipmentCode = equipmentCode;
            EquipmentType = Device.GetDeviceType(equipmentCode);

            if (serialNumbers != null)
            {
                SerialNumbers.AddRange(serialNumbers);
            }

            Instrument = instrument;
        }
예제 #19
0
 internal TokenWipeAccountTransactionBody(Address token, IEnumerable <long> serialNumbers, AddressOrAlias address) : this()
 {
     if (Hashgraph.Asset.None.Equals(token))
     {
         throw new ArgumentOutOfRangeException(nameof(token), "The asset token type to confiscate is missing.");
     }
     if (Hashgraph.Address.None.Equals(address))
     {
         throw new ArgumentOutOfRangeException(nameof(address), "The account Addresss can not be empty or None.  Please provide a valid value.");
     }
     Token   = new TokenID(token);
     Account = new AccountID(address);
     SerialNumbers.AddRange(serialNumbers);
 }
예제 #20
0
 void loadSerialNumbers()
 {
     try
     {
         var sn = File
                  .ReadLines(SnPath)
                  .Select(p => new SerialNumber(p))
                  .ToList();
         SerialNumbers.ReplaceRange(sn);
     }
     catch
     {
         SerialNumbers.Clear();
     }
 }
예제 #21
0
    public HttpResponseMessage GetSerialNumber(string deviceLibraryIdentifier, string passTypeIdentifier, string passesUpdatedSince)
    {
        // For example...
        SerialNumbers lastUpdateToSerialNumDict = new SerialNumbers();

        // LastUpdated timestamp set to current datetime
        lastUpdateToSerialNumDict.lastUpdated = String.Format("{0:MM/dd/yyyy HH:mm:ss}", DateTime.Now);
        // A list of serial numbers got from database
        lastUpdateToSerialNumDict.serialNumbers = serialNumList;
        string jsonRes = JsonConvert.SerializeObject(lastUpdateToSerialNumDict);
        HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.OK);

        response.Content = new StringContent(jsonRes, Encoding.UTF8, "application/json");
        return(response);
    }
예제 #22
0
        public async Task <ActionResult> Post(PostSerial model)
        {
            try
            {
                var meta = await AppUsers.GetCurrentAsync().ConfigureAwait(true);

                bool result = await SerialNumbers.Post(this.Tenant, meta, model)
                              .ConfigureAwait(true);

                return(this.Ok(result));
            }
            catch (Exception ex)
            {
                return(this.Failed(ex.Message, HttpStatusCode.InternalServerError));
            }
        }
        //Similar code above but doesn't pad out a variable's line until it needs to

        /// <summary>
        /// Create a DenseStructMatrix from a sequences of RowKeyColKeyValue triples.
        /// </summary>
        /// <param name="tripleEnumerable">The squences of RowKeyColKeyValue triples</param>
        public void GetInstanceFromSparseInternal(IEnumerable <RowKeyColKeyValue <string, string, TValue> > tripleEnumerable)
        {
            ColSerialNumbers  = new SerialNumbers <string>();
            RowKeyToStoreList = new Dictionary <string, List <TStore> >();

            foreach (var triple in tripleEnumerable)
            {
                string        rowKey = triple.RowKey;
                List <TStore> storeList;
                if (!RowKeyToStoreList.TryGetValue(rowKey, out storeList))
                {
                    storeList = Enumerable.Repeat(StoreMissingValue, ColSerialNumbers.Count).ToList();
                    RowKeyToStoreList[rowKey] = storeList;
                }

                string colKey = triple.ColKey;
                TValue value  = triple.Value;
                TStore store  = ValueToStore(value);
                Helper.CheckCondition(!store.Equals(StoreMissingValue), () => string.Format(CultureInfo.InvariantCulture, Properties.Resource.ErrorConvertingValGaveMissingValue, value, StoreMissingValue));

                int colIndex = ColSerialNumbers.GetNewOrOld(colKey);
                if (colIndex < storeList.Count)
                {
                    Helper.CheckCondition(storeList[colIndex].Equals(StoreMissingValue), () => string.Format(CultureInfo.InvariantCulture, "Each pair of keys, i,e,.<{0},{1}>, should only be seen once", rowKey, colKey));
                    storeList[colIndex] = store;
                }
                else
                {
                    while (colIndex > storeList.Count)
                    {
                        storeList.Add(StoreMissingValue);
                    }
                    // REVIEW:  is this a bogus check?  Only a failure of storeList.Add could make this not be true
                    Helper.CheckCondition(colIndex == storeList.Count, () => Properties.Resource.RealAssert);
                    storeList.Add(store);
                }
            }

            foreach (var storeList in RowKeyToStoreList.Values)
            {
                storeList.TrimExcess();
            }

            _rowKeys       = RowKeyToStoreList.Keys.ToList();
            _indexOfRowKey = RowKeys.Select((key, index) => new { key, index }).ToDictionary(keyAndIndex => keyAndIndex.key, keyAndIndex => keyAndIndex.index);
        }
예제 #24
0
        //Similar code above but doesn't pad out a variable's line until it needs to

        /// <summary>
        /// Create a DenseStructMatrix from a sequences of RowKeyColKeyValue triples.
        /// </summary>
        /// <param name="tripleEnumerable">The squences of RowKeyColKeyValue triples</param>
        public void GetInstanceFromSparseInternal(IEnumerable <RowKeyColKeyValue <string, string, TValue> > tripleEnumerable)
        {
            ColSerialNumbers  = new SerialNumbers <string>();
            RowKeyToStoreList = new Dictionary <string, List <TStore> >();

            foreach (var triple in tripleEnumerable)
            {
                string        rowKey = triple.RowKey;
                List <TStore> storeList;
                if (!RowKeyToStoreList.TryGetValue(rowKey, out storeList))
                {
                    storeList = Enumerable.Repeat(StoreMissingValue, ColSerialNumbers.Count).ToList();
                    RowKeyToStoreList[rowKey] = storeList;
                }

                string colKey = triple.ColKey;
                TValue value  = triple.Value;
                TStore store  = ValueToStore(value);
                Helper.CheckCondition(!store.Equals(StoreMissingValue), "Vals cannot covert to '" + StoreMissingValue.ToString() + "'");

                int colIndex = ColSerialNumbers.GetNewOrOld(colKey);
                if (colIndex < storeList.Count)
                {
                    storeList[colIndex] = store;
                }
                else
                {
                    while (colIndex > storeList.Count)
                    {
                        storeList.Add(StoreMissingValue);
                    }
                    Helper.CheckCondition(colIndex == storeList.Count, "real assert");
                    storeList.Add(store);
                }
            }

            foreach (var storeList in RowKeyToStoreList.Values)
            {
                storeList.TrimExcess();
            }

            _rowKeys       = RowKeyToStoreList.Keys.ToList();
            _indexOfRowKey = RowKeys.Select((key, index) => new { key, index }).ToDictionary(keyAndIndex => keyAndIndex.key, keyAndIndex => keyAndIndex.index);
        }
예제 #25
0
        public async Task <ResponseModel> Post(object o)
        {
            ResponseModel response;

            try
            {
                AnswerViewModel answer   = JsonConvert.DeserializeObject <AnswerViewModel>(o.ToString());
                IContentService service  = new ContentService(new VirtualtraineesEntities());
                int             quizType = service.GetQuizType(answer);

                bool ok = quizType == 1
                    ? await service.SubmitAnswer(answer, UserModel.Id)
                    : await service.SubmitAssignment(answer, UserModel.Id);

                response = ok ? new ResponseModel() : new ResponseModel(null, false, MessageContainer.AnswerIsWrong);
                if (ok)
                {
                    if (quizType == 1)
                    {
                        SerialNumbers no = await service.GetNo(answer.ContentId);

                        response = await service.UnlockContent(no.ContentNo, no.LevelNo, UserModel.Id);

                        if (!response.IsSuccess)
                        {
                            response = new ResponseModel(null, false, MessageContainer.AllAnswersCorrect + MessageContainer.UnableToUnlock + response.Message);
                        }
                    }
                    else
                    {
                        response = new ResponseModel("Assignment", false, MessageContainer.AssignmentIsSubmitted);
                    }
                }
            }
            catch (Exception exception)
            {
                response = new ResponseModel(isSuccess: false, message: MessageContainer.ErrorOccurred, exception: exception);
            }

            return(response);
        }
        internal void GetInstanceFromSparseInternal(string inputSparsePattern)
        {
            ColSerialNumbers  = new SerialNumbers <string>();
            RowKeyToStoreList = new Dictionary <string, List <TStore> >();

            //!!!05/18/2009 optimize could be made faster with plinq using an index read to keep the order of the rowKeys (aka vars)
            foreach (List <string[]> linesWithSameRowKey in SparseGroupedByVar(inputSparsePattern, /*zeroIsOK*/ false, "File {0}"))
            {
                Debug.Assert(linesWithSameRowKey.Count > 0); // real assert
                string rowKey = linesWithSameRowKey[0][0];

                List <TStore> storeList = Enumerable.Repeat(StoreMissingValue, ColSerialNumbers.Count).ToList();
                RowKeyToStoreList.Add(rowKey, storeList);

                foreach (string[] rowKeyColKeyVal in linesWithSameRowKey)
                {
                    string colKey      = rowKeyColKeyVal[1];
                    string valAsString = rowKeyColKeyVal[2];
                    TStore store       = SparseValToStore(valAsString);
                    Helper.CheckCondition(!store.Equals(StoreMissingValue), () => string.Format(CultureInfo.InvariantCulture, Properties.Resource.ErrorConvertingValGaveMissingValue, valAsString, StoreMissingValue)); //OK to use Equals because TScore can't be null

                    int colIndex = ColSerialNumbers.GetNewOrOld(colKey);
                    if (colIndex < storeList.Count)
                    {
                        Helper.CheckCondition(storeList[colIndex].Equals(StoreMissingValue), () => string.Format(CultureInfo.InvariantCulture, "Each pair of keys, i,e,.<{0},{1}>, should only be seen once", rowKey, colKey));
                        storeList[colIndex] = store;
                    }
                    else
                    {
                        Helper.CheckCondition(colIndex == storeList.Count, () => Properties.Resource.ErrorInputDataShouldBeGroupedByVar);
                        storeList.Add(store);
                    }
                }
                storeList.TrimExcess();
            }

            _rowKeys       = RowKeyToStoreList.Keys.ToList();
            _indexOfRowKey = RowKeys.Select((key, index) => new { key, index }).ToDictionary(keyAndIndex => keyAndIndex.key, keyAndIndex => keyAndIndex.index);
        }
예제 #27
0
        internal void GetInstanceFromSparseInternal(string inputSparsePattern)
        {
            ColSerialNumbers  = new SerialNumbers <string>();
            RowKeyToStoreList = new Dictionary <string, List <TStore> >();

            //!!!05/18/2009 optimize could be made faster with plinq using an index read to keep the order of the rowKeys (aka vars)
            foreach (List <string[]> linesWithSameRowKey in SparseGroupedByVar(inputSparsePattern, /*zeroIsOK*/ false, "File {0}"))
            {
                Debug.Assert(linesWithSameRowKey.Count > 0); // real assert
                string rowKey = linesWithSameRowKey[0][0];

                List <TStore> storeList = Enumerable.Repeat(StoreMissingValue, ColSerialNumbers.Count).ToList();
                RowKeyToStoreList.Add(rowKey, storeList);

                foreach (string[] rowKeyColKeyVal in linesWithSameRowKey)
                {
                    string colKey      = rowKeyColKeyVal[1];
                    string valAsString = rowKeyColKeyVal[2];
                    TStore store       = SparseValToStore(valAsString);
                    Helper.CheckCondition(!store.Equals(StoreMissingValue), "Vals cannot covert to '" + StoreMissingValue.ToString() + "'"); //OK to use Equals because TScore can't be null

                    int colIndex = ColSerialNumbers.GetNewOrOld(colKey);
                    if (colIndex < storeList.Count)
                    {
                        storeList[colIndex] = store;
                    }
                    else
                    {
                        Helper.CheckCondition(colIndex == storeList.Count, "the input data should be grouped by var");
                        storeList.Add(store);
                    }
                }
                storeList.TrimExcess();
            }

            _rowKeys       = RowKeyToStoreList.Keys.ToList();
            _indexOfRowKey = RowKeys.Select((key, index) => new { key, index }).ToDictionary(keyAndIndex => keyAndIndex.key, keyAndIndex => keyAndIndex.index);
        }
예제 #28
0
        public Line(Line pLine)
            : this()
        {
            CopyBy(pLine);

            pLine.BatchNumbes.ForEach(
                b => BatchNumbes.Add(new BatchNumber(b)));

            BatchNumberForDrafts.ForEach(
                b => BatchNumberForDrafts.Add(new BatchNumberBase(b)));

            pLine.WithholdingTaxes.ForEach(
                b => WithholdingTaxes.Add(new DocumentWithholdingTax(b)));

            pLine.SerialNumbers.ForEach(
                b => SerialNumbers.Add(new LineSerialNumber(b)));

            pLine.TaxAmounts.ForEach(
                b => TaxAmounts.Add(new DocumentTaxAmount(b)));

            pLine.AdditionalExpenses.ForEach(
                b => AdditionalExpenses.Add(new DocumentLinesAdditionalExpenses(b)));
        }
        //!!!This seems too specific. Better would be one that returns RowKeyColKeyValue from a file and then that could be changed to string[] outside this class.
        internal static IEnumerable <string[]> EachSparseLine(string filePattern,
                                                              StaticStringToStoreListDelegate staticStringiToStoreListDelegate,
                                                              Converter <TStore, string> StoreToSparseValueDelegate,
                                                              bool zeroIsOK, string fileMessageOrNull, TStore storeMissingValue, CounterWithMessages counterWithMessages)
        {
            foreach (string fileName in FileUtils.GetFiles(filePattern, zeroIsOK))
            {
                if (null != fileMessageOrNull)
                {
                    Console.WriteLine(fileMessageOrNull, fileName);
                }

                using (TextReader textReader = FileUtils.OpenTextStripComments(fileName))
                {
                    string header = textReader.ReadLine();
                    SerialNumbers <string> colSerialNumberCollection = ColSerialNumbersFromHeader(header, fileName);

                    string line;
                    while (null != (line = textReader.ReadLine()))
                    {
                        var           rowKeyAndStructList = CreateRowKeyAndStructList(line, filePattern, colSerialNumberCollection.Count, staticStringiToStoreListDelegate, counterWithMessages);
                        string        rowKey     = rowKeyAndStructList.Key;
                        List <TStore> structList = rowKeyAndStructList.Value;
                        for (int colIndex = 0; colIndex < colSerialNumberCollection.Count; ++colIndex)
                        {
                            TStore store = structList[colIndex];
                            if (!store.Equals(storeMissingValue)) //OK to use Equals because TStore can't be null
                            {
                                string   val         = StoreToSparseValueDelegate(store);
                                string[] stringArray = new string[] { rowKey, colSerialNumberCollection.GetItem(colIndex), val };
                                yield return(stringArray);
                            }
                        }
                    }
                }
            }
        }
예제 #30
0
        protected void GetInstanceFromDenseStructFileNameInternal(string denseStructFileName, ParallelOptions parallelOptions, FileAccess fileAccess = FileAccess.Read, FileShare fileShare = FileShare.Read)
        {
            // parallelOptions is not currently used, but it is need so that this method will have the same signature as other, similar methods.
            lock (this)
            {
                using (FileStream fileStream = File.Open(denseStructFileName, FileMode.Open, fileAccess, fileShare))
                {
                    using (TextReader textReader = new StreamReader(fileStream))
                    {
                        string firstLineOrNull = textReader.ReadLine();
                        Helper.CheckCondition(null != firstLineOrNull, Properties.Resource.ExpectedFileToHaveData, denseStructFileName);
                        Helper.CheckCondition(!firstLineOrNull.StartsWith(FileUtils.CommentHeader, StringComparison.Ordinal), Properties.Resource.ExpectedNoCommentsInRowKeysAnsiFiles, denseStructFileName);
                    }
                }

                RowKeyToFilePosition = new Dictionary <string, long>();

                DenseStructFileName = denseStructFileName;
                FileAccess          = fileAccess;
                FileShare           = fileShare;
                long position = 0;


                string colKeysLineOrNull = ThreadLocalTextReader.ReadLine();
                position += colKeysLineOrNull.Length + 2; //!!!const assuming 2 char newslines
                string[] varAndColKeys = colKeysLineOrNull.Split('\t');
                if (!varAndColKeys[0].Equals("var"))
                {
                    throw new MatrixFormatException("Expect first row's first value to be 'var'");
                }
                ColSerialNumbers = new SerialNumbers <string>(varAndColKeys.Skip(1));
                _rowKeys         = new List <string>();
                if (null == colKeysLineOrNull)
                {
                    throw new MatrixFormatException("Surprised by empty file. " + denseStructFileName);
                }
                CounterWithMessages counterWithMessages = new CounterWithMessages("Reading data file to find location of rows, #{0}", 10000, null);

                while (true)
                {
                    counterWithMessages.Increment();
                    ThreadLocalStream.Position = position;
                    StringBuilder sb = new StringBuilder();
                    while (true)
                    {
                        int i = ThreadLocalStream.ReadByte();
                        if (-1 == i)
                        {
                            goto END;
                        }
                        if ('\t' == (char)i)
                        {
                            break; // real break, not conintue
                        }
                        sb.Append((char)i);
                    }

                    string rowKey = sb.ToString();
                    if (RowKeyToFilePosition.ContainsKey(rowKey))
                    {
                        throw new MatrixFormatException(string.Format(CultureInfo.InvariantCulture, "The rowkey {0} appears more than once", rowKey));
                    }

                    _rowKeys.Add(rowKey);
                    position += rowKey.Length + 1;
                    RowKeyToFilePosition.Add(rowKey, position);
                    position += ColCount * BytesPerValue + 2;//!!!assumes two char newlines
                    if (position > ThreadLocalStream.Length)
                    {
                        throw new MatrixFormatException("File seems too short");
                    }
                }
                END :;

                _indexOfRowKey = RowKeys.Select((key, index) => new { key, index }).ToDictionary(keyAndIndex => keyAndIndex.key, keyAndIndex => keyAndIndex.index);
            }
        }