Ejemplo n.º 1
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Requires({"name != null", "! ( location == null && output == null )", "! ( enableOnTheFlyIndexing && location == null )"}) protected IndexingVariantContextWriter(final String name, final File location, final OutputStream output, final net.sf.samtools.SAMSequenceDictionary refDict, final boolean enableOnTheFlyIndexing)
//JAVA TO C# CONVERTER WARNING: 'final' parameters are not allowed in .NET:
		protected internal IndexingVariantContextWriter(string name, File location, OutputStream output, SAMSequenceDictionary refDict, bool enableOnTheFlyIndexing)
		{
			outputStream = output;
			this.name = name;
			this.refDict = refDict;

			if (enableOnTheFlyIndexing)
			{
				try
				{
					idxStream = new LittleEndianOutputStream(new FileOutputStream(Tribble.indexFile(location)));
					//System.out.println("Creating index on the fly for " + location);
					indexer = new DynamicIndexCreator(IndexFactory.IndexBalanceApproach.FOR_SEEK_TIME);
					indexer.initialize(location, indexer.defaultBinSize());
					positionalOutputStream = new PositionalOutputStream(output);
					outputStream = positionalOutputStream;
				}
				catch (IOException ex)
				{
					// No matter what we keep going, since we don't care if we can't create the index file
					idxStream = null;
					indexer = null;
					positionalOutputStream = null;
				}
			}
		}
Ejemplo n.º 2
0
        public PpmdArchiveDecoder(ImmutableArray<byte> settings, long length)
        {
            if (settings.IsDefault)
                throw new ArgumentNullException(nameof(settings));

            if (settings.Length != 5)
                throw new InvalidDataException();

            if (length < 0)
                throw new ArgumentOutOfRangeException(nameof(length));

            mOutput = new OutputStream(this);
            mLength = length;

            mSettingOrder = settings[0];
            if (mSettingOrder < PPMD.PPMD7_MIN_ORDER || mSettingOrder > PPMD.PPMD7_MAX_ORDER)
                throw new InvalidDataException();

            mSettingMemory = (uint)settings[1] | ((uint)settings[2] << 8) | ((uint)settings[3] << 16) | ((uint)settings[4] << 24);
            if (mSettingMemory < PPMD.PPMD7_MIN_MEM_SIZE || mSettingMemory > PPMD.PPMD7_MAX_MEM_SIZE)
                throw new InvalidDataException();

            mRangeDecoder = new PPMD.CPpmd7z_RangeDec();
            PPMD.Ppmd7z_RangeDec_CreateVTable(mRangeDecoder);
            mRangeDecoder.Stream = new PPMD.IByteIn { Read = x => ReadByte() };

            PPMD.Ppmd7_Construct(mState);
            if (!PPMD.Ppmd7_Alloc(mState, mSettingMemory, mAlloc))
                throw new OutOfMemoryException();
        }
Ejemplo n.º 3
0
//JAVA TO C# CONVERTER WARNING: 'final' parameters are not allowed in .NET:
//ORIGINAL LINE: public VCFWriter(final File location, final OutputStream output, final net.sf.samtools.SAMSequenceDictionary refDict, final boolean enableOnTheFlyIndexing, boolean doNotWriteGenotypes, final boolean allowMissingFieldsInHeader)
		public VCFWriter(File location, OutputStream output, SAMSequenceDictionary refDict, bool enableOnTheFlyIndexing, bool doNotWriteGenotypes, bool allowMissingFieldsInHeader) : base(writerName(location, output), location, output, refDict, enableOnTheFlyIndexing)
		{
			this.doNotWriteGenotypes = doNotWriteGenotypes;
			this.allowMissingFieldsInHeader = allowMissingFieldsInHeader;
			this.charset = Charset.forName("ISO-8859-1");
			this.writer = new OutputStreamWriter(lineBuffer, charset);
		}
        public void WriteMultipleData_OneFramePerWrite()
        {
            using (Stream transport = new QueueStream())
            using (WriteQueue queue = new WriteQueue(transport))
            {
                Task pumpTask = queue.PumpToStreamAsync();
                Stream output = new OutputStream(1, Framing.Priority.Pri1, queue);
                FrameReader reader = new FrameReader(transport, false, CancellationToken.None);

                int dataLength = 100;
                output.Write(new byte[dataLength], 0, dataLength);
                output.Write(new byte[dataLength * 2], 0, dataLength * 2);
                output.Write(new byte[dataLength * 3], 0, dataLength * 3);

                Frame frame = reader.ReadFrameAsync().Result;
                Assert.False(frame.IsControl);
                Assert.Equal(dataLength, frame.FrameLength);

                frame = reader.ReadFrameAsync().Result;
                Assert.False(frame.IsControl);
                Assert.Equal(dataLength * 2, frame.FrameLength);

                frame = reader.ReadFrameAsync().Result;
                Assert.False(frame.IsControl);
                Assert.Equal(dataLength * 3, frame.FrameLength);
            }
        }
        public void WriteMoreDataThanCredited_OnlyCreditedDataWritten()
        {
            using (Stream transport = new QueueStream())
            using (WriteQueue queue = new WriteQueue(transport))
            {
                Task pumpTask = queue.PumpToStreamAsync();
                OutputStream output = new OutputStream(1, Framing.Priority.Pri1, queue);
                FrameReader reader = new FrameReader(transport, false, CancellationToken.None);

                int dataLength = 0x1FFFF; // More than the 0x10000 default
                Task writeTask = output.WriteAsync(new byte[dataLength], 0, dataLength);
                Assert.False(writeTask.IsCompleted);

                Frame frame = reader.ReadFrameAsync().Result;
                Assert.False(frame.IsControl);
                Assert.Equal(0x10000, frame.FrameLength);

                Task<Frame> nextFrameTask = reader.ReadFrameAsync();
                Assert.False(nextFrameTask.IsCompleted);

                // Free up some space
                output.AddFlowControlCredit(10);

                frame = nextFrameTask.Result;
                Assert.False(frame.IsControl);
                Assert.Equal(10, frame.FrameLength);

                nextFrameTask = reader.ReadFrameAsync();
                Assert.False(nextFrameTask.IsCompleted);
            }
        }
Ejemplo n.º 6
0
 public override void Dispose()
 {
     mDecoder?.Dispose();
     mDecoder = null;
     mOutput?.Dispose();
     mOutput = null;
     mBuffer = null;
 }
Ejemplo n.º 7
0
        public void Init(IStreamHost host)
        {
            this.host = host;

            this.path = host.CreateParameter<string>("Path");

            this.to = host.CreateOutputStream<ImageStream>("Image Out");
        }
Ejemplo n.º 8
0
        public void Init(IStreamHost host)
        {
            this.host = host;
            this.testoutputstream = host.CreateOutputStream<DoubleStream>("Stream Out");
            this.to2 = host.CreateOutputStream<ImageStream>("Image Out");

            this.p1 = host.CreateParameter<double>("Param 1");
        }
Ejemplo n.º 9
0
        public Lzma2ArchiveDecoder(ImmutableArray<byte> settings, long length)
        {
            System.Diagnostics.Debug.Assert(!settings.IsDefault && settings.Length == 1 && length >= 0);

            mDecoder = new LZMA2.Decoder(new LZMA2.DecoderSettings(settings[0]));
            mOutput = new OutputStream(this);
            mBuffer = new byte[4 << 10]; // TODO: We shouldn't have to use a buffer here. Let the input stream submit directly into the decoder.
            mLength = length;
        }
Ejemplo n.º 10
0
        public void Init(IStreamHost host)
        {
            this.host = host;
            this.testinputstream = host.CreateInputStream<IBaseStream>("Stream In");
            this.testoutputstream = host.CreateOutputStream<IBaseStream>("Stream Out");

            this.p1 = host.CreateParameter<double>("Param 1");
            this.p2 = host.CreateParameter<double>("Param 2");

            this.testoutdata = host.CreateOutput<double>("Out 1");
        }
Ejemplo n.º 11
0
        public void Write(Action<Stream> output)
        {
            Action complete = () => { };
            var stream = new OutputStream((segment, continuation) =>
            {
                _response.BinaryWrite(segment);
                return true;
            }, complete);

            output(stream);
        }
Ejemplo n.º 12
0
 public static void CopyStream(Stream inputStream, OutputStream os)
 {
     int buffer_size = 1024;
     try {
         byte[] bytes = new byte[buffer_size];
         for (;;) {
             int count = inputStream.Read (bytes, 0, buffer_size);
             if (count <= 0)
                 break;
             os.Write (bytes, 0, count);
         }
     } catch (Exception ex) {
     }
 }
Ejemplo n.º 13
0
        public CopyArchiveDecoder(ImmutableArray<byte> settings, long length)
        {
            if (settings.IsDefault)
                throw new ArgumentNullException(nameof(settings));

            if (!settings.IsEmpty)
                throw new InvalidDataException();

            if (length < 0)
                throw new ArgumentOutOfRangeException(nameof(length));

            mOutput = new OutputStream(this);
            mLength = length;
        }
Ejemplo n.º 14
0
//JAVA TO C# CONVERTER WARNING: 'final' parameters are not allowed in .NET:
//ORIGINAL LINE: public static VariantContextWriter create(final java.io.File location, final java.io.OutputStream output, final net.sf.samtools.SAMSequenceDictionary refDict, final java.util.EnumSet<Options> options)
		public static VariantContextWriter create(File location, OutputStream output, SAMSequenceDictionary refDict, EnumSet<Options> options)
		{
//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final boolean enableBCF = isBCFOutput(location, options);
			bool enableBCF = isBCFOutput(location, options);

			if (enableBCF)
			{
				return new BCF2Writer(location, output, refDict, options.contains(Options.INDEX_ON_THE_FLY), options.contains(Options.DO_NOT_WRITE_GENOTYPES));
			}
			else
			{
				return new VCFWriter(location, output, refDict, options.contains(Options.INDEX_ON_THE_FLY), options.contains(Options.DO_NOT_WRITE_GENOTYPES), options.contains(Options.ALLOW_MISSING_FIELDS_IN_HEADER));
			}
		}
Ejemplo n.º 15
0
 /// <summary>
 ///
 /// </summary>
 public OutputStream getLocalizedOutputStream(OutputStream @out)
 {
     return(default(OutputStream));
 }
Ejemplo n.º 16
0
 protected virtual void writeImpl__(OutputStream os__)
 {
 }
        public override void ExecuteCmdlet()
        {
            CloudFileShare share;

            switch (this.ParameterSetName)
            {
            case Constants.ShareParameterSetName:
                share = this.Share;
                break;

            case Constants.ShareNameParameterSetName:
                share = this.BuildFileShareObjectFromName(this.Name);
                break;

            default:
                throw new PSArgumentException(string.Format(CultureInfo.InvariantCulture, "Invalid parameter set name: {0}", this.ParameterSetName));
            }

            if (ShouldProcess(share.Name, "Remove share"))
            {
                this.RunTask(async taskId =>
                {
                    if (share.IsSnapshot && IncludeAllSnapshot.IsPresent)
                    {
                        throw new PSArgumentException(string.Format(CultureInfo.InvariantCulture, "'IncludeAllSnapshot' should only be specified to delete a base share, and should not be specified to delete a Share snapshot: {0}", share.SnapshotQualifiedUri));
                    }

                    if (force || ShareIsEmpty(share) || ShouldContinue(string.Format("Remove share and all content in it: {0}", share.Name), ""))
                    {
                        DeleteShareSnapshotsOption deleteShareSnapshotsOption = DeleteShareSnapshotsOption.None;
                        bool retryDeleteSnapshot = false;

                        //Force means will delete the share anyway, so use 'IncludeSnapshots' to delete the share even has snapshot, or delete will fail when share has snapshot
                        // To delete a Share shapshot, must use 'None'
                        if (IncludeAllSnapshot.IsPresent)
                        {
                            deleteShareSnapshotsOption = DeleteShareSnapshotsOption.IncludeSnapshots;
                        }
                        else
                        {
                            retryDeleteSnapshot = true;
                        }

                        try
                        {
                            await this.Channel.DeleteShareAsync(share, deleteShareSnapshotsOption, null, this.RequestOptions, this.OperationContext, this.CmdletCancellationToken).ConfigureAwait(false);
                            retryDeleteSnapshot = false;
                        }
                        catch (StorageException e)
                        {
                            //If x-ms-delete-snapshots is not specified on the request and the share has associated snapshots, the File service returns status code 409 (Conflict).
                            if (!(e.IsConflictException() && retryDeleteSnapshot))
                            {
                                throw;
                            }
                        }

                        if (retryDeleteSnapshot)
                        {
                            if (force || await OutputStream.ConfirmAsync(string.Format("This share might have snapshots, remove the share and all snapshots?: {0}", share.Name)).ConfigureAwait(false))
                            {
                                deleteShareSnapshotsOption = DeleteShareSnapshotsOption.IncludeSnapshots;
                                await this.Channel.DeleteShareAsync(share, deleteShareSnapshotsOption, null, this.RequestOptions, this.OperationContext, this.CmdletCancellationToken).ConfigureAwait(false);
                            }
                            else
                            {
                                string result = string.Format("The remove operation of share '{0}' has been cancelled.", share.Name);
                                OutputStream.WriteVerbose(taskId, result);
                            }
                        }
                    }

                    if (this.PassThru)
                    {
                        this.OutputStream.WriteObject(taskId, share);
                    }
                });
            }
        }
        public void Write(string text)
        {
            var bytes = UTF8EncodingWithoutBom.GetBytes(text);

            OutputStream.Write(bytes, 0, bytes.Length);
        }
Ejemplo n.º 19
0
 public BufferedOutputStream(OutputStream arg0, int arg1)
     : base(ProxyCtor.I)
 {
     Instance.CallConstructor("(Ljava/io/OutputStream;I)V", arg0, arg1);
 }
Ejemplo n.º 20
0
//JAVA TO C# CONVERTER WARNING: 'final' parameters are not allowed in .NET:
//ORIGINAL LINE: public BCF2Writer(final File location, final OutputStream output, final net.sf.samtools.SAMSequenceDictionary refDict, final boolean enableOnTheFlyIndexing, final boolean doNotWriteGenotypes)
		public BCF2Writer(File location, OutputStream output, SAMSequenceDictionary refDict, bool enableOnTheFlyIndexing, bool doNotWriteGenotypes) : base(writerName(location, output), location, output, refDict, enableOnTheFlyIndexing)
		{
			this.outputStream = OutputStream;
			this.doNotWriteGenotypes = doNotWriteGenotypes;
		}
Ejemplo n.º 21
0
        /// <summary>
        /// Creates a new <code>JarOutputStream</code> with no manifest. </summary>
        /// <param name="out"> the actual output stream </param>
        /// <exception cref="IOException"> if an I/O error has occurred </exception>
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET:
//ORIGINAL LINE: public JarOutputStream(OutputStream out) throws IOException
        public JarOutputStream(OutputStream @out) : base(@out)
        {
        }
Ejemplo n.º 22
0
        // X:\jsc.svn\examples\javascript\android\com.abstractatech.dcimgalleryapp\com.abstractatech.dcimgalleryapp\ApplicationWebService.cs


        public bool compress(CompressFormat format, int quality, OutputStream stream)
        {
            return(default(bool));
        }
Ejemplo n.º 23
0
 public override void serializeBody(OutputStream stream)
 {
     base.serializeBody(stream);
     StreamingUtils.writeTLVector(this.exportCard, stream);
 }
Ejemplo n.º 24
0
 public override void serializeBody(OutputStream stream)
 {
     StreamingUtils.writeLong(base.id, stream);
     StreamingUtils.writeLong(base.accessHash, stream);
 }
Ejemplo n.º 25
0
 public override void serializeBody(OutputStream stream)
 {
     StreamingUtils.writeLong(this.session_id.longValue(), stream);
 }
Ejemplo n.º 26
0
        public void WriteCell(int columnIndex, ICell cell)
        {
            if (cell == null)
            {
                return;
            }
            string cellRef = new CellReference(RowNum, columnIndex).FormatAsString();

            WriteAsBytes(OutputStream, "<c r=\"" + cellRef + "\"");
            ICellStyle cellStyle = cell.CellStyle;

            if (cellStyle.Index != 0)
            {
                // need to convert the short to unsigned short as the indexes can be up to 64k
                // ideally we would use int for this index, but that would need changes to some more
                // APIs
                WriteAsBytes(OutputStream, " s=\"" + (cellStyle.Index & 0xffff) + "\"");
            }
            switch (cell.CellType)
            {
            case CellType.Blank:
            {
                WriteAsBytes(OutputStream, ">");
                break;
            }

            case CellType.Formula:
            {
                WriteAsBytes(OutputStream, ">");
                WriteAsBytes(OutputStream, "<f>");

                OutputQuotedString(cell.CellFormula);

                WriteAsBytes(OutputStream, "</f>");

                switch (cell.GetCachedFormulaResultTypeEnum())
                {
                case CellType.Numeric:
                    double nval = cell.NumericCellValue;
                    if (!Double.IsNaN(nval))
                    {
                        WriteAsBytes(OutputStream, "<v>" + nval + "</v>");
                    }
                    break;

                default:
                    break;
                }
                break;
            }

            case CellType.String:
            {
                if (_sharedStringSource != null)
                {
                    XSSFRichTextString rt = new XSSFRichTextString(cell.StringCellValue);
                    int sRef = _sharedStringSource.AddEntry(rt.GetCTRst());

                    WriteAsBytes(OutputStream, " t=\"" + ST_CellType.s + "\">");
                    WriteAsBytes(OutputStream, "<v>");
                    WriteAsBytes(OutputStream, sRef.ToString());
                    WriteAsBytes(OutputStream, "</v>");
                }
                else
                {
                    WriteAsBytes(OutputStream, " t=\"inlineStr\">");
                    WriteAsBytes(OutputStream, "<is><t");

                    if (HasLeadingTrailingSpaces(cell.StringCellValue))
                    {
                        WriteAsBytes(OutputStream, " xml:space=\"preserve\"");
                    }

                    WriteAsBytes(OutputStream, ">");

                    OutputQuotedString(cell.StringCellValue);

                    WriteAsBytes(OutputStream, "</t></is>");
                }
                break;
            }

            case CellType.Numeric:
            {
                WriteAsBytes(OutputStream, " t=\"n\">");
                WriteAsBytes(OutputStream, "<v>" + cell.NumericCellValue + "</v>");
                break;
            }

            case CellType.Boolean:
            {
                WriteAsBytes(OutputStream, " t=\"b\">");
                WriteAsBytes(OutputStream, "<v>" + (cell.BooleanCellValue ? "1" : "0") + "</v>");
                break;
            }

            case CellType.Error:
            {
                FormulaError error = FormulaError.ForInt(cell.ErrorCellValue);

                WriteAsBytes(OutputStream, " t=\"e\">");
                WriteAsBytes(OutputStream, "<v>" + error.String + "</v>");
                break;
            }

            default:
            {
                throw new InvalidOperationException("Invalid cell type: " + cell.CellType);
            }
            }
            WriteAsBytes(OutputStream, "</c>");
            OutputStream.Flush();
        }
Ejemplo n.º 27
0
 /// <summary>
 /// Returns a reference to the output stream.
 /// </summary>
 /// <returns>
 /// A <see cref="Stream"/> that contains a reference to the output stream.
 /// </returns>
 public Stream GetOutputStream() => new MemoryStream(OutputStream.AsByteArray());
 public OutputHandlerEventArgs(string line, OutputStream stream)
 {
     Line = line;
     OutputStream = stream;
 }
Ejemplo n.º 29
0
 public virtual void write__(OutputStream os__)
 {
     os__.startException(null);
     writeImpl__(os__);
     os__.endException();
 }
 /// <summary>Constructor with providing the output stream to decorate.</summary>
 /// <param name="out">an <code>OutputStream</code></param>
 internal CountOutputStream(OutputStream @out)
 {
     this.@out = @out;
 }
Ejemplo n.º 31
0
        static void SendNancyResponseToResult(Response response, ResultDelegate result)
        {
            if (!response.Headers.ContainsKey("Content-Type") && !string.IsNullOrWhiteSpace(response.ContentType))
                response.Headers["Content-Type"] = response.ContentType;

            result(
                string.Format("{0:000} UNK", (int) response.StatusCode),
                response.Headers,
                (next, error, complete) =>
                {
                    using (var stream = new OutputStream(next, complete))
                    {
                        try
                        {
                            response.Contents(stream);
                        }
                        catch (Exception ex)
                        {
                            error(ex);
                        }
                    }
                    return () => { };
                });
        }
Ejemplo n.º 32
0
        /// <summary>开始异步写操作</summary>
        /// <param name="buffer">缓冲区</param>
        /// <param name="offset">偏移</param>
        /// <param name="count">数量</param>
        /// <param name="callback"></param>
        /// <param name="state"></param>
        /// <returns></returns>
        public override IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback callback, object state)
        {
            CheckArgument(buffer, offset, count);

            return(OutputStream.BeginWrite(buffer, offset, count, callback, state));
        }
Ejemplo n.º 33
0
 public static void setOut0(Type system, OutputStream out0)
 {
     system.SetStatic("out", out0);
 }
Ejemplo n.º 34
0
 /// <summary>等待挂起的异步写完成</summary>
 /// <param name="asyncResult"></param>
 public override void EndWrite(IAsyncResult asyncResult)
 {
     OutputStream.EndWrite(asyncResult);
 }
        /// <summary>
        /// Stop copy operation by CloudBlob object
        /// </summary>
        /// <param name="blob">CloudBlob object</param>
        /// <param name="copyId">Copy id</param>
        private async Task StopCopyBlob(long taskId, IStorageBlobManagement localChannel, CloudBlob blob, string copyId, bool fetchCopyIdFromBlob = false)
        {
            ValidateBlobType(blob);

            AccessCondition    accessCondition    = null;
            BlobRequestOptions abortRequestOption = RequestOptions ?? new BlobRequestOptions();

            //Set no retry to resolve the 409 conflict exception
            abortRequestOption.RetryPolicy = new NoRetry();

            if (null == blob)
            {
                throw new ArgumentException(String.Format(Resources.ObjectCannotBeNull, typeof(CloudBlob).Name));
            }

            string specifiedCopyId = copyId;

            if (string.IsNullOrEmpty(specifiedCopyId) && fetchCopyIdFromBlob)
            {
                if (blob.CopyState != null)
                {
                    specifiedCopyId = blob.CopyState.CopyId;
                }
            }

            string abortCopyId = string.Empty;

            if (string.IsNullOrEmpty(specifiedCopyId) || Force)
            {
                //Make sure we use the correct copy id to abort
                //Use default retry policy for FetchBlobAttributes
                BlobRequestOptions options = RequestOptions;
                await localChannel.FetchBlobAttributesAsync(blob, accessCondition, options, OperationContext, CmdletCancellationToken).ConfigureAwait(false);

                if (blob.CopyState == null || String.IsNullOrEmpty(blob.CopyState.CopyId))
                {
                    ArgumentException e = new ArgumentException(String.Format(Resources.CopyTaskNotFound, blob.Name, blob.Container.Name));
                    OutputStream.WriteError(taskId, e);
                }
                else
                {
                    abortCopyId = blob.CopyState.CopyId;
                }

                if (!Force)
                {
                    string confirmation = String.Format(Resources.ConfirmAbortCopyOperation, blob.Name, blob.Container.Name, abortCopyId);
                    if (!await OutputStream.ConfirmAsync(confirmation).ConfigureAwait(false))
                    {
                        string cancelMessage = String.Format(Resources.StopCopyOperationCancelled, blob.Name, blob.Container.Name);
                        OutputStream.WriteVerbose(taskId, cancelMessage);
                    }
                }
            }
            else
            {
                abortCopyId = specifiedCopyId;
            }

            await localChannel.AbortCopyAsync(blob, abortCopyId, accessCondition, abortRequestOption, OperationContext, CmdletCancellationToken).ConfigureAwait(false);

            string message = String.Format(Resources.StopCopyBlobSuccessfully, blob.Name, blob.Container.Name);

            OutputStream.WriteObject(taskId, message);
        }
Ejemplo n.º 36
0
 /// <summary>刷新输出流写入的数据</summary>
 public override void Flush()
 {
     OutputStream.Flush();
 }
Ejemplo n.º 37
0
 public override void serializeBody(OutputStream stream)
 {
     StreamingUtils.writeTLString(this.text, stream);
 }
Ejemplo n.º 38
0
 /// <summary>设置输出流的长度</summary>
 /// <param name="value">数值</param>
 public override void SetLength(long value)
 {
     OutputStream.SetLength(value);
 }
Ejemplo n.º 39
0
		public void get(String src, OutputStream dst,
			SftpProgressMonitor monitor, int mode, long skip)
		{
			//throws SftpException{
			//try
			//{
				src=remoteAbsolutePath(src);
				Vector v=glob_remote(src);
				if(v.size()!=1)
				{
					throw new SftpException(SSH_FX_FAILURE, v.toString());
				}
				src=(String)(v.elementAt(0));

				if(monitor!=null)
				{
					SftpATTRS attr=_stat(src);
					monitor.init(SftpProgressMonitor.GET, src, "??", attr.getSize());
					if(mode==RESUME)
					{
						monitor.count(skip);
					}
				}
				_get(src, dst, monitor, mode, skip);
			//}
			//catch(Exception e)
			//{
			//	if(e is SftpException) throw (SftpException)e;
			//	throw new SftpException(SSH_FX_FAILURE, "");
			//}
		}
Ejemplo n.º 40
0
        /// <summary>把数据写入到输出流中</summary>
        /// <param name="buffer">缓冲区</param>
        /// <param name="offset">偏移</param>
        /// <param name="count">数量</param>
        public override void Write(byte[] buffer, int offset, int count)
        {
            CheckArgument(buffer, offset, count);

            OutputStream.Write(buffer, offset, count);
        }
Ejemplo n.º 41
0
        static int Main()
        {
            int row = 0;

            try
            {
                // Handle command line arguments
                Arguments args = new Arguments(Environment.CommandLine, true);
                bool      skipFirstRow;
                int       successes = 0, failures = 0;

                // First ordered argument is source CSV file name, it is required
                if (args.Count < RequiredArgumentCount)
                {
                    throw new ArgumentException($"Expected {RequiredArgumentCount:N0} argument, received {args.Count:N0}.");
                }

                // Check for switch based arguments
                if (!args.TryGetValue("sourceApp", out string sourceApp))   // Source GPA application, defaults to "SIEGate"
                {
                    sourceApp = DefaultSourceApp;
                }

                if (!args.TryGetValue("outputName", out string outputName)) // Target IEEE C37.118 output stream name, defaults to "IMPORTEDSTREAM"
                {
                    outputName = DefaultOutputName;
                }

                if (args.TryGetValue("skipFirstRow", out string setting))   // Setting to skip first row of import file, default to true
                {
                    skipFirstRow = setting.ParseBoolean();
                }
                else
                {
                    skipFirstRow = true;
                }

                // Make sure output name is upper case, this is an acronym for the output adapter in the target system
                outputName = outputName.ToUpperInvariant();

                // Make provided files name are relative to run path if not other path was provided
                string sourceFileName = FilePath.GetAbsolutePath(args["OrderedArg1"]);
                string configFile     = FilePath.GetAbsolutePath($"..\\{sourceApp}.exe.config");

#if DEBUG
                configFile = "C:\\Program Files\\openPDC\\openPDC.exe.config";
#endif

                // Fail if source config file does not exist
                if (!File.Exists(configFile))
                {
                    throw new FileNotFoundException($"Config file for {sourceApp} application \"{configFile}\" was not found.");
                }

                // Load needed database settings from target config file
                XDocument serviceConfig = XDocument.Load(configFile);

                nodeID = Guid.Parse(serviceConfig
                                    .Descendants("systemSettings")
                                    .SelectMany(systemSettings => systemSettings.Elements("add"))
                                    .Where(element => "NodeID".Equals((string)element.Attribute("name"), StringComparison.OrdinalIgnoreCase))
                                    .Select(element => (string)element.Attribute("value"))
                                    .FirstOrDefault());

                string connectionString = serviceConfig
                                          .Descendants("systemSettings")
                                          .SelectMany(systemSettings => systemSettings.Elements("add"))
                                          .Where(element => "ConnectionString".Equals((string)element.Attribute("name"), StringComparison.OrdinalIgnoreCase))
                                          .Select(element => (string)element.Attribute("value"))
                                          .FirstOrDefault();

                string dataProviderString = serviceConfig
                                            .Descendants("systemSettings")
                                            .SelectMany(systemSettings => systemSettings.Elements("add"))
                                            .Where(element => "DataProviderString".Equals((string)element.Attribute("name"), StringComparison.OrdinalIgnoreCase))
                                            .Select(element => (string)element.Attribute("value"))
                                            .FirstOrDefault();

                // Open database schema and input CSV file
                using (AdoDataConnection connection = new AdoDataConnection(connectionString, dataProviderString))
                    using (StreamReader reader = File.OpenText(sourceFileName))
                    {
                        // Configuration database tracks user changes for CIP reasons, use current user for ID
                        currentUserID = UserInfo.CurrentUserID ?? DefaultUserID;

                        // Setup database table operations for OutputStream table - this allows model, i.e., class instance representing record, based CRUD operations
                        TableOperations <OutputStream> outputStreamTable = new TableOperations <OutputStream>(connection);

                        // See if target output stream already exists
                        OutputStream outputStream = outputStreamTable.QueryRecordWhere("NodeID = {0} AND Acronym = {1}", nodeID, outputName);

                        if (outputStream == null)
                        {
                            // Setup a new output stream using default settings (user can adjust later as needed)
                            outputStream = new OutputStream
                            {
                                NodeID                        = nodeID,
                                Acronym                       = outputName,
                                Name                          = outputName,
                                ConnectionString              = "RoundToNearestTimestamp=True; addPhaseLabelSuffix=false;",
                                DataChannel                   = "port=-1; clients=localhost:4712; interface=0.0.0.0",
                                AutoPublishConfigFrame        = true,
                                AutoStartDataChannel          = true,
                                NominalFrequency              = 60,
                                FramesPerSecond               = 30,
                                LagTime                       = 5.0D,
                                LeadTime                      = 5.0D,
                                AllowSortsByArrival           = true,
                                TimeResolution                = 330000,
                                AllowPreemptivePublishing     = true,
                                PerformTimeReasonabilityCheck = true,
                                DownsamplingMethod            = "LastReceived",
                                DataFormat                    = "FloatingPoint",
                                CoordinateFormat              = "Polar",
                                CurrentScalingValue           = 2423,
                                VoltageScalingValue           = 2725785,
                                AnalogScalingValue            = 1373291,
                                DigitalMaskValue              = -65536,
                                Enabled                       = true,
                                CreatedOn                     = DateTime.UtcNow,
                                CreatedBy                     = currentUserID,
                                UpdatedOn                     = DateTime.UtcNow,
                                UpdatedBy                     = currentUserID
                            };

                            outputStreamTable.AddNewRecord(outputStream);
                            outputStream = outputStreamTable.QueryRecordWhere("NodeID = {0} AND Acronym = {1}", nodeID, outputName);

                            if (outputStream == null)
                            {
                                throw new InvalidOperationException($"Failed to lookup OutputStream record with Acronym of \"{outputName}\".");
                            }
                        }
                        else
                        {
                            // If record already exists, just track updates by user with timestamp
                            outputStream.UpdatedOn = DateTime.UtcNow;
                            outputStream.UpdatedBy = currentUserID;
                            outputStreamTable.UpdateRecord(outputStream);
                        }

                        // Setup database table operations for other needed tables
                        TableOperations <Device>                   deviceTable                   = new TableOperations <Device>(connection);
                        TableOperations <Measurement>              measurementTable              = new TableOperations <Measurement>(connection);
                        TableOperations <Phasor>                   phasorTable                   = new TableOperations <Phasor>(connection);
                        TableOperations <OutputStreamDevice>       outputStreamDeviceTable       = new TableOperations <OutputStreamDevice>(connection);
                        TableOperations <OutputStreamMeasurement>  outputStreamMeasurementTable  = new TableOperations <OutputStreamMeasurement>(connection);
                        TableOperations <OutputStreamDevicePhasor> outputStreamDevicePhasorTable = new TableOperations <OutputStreamDevicePhasor>(connection);

                        Device             device             = null;
                        OutputStreamDevice outputStreamDevice = null;

                        string line, lastDeviceName = null;
                        int    deviceIndex = 0, phasorIndex = 0;

                        // Loop through each line in CSV input file
                        while ((line = reader.ReadLine()) != null)
                        {
                            row++;

                            if (skipFirstRow)
                            {
                                skipFirstRow = false;
                                continue;
                            }

                            string[] columns = line.Split(',');

                            if (columns.Length < 6)
                            {
                                Console.WriteLine($"Not enough columns in CSV file at row {row} - expected 6, encountered {columns.Length}, skipped row.");
                                continue;
                            }

                            // Read columns of data from current row
                            string sourceDeviceName = columns[0].ToUpperInvariant().Trim();
                            string destDeviceName   = columns[1].ToUpperInvariant().Trim();
                            string sourcePhasorName = columns[2].ToUpperInvariant().Trim();
                            string destPhasorName   = columns[3].ToUpperInvariant().Trim();
                            ushort idCode           = ushort.Parse(columns[4].Trim());
                            string description      = columns[5].Trim();

                            if (!sourceDeviceName.Equals(lastDeviceName, StringComparison.InvariantCultureIgnoreCase))
                            {
                                lastDeviceName = sourceDeviceName;
                                deviceIndex++;
                                phasorIndex = 0;

                                // Lookup existing source device
                                device = deviceTable.QueryRecordWhere("Acronym = {0}", sourceDeviceName);

                                if (device == null)
                                {
                                    Console.WriteLine($"Failed to find source device \"{sourceDeviceName}\" - cannot create new output stream device for \"{destDeviceName}\".");
                                    failures++;
                                    continue;
                                }

                                Console.WriteLine($"Mapping source device \"{sourceDeviceName}\" to output stream device \"{destDeviceName}\"...");

                                // Setup a new output stream device
                                outputStreamDevice = outputStreamDeviceTable.QueryRecordWhere("NodeID = {0} AND AdapterID = {1} AND Acronym = {2}", nodeID, outputStream.ID, destDeviceName);

                                if (outputStreamDevice == null)
                                {
                                    outputStreamDevice = new OutputStreamDevice
                                    {
                                        NodeID    = nodeID,
                                        AdapterID = outputStream.ID,
                                        IDCode    = idCode > 0 ? idCode : deviceIndex,
                                        Acronym   = destDeviceName,
                                        Name      = destDeviceName.ToTitleCase(),
                                        Enabled   = true,
                                        CreatedOn = DateTime.UtcNow,
                                        CreatedBy = currentUserID,
                                        UpdatedOn = DateTime.UtcNow,
                                        UpdatedBy = currentUserID
                                    };

                                    outputStreamDeviceTable.AddNewRecord(outputStreamDevice);
                                    outputStreamDevice = outputStreamDeviceTable.QueryRecordWhere("NodeID = {0} AND AdapterID = {1} AND Acronym = {2}", nodeID, outputStream.ID, destDeviceName);

                                    if (outputStreamDevice == null)
                                    {
                                        throw new InvalidOperationException($"Failed to lookup OutputStreamDevice record with Acronym of \"{destDeviceName}\".");
                                    }
                                }
                                else
                                {
                                    // TODO: Could augment existing record, current logic just skips existing to account for possible input file errors
                                    outputStreamDevice.IDCode    = idCode > 0 ? idCode : deviceIndex;
                                    outputStreamDevice.UpdatedOn = DateTime.UtcNow;
                                    outputStreamDevice.UpdatedBy = currentUserID;
                                    outputStreamDeviceTable.UpdateRecord(outputStreamDevice);
                                }

                                // Validate base output stream measurements exist
                                foreach (string signalType in new[] { "SF", "FQ", "DF" }) // Status flags, frequency and dF/dT (delta frequency over delta time, i.e., rate of change of frequency)
                                {
                                    AddOutputStreamMeasurement(measurementTable, outputStreamMeasurementTable, outputStream.ID, $"{device.Acronym}-{signalType}", $"{destDeviceName}-{signalType}");
                                }
                            }

                            if (device == null)
                            {
                                failures++;
                                continue;
                            }

                            //                  123456789012345678901234567890
                            Console.WriteLine($"    Adding phasors for \"{$"{destPhasorName} - {description}".TrimWithEllipsisEnd(70)}\"");

                            // Lookup existing device phasor record
                            Phasor phasor = phasorTable.QueryRecordWhere("DeviceID = {0} AND Label = {1}", device.ID, sourcePhasorName);
                            phasorIndex++;

                            if (phasor == null)
                            {
                                Console.WriteLine($"Failed to lookup Phasor record with Label of \"{sourcePhasorName}\"");
                                failures++;
                            }
                            else
                            {
                                // Setup a new output stream device phasor
                                OutputStreamDevicePhasor outputStreamDevicePhasor = outputStreamDevicePhasorTable.QueryRecordWhere("NodeID = {0} AND OutputStreamDeviceID = {1} AND Label = {2}", nodeID, outputStreamDevice.ID, destPhasorName);

                                if (outputStreamDevicePhasor == null)
                                {
                                    outputStreamDevicePhasor = new OutputStreamDevicePhasor
                                    {
                                        NodeID = nodeID,
                                        OutputStreamDeviceID = outputStreamDevice.ID,
                                        Label     = destPhasorName,
                                        Type      = phasor.Type,
                                        Phase     = phasor.Phase,
                                        LoadOrder = phasorIndex,
                                        CreatedOn = DateTime.UtcNow,
                                        CreatedBy = currentUserID,
                                        UpdatedOn = DateTime.UtcNow,
                                        UpdatedBy = currentUserID
                                    };

                                    outputStreamDevicePhasorTable.AddNewRecord(outputStreamDevicePhasor);
                                    outputStreamDevicePhasor = outputStreamDevicePhasorTable.QueryRecordWhere("NodeID = {0} AND OutputStreamDeviceID = {1} AND Label = {2}", nodeID, outputStreamDevice.ID, destPhasorName);

                                    if (outputStreamDevicePhasor == null)
                                    {
                                        throw new InvalidOperationException($"Failed to lookup OutputStreamDevicePhasor record with Label of \"{destPhasorName}\".");
                                    }
                                }
                                else
                                {
                                    // TODO: Could augment existing record, current logic just skips existing to account for possible input file errors
                                    outputStreamDevicePhasor.UpdatedOn = DateTime.UtcNow;
                                    outputStreamDevicePhasor.UpdatedBy = currentUserID;
                                    outputStreamDevicePhasorTable.UpdateRecord(outputStreamDevicePhasor);
                                }

                                // Define output stream phasor measurements
                                AddOutputStreamMeasurement(measurementTable, outputStreamMeasurementTable, outputStream.ID, $"{device.Acronym}-PA{phasor.SourceIndex}", $"{destDeviceName}-PA{phasorIndex}");
                                AddOutputStreamMeasurement(measurementTable, outputStreamMeasurementTable, outputStream.ID, $"{device.Acronym}-PM{phasor.SourceIndex}", $"{destDeviceName}-PM{phasorIndex}");

                                successes++;
                            }
                        }
                    }

                Console.WriteLine();
                Console.WriteLine($"{successes:N0} successful phasor imports.");
                Console.WriteLine($"{failures:N0} failed phasor imports.");

            #if DEBUG
                Console.ReadKey();
            #endif

                return(0);
            }
            catch (Exception ex)
            {
                Console.WriteLine();
                Console.WriteLine($"Import halted at row {row}!");
                Console.Error.WriteLine($"Load Exception: {ex.Message}");

                return(1);
            }
        }
Ejemplo n.º 42
0
 /// <param name="out">the stream to write line data</param>
 /// <returns>this instance</returns>
 public virtual NGit.Api.DiffCommand SetOutputStream(OutputStream @out)
 {
     this.@out = @out;
     return(this);
 }
 private static Task ReadLinesFromOutput(OutputStream outputStream, StreamReader stream, EventHandler<OutputHandlerEventArgs> handler)
 {
     return Task.Run(() =>
     {
         while (!stream.EndOfStream)
         {
             var line = stream.ReadLine();
             handler(null, new OutputHandlerEventArgs(line, outputStream));
         }
     });
 }
			public ConnectedThread(BluetoothChatService chatService, BluetoothSocket socket, string socketType)
			{
				Log.D(TAG, "create ConnectedThread: " + socketType);
			    this.chatService = chatService;
			    mmSocket = socket;
				InputStream tmpIn = null;
				OutputStream tmpOut = null;

				// Get the BluetoothSocket input and output streams
				try
				{
					tmpIn = socket.GetInputStream();
					tmpOut = socket.GetOutputStream();
				}
				catch (IOException e)
				{
					Log.E(TAG, "temp sockets not created", e);
				}

				mmInStream = tmpIn;
				mmOutStream = tmpOut;
			}
Ejemplo n.º 45
0
 public static void setErr0(Type system, OutputStream err0)
 {
     system.SetStatic("err", err0);
 }
Ejemplo n.º 46
0
 protected virtual void writeImpl__(OutputStream os__)
 {
     throw new MarshalException("class was not generated with stream support");
 }
Ejemplo n.º 47
0
 protected abstract void writeImpl__(OutputStream os__);
Ejemplo n.º 48
0
        public void Encode(OutputStream output, Indentation indenter)
        {
            var psout = new PrintStream(output);

            psout.PrintLine(indenter + "<StatusMessage>" + this._msg + "</StatusMessage>");
        }
Ejemplo n.º 49
0
 public FilterOutputStream(OutputStream arg0)
     : base(ProxyCtor.I)
 {
     Instance.CallConstructor("(Ljava/io/OutputStream;)V", arg0);
 }
Ejemplo n.º 50
0
 public override void serializeBody(OutputStream stream)
 {
     base.serializeBody(stream);
     StreamingUtils.writeInt(this.progress, stream);
 }
 public SimpleAsciiOutputStream(OutputStream os)
 {
     _os = os;
 }
Ejemplo n.º 52
0
 public override void write(OutputStream output)
 {
     output.write <int>(playerId);
 }
Ejemplo n.º 53
0
        internal static NetFxToWinRtStreamAdapter Create(Stream stream)
        {
            if (stream == null)
                throw new ArgumentNullException("stream");

            StreamReadOperationOptimization readOptimization = StreamReadOperationOptimization.AbstractStream;
            if (stream.CanRead)
                readOptimization = DetermineStreamReadOptimization(stream);

            NetFxToWinRtStreamAdapter adapter;

            if (stream.CanSeek)
                adapter = new RandomAccessStream(stream, readOptimization);

            else if (stream.CanRead && stream.CanWrite)
                adapter = new InputOutputStream(stream, readOptimization);

            else if (stream.CanRead)
                adapter = new InputStream(stream, readOptimization);

            else if (stream.CanWrite)
                adapter = new OutputStream(stream, readOptimization);

            else
                throw new ArgumentException(SR.Argument_NotSufficientCapabilitiesToConvertToWinRtStream);

            return adapter;
        }
 internal ParquetRowWriter(OutputStream outputStream, Column[] columns, WriteAction writeAction)
     : this(new ParquetFileWriter(outputStream, columns), writeAction)
 {
 }
Ejemplo n.º 55
0
 public override void Encode(OutputStream output, Indentation indenter)
 {
     throw new UnsupportedOperationException("Not supported yet.");
 }
 public void Flush()
 {
     OutputStream.Flush();
 }
Ejemplo n.º 57
0
 public virtual void write__(OutputStream os__)
 {
     os__.startObject(null);
     writeImpl__(os__);
     os__.endObject();
 }
Ejemplo n.º 58
0
 private void WriteFooter(uint crc, uint compressed, uint uncompressed)
 {
     OutputStream.Write(BitConverter.GetBytes(crc), 0, 4);
     OutputStream.Write(BitConverter.GetBytes(compressed), 0, 4);
     OutputStream.Write(BitConverter.GetBytes(uncompressed), 0, 4);
 }
Ejemplo n.º 59
0
        public Bcj2ArchiveDecoder(ImmutableArray<byte> settings, long length)
        {
            if (!settings.IsDefaultOrEmpty)
                throw new ArgumentException();

            mOutput = new OutputStream(this);
            mLength = length;
            mLimit = length;
        }
Ejemplo n.º 60
0
 public override void serializeBody(OutputStream stream)
 {
     StreamingUtils.writeLong(this.volumeId, stream);
     StreamingUtils.writeInt(this.localId, stream);
     StreamingUtils.writeLong(this.secret, stream);
 }