private void InitFirmata()
    {
      //USB\VID_2A03&PID_0043&REV_0001
      //create a serial connection
      //var devices = await UsbSerial.listAvailableDevicesAsync();
      //var devList = devices.ToList();

      serial = new UsbSerial("VID_2A03", "PID_0043");

      //construct the firmata client
      firmata = new UwpFirmata();
      firmata.FirmataConnectionReady += Firmata_FirmataConnectionReady;
      firmata.StringMessageReceived += Firmata_StringMessageReceived;

      //last, construct the RemoteWiring layer by passing in our Firmata layer.
      arduino = new RemoteDevice(firmata);
      arduino.DeviceReady += Arduino_DeviceReady;

      //if you create the firmata client yourself, don't forget to begin it!
      firmata.begin(serial);

      //you must always call 'begin' on your IStream object to connect.
      //these parameters do not matter for bluetooth, as they depend on the device. However, these are the best params to use for USB, so they are illustrated here
      serial.begin(57600, SerialConfig.SERIAL_8N1);

    }
 public void SetUp()
 {
     streamId = Guid.NewGuid().ToString();
     store = TestEventStore.Create();
     store.Populate(streamId);
     stream =  NEventStoreStream.ByAggregate(store, streamId);
 }
 private void Arduino_Disconnect()
 {
     arduinoConnected = false;
     arduinoConnection.end();
     arduinoConnection = null;
     arduino = null;
 }
        public void Setup()
        {
            StreamFactory sf = StreamFactory.Instance;
            
            dfs_str_val = sf.openValueDataStream<StrKey, StrValue>(new FqStreamID("99-2729", "A0", "TestRange"),
                                                                 new CallerInfo(null, "A0", "A0", 1),
                                                                 null,
                                                                 StreamFactory.StreamSecurityType.Plain,
                                                                 CompressionType.None,
                                                                 StreamFactory.StreamOp.Write);
            keys = new List<IKey>();
            for (int i = 0; i < 10; i++) 
            {
                keys.Add(new StrKey("k" + i));
                for (int j = 0; j < 100; j++)
                {
                    dfs_str_val.Append(keys[i], new StrValue("k" + i + "_value" + j));
                }
      //          dfs_str_val.Seal(null);
            }

        //    IEnumerable<IDataItem> iterator = dfs_str_val.GetAll(new StrKey("k0"));
       //     foreach (IDataItem data in iterator)
        //        Console.WriteLine("data is: " + data.GetTimestamp());

        }
Example #5
0
        //static public ImagePlus FromFile(
        //    string filename,
        //    bool useEmbeddedColorManagement 
        //)
        //{
        //}

        static public ImagePlus FromStream(
            IStream stream,
            bool useEmbeddedColorManagement
        )
        {
            return new ImagePlus(stream, useEmbeddedColorManagement);
        }
        private void btnConnect_Click(object sender, RoutedEventArgs e)
        {
            Helpers.OutputTextBox = txtMessages;
            Helpers.ShowMessage("About to Connect");

            // *** IMPORTANT ***
            // You need to add the VID and PID for your device.
            // I'll post screen shots of finding it on my blog
            // at http://MosesSoftware.com
            //
            // NOTE: The line below is, obviously, for a USB cnnected
            // device.  You can also use a BlueTooth.
            connection = new UsbSerial("VID_2341", "PID_0042");
            arduino = new RemoteDevice(connection);
            arduino.DeviceReady += OnDeviceReady;
            arduino.AnalogPinUpdated += OnAnalogPinUpdated;
            arduino.DeviceConnectionFailed += OnDeviceConnectionFailed;
            arduino.DeviceConnectionLost += OnDeviceConnectionLost;
            arduino.DigitalPinUpdated += OnDigitialPinUpdated;
            arduino.StringMessageReceived += OnStringMessageReceived;
            arduino.SysexMessageReceived += OnSysexMessageReceived;
            arduino.I2c.I2cReplyEvent += OnI2CReplyEvent;

            // *** IMPORTANT ***
            // Make sure the baud rate is the same as the one specified
            //  in the Firmata program uploaded to the arduino.
            connection.begin(57600, SerialConfig.SERIAL_8N1);
        }
Example #7
0
		/// <summary>
		///     Copies data between two locations in the same stream.
		///     The source and destination areas may overlap.
		/// </summary>
		/// <param name="stream">The stream to copy data in.</param>
		/// <param name="originalPos">The position of the block of data to copy.</param>
		/// <param name="targetPos">The position to copy the block to.</param>
		/// <param name="size">The number of bytes to copy.</param>
		public static void Copy(IStream stream, long originalPos, long targetPos, long size)
		{
			if (size == 0)
				return;
			if (size < 0)
				throw new ArgumentException("The size of the data to copy must be >= 0");

			const int BufferSize = 0x1000;
			var buffer = new byte[BufferSize];
			long remaining = size;
			while (remaining > 0)
			{
				var read = (int) Math.Min(BufferSize, remaining);

				if (targetPos > originalPos)
					stream.SeekTo(originalPos + remaining - read);
				else
					stream.SeekTo(originalPos + size - remaining);

				stream.ReadBlock(buffer, 0, read);

				if (targetPos > originalPos)
					stream.SeekTo(targetPos + remaining - read);
				else
					stream.SeekTo(targetPos + size - remaining);

				stream.WriteBlock(buffer, 0, read);
				remaining -= read;
			}
		}
Example #8
0
        private static void Write(IStream stream)
        {
            try
            {
                int i = 1;
                StrKey k1 = k1 = new StrKey("k1");
                while (true)
                {
                    stream.Append(k1, new ByteValue(StreamFactory.GetBytes("k1-value" + i)));
                    i++;

                    Console.WriteLine("Written "+i+" values");
                   if (i %10==0)
                        stream.Seal(false);


                    if (isWriting)
                        System.Threading.Thread.Sleep(1000);
                    else
                        break;
                }
            }
            catch(Exception e)
            {
                Console.WriteLine("Exception in write: "+e);
            }

        }
        public override void Start()
        {
            logger.Log("Started: {0} ", ToString());

            DummyService dummyService = new DummyService(logger, this);
            serviceHost = new SafeServiceHost(logger,typeof(IMatlabInterfaceContract), dummyService , this, Constants.AjaxSuffix, moduleInfo.BaseURL());
            serviceHost.Open();

            appServer = new WebFileServer(moduleInfo.BinaryDir(), moduleInfo.BaseURL(), logger);
            
 
            //........... instantiate the list of other ports that we are interested in
            accessibleDummyPorts = new List<VPort>();

            //..... get the list of current ports from the platform
            IList<VPort> allPortsList = GetAllPortsFromPlatform();

            if (allPortsList != null)
                ProcessAllPortsList(allPortsList);

            this.receivedMessageList = new List<string>();
            this.receivedMessageListMatlab = new List<string>();
            

            // remoteSync flag can be set to true, if the Platform Settings has the Cloud storage
            // information i.e., DataStoreAccountName, DataStoreAccountKey values
            datastream = base.CreateValueDataStream<StrKey, StrValue>("test", false /* remoteSync */);

            worker = new SafeThread(delegate()
            {
                Work();
            }, "AppDummy-worker", logger);
            worker.Start();
        }
 void IStream.CopyTo(IStream pstm, long cb, IntPtr pcbRead, IntPtr pcbWritten)
 {
     var bytes = new byte[cb];
     Marshal.WriteInt64(pcbRead, this.stream.Read(bytes, 0, (int)cb));
     Marshal.WriteInt64(pcbWritten, cb);
     this.stream.Write(bytes, 0, (int)cb);
 }
        public void Setup()
        {
            StreamFactory sf = StreamFactory.Instance;
            DateTime Date = new DateTime(DateTime.UtcNow.Ticks);
            string HomeName = String.Format("TestHome-{0}", Date.ToString("yyyy-MM-dd"));
            string Caller = String.Format("{0}", Date.ToString("HH-mm-ss"));
            string AppName = Caller;
            Random rnd = new Random();
            string StreamName = String.Format("{0}", rnd.Next());

            FqStreamID fqstreamid = new FqStreamID(HomeName, AppName, StreamName);
            CallerInfo ci = new CallerInfo(null, Caller, Caller, 1);
            
            sf.deleteStream(fqstreamid, ci);
            
            vds = sf.openValueDataStream<StrKey, ByteValue>(fqstreamid, ci,
                                                                 null,
                                                                 StreamFactory.StreamSecurityType.Plain,
                                                                 CompressionType.None,
                                                                 StreamFactory.StreamOp.Write,
                                                                 mdserveraddress: "http://localhost:23456/MetadataServer");

            k1 = new StrKey("k1");
            k2 = new StrKey("k2");
        }
Example #12
0
        private static void Read(IStream stream)
        {
            try
            {
                StrKey k1 = k1 = new StrKey("k1");
                while (true)
                {
                    IEnumerable<IDataItem> dataitems= stream.GetAll(k1);

                    DateTime now = DateTime.Now;
                    int count =0;
                    foreach (IDataItem item in dataitems)
                    {
                        item.GetVal();
                        count++;
                    }
                    
                    Console.WriteLine("[" + now + "]" + "GetAll "+count+" values received.");

                    if (isReading)
                        System.Threading.Thread.Sleep(ReadFrequencySeconds * 1000);
                    else
                        break;
                }
            }
            catch (Exception e)
            {
                Console.WriteLine("Exception in read: " + e);
            }

        }
Example #13
0
        public void MarshalInterface(IStream pstm, ref Guid riid, IntPtr pv, uint dwDestContext, IntPtr pvDestContext, uint MSHLFLAGS)
        {
            uint written;
            byte[] data = ComUtils.CreateStandardMarshal(_binding);

            pstm.Write(data, (uint)data.Length, out written);
        }
Example #14
0
 /// <summary>
 /// Wraps a native IStream interface into a CLR Stream subclass.
 /// </summary>
 /// <param name="stream">
 /// The stream that this object wraps.
 /// </param>
 /// <remarks>
 /// Note that the parameter is passed by ref.  On successful creation it is
 /// zeroed out to the caller.  This object becomes responsible for the lifetime
 /// management of the wrapped IStream.
 /// </remarks>
 public ComStream(ref IStream stream)
 {
     Verify.IsNotNull(stream, "stream");
     _source = stream;
     // Zero out caller's reference to this.  The object now owns the memory.
     stream = null;
 }
 public void DirStreamTest_TestUpdateByteValue()
 {
     dds_byte_val = streamFactory.openFileDataStream<StrKey>(streamID, callerInfo, locationInfo, streamSecurityType, CompressionType.None, StreamFactory.StreamOp.Write);
     dds_byte_val.Update(k1, new ByteValue(StreamFactory.GetBytes("k1-cmu")));
     dds_byte_val.Update(k2, new ByteValue(StreamFactory.GetBytes("k2-msr")));
     dds_byte_val.Update(k1, new ByteValue(StreamFactory.GetBytes("k1-msr")));
 }
Example #16
0
        public bool RegisterStream(IStream stream)
        {
            if (StreamsByUniqueId.ContainsKey(stream.UniqueId))
            {
                Logger.FATAL("Stream with unique ID {0} already registered",stream.UniqueId);
                return false;
            }
            StreamsByUniqueId[stream.UniqueId] = stream;
            var protocol = stream.GetProtocol();
            if (protocol != null)
            {
                if (!StreamsByProtocolId.ContainsKey(protocol.Id))
                    StreamsByProtocolId[protocol.Id] = new Dictionary<uint, IStream>();
                StreamsByProtocolId[protocol.Id][stream.UniqueId] = stream;

            }
            if (!StreamsByType.ContainsKey(stream.Type))
            {
                StreamsByType[stream.Type] = new Dictionary<uint, IStream>();
            }
            StreamsByType[stream.Type][stream.UniqueId] = stream;
            if (!StreamsByName.ContainsKey(stream.Name))
            {
                StreamsByName[stream.Name] = new Dictionary<uint, IStream>();
            }
            StreamsByName[stream.Name][stream.UniqueId] = stream;
            Application.SignalStreamRegistered(stream);
            return true;
        }
Example #17
0
 /// <summary>
 /// Create a sequence from a stream.
 /// </summary>
 /// <param name="stream">The stream to sequence.</param>
 /// <returns>The persistent sequence.</returns>
 /// <remarks>Requires looking at the first element of the stream.  
 /// This is so that we know if the stream has any elements.  
 /// This is so because the sequence must have at least element or be null.</remarks>
 public static StreamSeq create(IStream stream)
 {
     object x = stream.next();
     return (RT.isEOS(x))
         ? null
         : new StreamSeq(x, stream);
 }
Example #18
0
        private int width = 7*24 ; // hours

        #endregion Fields

        #region Constructors

        public RowlandsAnalysis(string dataFilePath, int width)
        {
            this.width = width;
            this.dataFilePath = dataFilePath;
            count = 0 ;
            timestamp_energy_temperature = new List<Tuple<DateTime, double, double>>();

            File.Delete(".\\result-width-" + width + ".txt");

            StreamFactory streamFactory = StreamFactory.Instance;

            FqStreamID fq_sid = new FqStreamID("RowlandsAnalysis"+ width, "A", "TestBS");
            CallerInfo ci = new CallerInfo(null, "A", "A", 1);
            streamFactory.deleteStream(fq_sid, ci);
            dataStream = streamFactory.openFileStream<DoubleKey, ByteValue>(fq_sid, ci, null, StreamFactory.StreamSecurityType.Plain, CompressionType.None, StreamFactory.StreamOp.Write, null, 4*1024*1024, 1, new Logger());

            string line;
            System.IO.StreamReader file = new System.IO.StreamReader(dataFilePath);
            while ((line = file.ReadLine()) != null)
            {
                string[] words = line.Split(',');
                DateTime date = Convert.ToDateTime(words[0]);
                double energy = Double.Parse(words[1]);
                double temperature = Double.Parse(words[2]);
                timestamp_energy_temperature.Add(new Tuple<DateTime, double, double>(date, energy, temperature));
            }
            file.Close();
        }
Example #19
0
 /// <summary>
 /// Construct a <see cref="StreamSeq">StreamSeq</see> from metadata and first/rest.
 /// </summary>
 /// <param name="meta">The metadata to attach</param>
 /// <param name="first">The first item.</param>
 /// <param name="rest">The rest of the sequence.</param>
 StreamSeq(IPersistentMap meta, Object first, ISeq rest)
     : base(meta)
 {
     _first = first;
     _rest = rest;
     _stream = null;
 }
Example #20
0
        /// <summary>
        ///     Writes data to a reflexive, reallocating the original.
        /// </summary>
        /// <param name="entries">The entries to write.</param>
        /// <param name="oldCount">The old count.</param>
        /// <param name="oldAddress">The old address.</param>
        /// <param name="newCount">The number of entries to write.</param>
        /// <param name="layout">The layout of the data to write.</param>
        /// <param name="metaArea">The meta area of the cache file.</param>
        /// <param name="allocator">The cache file's meta allocator.</param>
        /// <param name="stream">The stream to manipulate.</param>
        /// <returns>The address of the new reflexive, or 0 if the entry list is empty and the reflexive was freed.</returns>
        public static uint WriteReflexive(IEnumerable<StructureValueCollection> entries, int oldCount, uint oldAddress,
			int newCount, StructureLayout layout, FileSegmentGroup metaArea, MetaAllocator allocator, IStream stream)
        {
            if (newCount == 0)
            {
                // Free the old reflexive and return
                if (oldCount > 0 && oldAddress != 0)
                    allocator.Free(oldAddress, oldCount*layout.Size);
                return 0;
            }

            uint newAddress = oldAddress;
            if (newCount != oldCount)
            {
                // Reallocate the reflexive
                int oldSize = oldCount*layout.Size;
                int newSize = newCount*layout.Size;
                if (oldCount > 0 && oldAddress != 0)
                    newAddress = allocator.Reallocate(oldAddress, oldSize, newSize, stream);
                else
                    newAddress = allocator.Allocate(newSize, stream);
            }

            // Write the new values
            WriteReflexive(entries.Take(newCount), newAddress, layout, metaArea, stream);
            return newAddress;
        }
 public static IStream GetDecorateAscii7Stream(IStream stream)
 {
     return new Ascii7Stream
                {
                    Stream = stream
                };
 }
Example #22
0
        public void LoadStreams(IStream leftStream, FileType leftFileType, byte[] leftData, IStream rightStream, FileType rightFileType, byte[] rightData)
        {
            _leftDetails.SelectDetails(leftStream, leftFileType);
            _rightDetails.SelectDetails(rightStream, rightFileType);

            _summary.Text = Labels.BinaryFileSummary;
        }
Example #23
0
        /// <summary>
        ///     Patches the file segments in a stream.
        /// </summary>
        /// <param name="changes">The changes to make to the segments and their data.</param>
        /// <param name="stream">The stream to write changes to.</param>
        public static void PatchSegments(IEnumerable<SegmentChange> changes, IStream stream)
        {
            // Sort changes by their offsets
            var changesByOffset = new SortedList<uint, SegmentChange>();
            foreach (SegmentChange change in changes)
                changesByOffset[change.OldOffset] = change;

            // Now adjust each segment
            foreach (SegmentChange change in changesByOffset.Values)
            {
                // Resize it if necessary
                if (change.NewSize != change.OldSize)
                {
                    if (change.ResizeAtEnd)
                        stream.SeekTo(change.NewOffset + change.OldSize);
                    else
                        stream.SeekTo(change.NewOffset);

                    StreamUtil.Insert(stream, change.NewSize - change.OldSize, 0);
                }

                // Patch its data
                DataPatcher.PatchData(change.DataChanges, change.NewOffset, stream);
            }
        }
Example #24
0
 public ImagePlus(
     IStream stream,
     bool useEmbeddedColorManagement
 )
 {
     NativeMethods.GdipLoadImageFromStream(stream, out nativeImage);
 }
Example #25
0
        /// <summary>
        ///     Allocates a free block of memory in the cache file's meta area.
        /// </summary>
        /// <param name="size">The size of the memory block to allocate.</param>
        /// <param name="align">The power of two to align the block to.</param>
        /// <param name="stream">The stream to write cache file changes to.</param>
        /// <returns></returns>
        public uint Allocate(int size, uint align, IStream stream)
        {
            // Find the smallest block that fits, or if nothing is found, expand the meta area
            FreeArea block = FindSmallestBlock(size, align);
            if (block == null)
                block = Expand(size, stream);

            if (block.Size == size)
            {
                // Perfect fit - just remove the block and we're done
                RemoveArea(block);
                return block.Address;
            }

            // Align the address
            uint oldAddress = block.Address;
            uint alignedAddress = (oldAddress + align - 1) & ~(align - 1);

            // Adjust the block's start address to free the data we're using
            ChangeStartAddress(block, (uint) (alignedAddress + size));

            // Add a block at the beginning if we had to align
            if (alignedAddress > oldAddress)
                Free(oldAddress, (int) (alignedAddress - oldAddress));

            return alignedAddress;
        }
        public ControlPageMaisto()
        {
            this.InitializeComponent();

            turn = Turn.none;
            direction = Direction.none;

            App.Telemetry.TrackPageView( "RC_Car_ControlPageMaisto" );

            accelerometer = App.Accelerometer;
            bluetooth = App.Bluetooth;
            arduino = App.Arduino;

            if( accelerometer == null || bluetooth == null || arduino == null )
            {
                Frame.Navigate( typeof( MainPage ) );
                return;
            }

            startButton.IsEnabled = true;
            stopButton.IsEnabled = true;
            disconnectButton.IsEnabled = true;

            bluetooth.ConnectionLost += Bluetooth_ConnectionLost;

            keepScreenOnRequest = new DisplayRequest();
            keepScreenOnRequest.RequestActive();

            App.Arduino.pinMode( FORWARD_CONTROL_PIN, PinMode.OUTPUT );
            App.Arduino.pinMode( REVERSE_CONTROL_PIN, PinMode.OUTPUT );
            App.Arduino.pinMode( LEFT_CONTROL_PIN, PinMode.OUTPUT );
            App.Arduino.pinMode( RIGHT_CONTROL_PIN, PinMode.OUTPUT );
        }
Example #27
0
 public void Write(IStream stream, object somethingToWrite, int level)
 {
     objectCounter.Add(somethingToWrite);
     stream.Write(string.Format("#{0} : {1}.", objectCounter.Count, somethingToWrite.GetType().Name));
     stream.WriteLine();
     foreach (var propertyInfo in somethingToWrite.GetType().GetProperties(DomainGenerator.FlattenHierarchyBindingFlag))
     {
         level.Times(() => stream.Write("    "));
         stream.Write(string.Format("{0} = ", propertyInfo.Name));
         if (primitivesWriter.IsMatch(propertyInfo.PropertyType))
         {
             primitivesWriter.Write(stream, propertyInfo.PropertyType, propertyInfo.GetValue(somethingToWrite, null));
             stream.WriteLine();
             continue;
         }
         //try
         //{
         //    var value = propertyInfo.GetValue(somethingToWrite, null);
         //    if (objectCounter.Contains(value))
         //    {
         //        stream.Write(string.Format("#{0} : {1}.", objectCounter.IndexOf(value) + 1, propertyInfo.PropertyType.Name));
         //        stream.WriteLine();
         //        continue;
         //    }
         //    Write(stream, value, ++level);
         //}
         //catch (Exception)
         //{
         //    stream.Write(string.Format("#dunno : {0}.", propertyInfo.PropertyType.Name));
         //    stream.WriteLine();
         //    continue;
         //}
     }
 }
        public void Return(IStream stream)
        {
            var fileSystemStream = stream as PooledFileSystemStream;
            if (fileSystemStream == null)
                throw new ArgumentException("The stream parameter does not contain a stream handled by this provider");

            fileSystemStream.Stream.Dispose();
        }
        public void Delete(IStream feedStream)
        {
            List<IStream> feedStreams = new List<IStream>();
            if (activityFeedStore.TryGetValue(feedStream.FeedId, out feedStreams) == false)
                activityFeedStore.TryAdd(feedStream.FeedId, feedStreams);

            feedStreams.Remove(feedStream);
        }
        //------------------------------------------------------
        //
        //  Constructors
        //
        //------------------------------------------------------
        /// <summary>
        /// Build a System.IO.Stream implementation around an IStream component.
        /// </summary>
        /// <remarks>
        /// The client code is entirely responsible for the lifespan of the stream,
        /// and there is no way it can tip us off for when to release it. Therefore,
        /// its reference count is not incremented. The risk of the client 
        /// releasing the IStream component before we're done with it is no worse than
        /// that of the client passing a pointer to garbage in the first place, and we
        /// cannot protect against that either. After all, the client is unmanaged and
        /// has endless possibilities of trashing the machine if she wishes to.
        /// </remarks>
        internal UnsafeIndexingFilterStream(IStream oleStream)
        {
            if (oleStream == null)
                throw new ArgumentNullException("oleStream");

            _oleStream = oleStream;
            _disposed = false;
        }
Example #31
0
 //LineString
 public static void NifStream(out LineString val, IStream s, NifInfo info) => val = new LineString
 {
     line = s.GetLine(Buf, 256)
 };
Example #32
0
 public int SaveState(IStream pIStream, LIB_PERSISTTYPE lptType)
 {
     return(VSConstants.S_OK);
 }
Example #33
0
 public void SaveScripts(ScriptTable scripts, IStream stream)
 {
     throw new NotImplementedException();
 }
Example #34
0
 //unsigned int
 public static void NifStream(out uint val, IStream s, NifInfo info) => val = ReadUInt(s);
Example #35
0
/*! NIFLIB_HIDDEN function.  For internal use only. */
        internal override void Read(IStream s, List <uint> link_stack, NifInfo info)
        {
            base.Read(s, link_stack, info);
            Nif.NifStream(out strength, s, info);
        }
Example #36
0
 //float
 public static void NifStream(out float val, IStream s, NifInfo info) => val = ReadFloat(s);
Example #37
0
 public ET_ObjectSequence(IStream element, int index, eTypeObjectCollection typeCollection, eTypeObjectStream type, object data = null)
     : base(element, index, typeCollection)
 {
     Type = eTypeObjectStream.Default;
 }
Example #38
0
 /*! NIFLIB_HIDDEN function.  For internal use only. */
 internal override void Read(IStream s, List <uint> link_stack, NifInfo info)
 {
     base.Read(s, link_stack, info);
 }
Example #39
0
 public void SaveChanges(IStream stream)
 {
     // TODO: Write the tag table
     _header.Checksum = ICacheFileExtensions.GenerateChecksum(this, stream);
     WriteHeader(stream);
 }
Example #40
0
 /// <summary>
 /// Gets a com pointer to the underlying <see cref="IStream"/> object.
 /// </summary>
 /// <param name="stream">The stream.</param>
 /// <returns>A Com pointer</returns>
 public static IntPtr ToIntPtr(IStream stream)
 {
     return(ComStreamShadow.ToIntPtr(stream));
 }
Example #41
0
 /// <summary>
 /// Copies a specified number of bytes from the current seek pointer in the stream to the current seek pointer in another stream.
 /// </summary>
 /// <param name="streamDest">The stream destination.</param>
 /// <param name="numberOfBytesToCopy">The number of bytes to copy.</param>
 /// <param name="bytesWritten">The bytes written.</param>
 /// <returns>The number of bytes read from this instance</returns>
 public long CopyTo(IStream streamDest, long numberOfBytesToCopy, out long bytesWritten)
 {
     CopyTo_(ToIntPtr(streamDest), numberOfBytesToCopy, out bytesWritten);
     return(bytesWritten);
 }
Example #42
0
 public void Write(IStream stream, object somethingToWrite)
 {
     Write(stream, somethingToWrite, 1);
 }
Example #43
0
        public void EncodeToStream(IWICComponentFactory factory, IWICBitmapSource data, Size imageSize, IStream outputStream)
        {
            //A list of COM objects to destroy
            List <object> com = new List <object>();

            try {
                //Find the GUID of the destination format
                Guid guidEncoder = GetOutputFormatWicGuid();

                //Find out the data's pixel format
                Guid pFormat = Guid.Empty;
                data.GetPixelFormat(out pFormat);

                //Create the encoder
                var encoder = factory.CreateEncoder(guidEncoder, null);
                com.Add(encoder);
                //And initialize it
                encoder.Initialize(outputStream, WICBitmapEncoderCacheOption.WICBitmapEncoderNoCache);

                // Create the output frame and property bag
                IWICBitmapFrameEncode outputFrame;
                var propertyBagArray = new IPropertyBag2[1];
                encoder.CreateNewFrame(out outputFrame, propertyBagArray); //An array is used instead of an out parameter... I have no idea why
                com.Add(outputFrame);
                //The property bag is a COM object...
                var propBag = propertyBagArray[0];
                com.Add(propBag);

                //Adjust encoder settings if it's a JPEG
                if (guidEncoder.Equals(Consts.GUID_ContainerFormatJpeg))
                {
                    //JPEG
                    //ImageQuality 0..1
                    //"JpegYCrCbSubsampling"  WICJpegYCrCbSubsamplingOption.

                    //Configure encoder settings (see http://msdn.microsoft.com/en-us/library/windows/desktop/ee719871(v=vs.85).aspx#encoderoptions)
                    var qualityOption = new PROPBAG2[1];
                    qualityOption[0].pstrName = "ImageQuality";

                    propBag.Write(1, qualityOption, new object[] { ((float)Math.Max(0, Math.Min(100, Quality))) / 100 });

                    WICJpegYCrCbSubsamplingOption subsampling = WICJpegYCrCbSubsamplingOption.WICJpegYCrCbSubsamplingDefault;
                    //411 NOT SUPPORTED BY WIC - only by freeimage
                    if ("420".Equals(Subsampling))
                    {
                        subsampling = WICJpegYCrCbSubsamplingOption.WICJpegYCrCbSubsampling420;
                    }
                    if ("422".Equals(Subsampling))
                    {
                        subsampling = WICJpegYCrCbSubsamplingOption.WICJpegYCrCbSubsampling422;
                    }
                    if ("444".Equals(Subsampling))
                    {
                        subsampling = WICJpegYCrCbSubsamplingOption.WICJpegYCrCbSubsampling444;
                    }

                    if (subsampling != WICJpegYCrCbSubsamplingOption.WICJpegYCrCbSubsamplingDefault)
                    {
                        var samplingOption = new PROPBAG2[1];
                        samplingOption[0].pstrName = "JpegYCrCbSubsampling";
                        samplingOption[0].vt       = VarEnum.VT_UI1;
                        propBag.Write(1, samplingOption, new object[] { (byte)subsampling });
                    }
                }
                //PNG interlace
                if (guidEncoder.Equals(Consts.GUID_ContainerFormatPng))
                {
                    var interlaceOption = new PROPBAG2[1];
                    interlaceOption[0].pstrName = "InterlaceOption";

                    propBag.Write(1, interlaceOption, new object[] { Interlace ?? false });
                }

                //Apply the property bag
                outputFrame.Initialize(propBag);


                //Convert the bitmap to the correct pixel format for encoding.

                //JPEG: encodes as GUID_WICPixelFormat24bppBGR or GUID_WICPixelFormat8bppGray.
                //If the original pixel format has an alpha channel, we need to specify a matte color.
                //UPDATE - IWICFormatConverter doesn't let you specify a matte color. Disabling code
                if (false && guidEncoder.Equals(Consts.GUID_ContainerFormatJpeg))
                {
                    ConversionUtils.HasAlphaAbility(pFormat);
                    var conv = factory.CreateFormatConverter();
                    com.Add(conv);
                    if (conv.CanConvert(pFormat, Consts.GUID_WICPixelFormat24bppBGR))
                    {
                        /*dither, pIPalette, alphaThresholdPercent, and paletteTranslate are used to mitigate color loss when
                         * converting to a reduced bit-depth format. For conversions that do not need these settings, the
                         * following parameters values should be used: dither set to WICBitmapDitherTypeNone, pIPalette set to NULL,
                         * alphaThresholdPercent set to 0.0f, and paletteTranslate set to WICBitmapPaletteTypeCustom.*/
                        conv.Initialize(data, Consts.GUID_WICPixelFormat24bppBGR, WICBitmapDitherType.WICBitmapDitherTypeNone, null, 0.0f, WICBitmapPaletteType.WICBitmapPaletteTypeCustom);
                        data = conv;
                        //Oops, we didn't do anything - there's no way to specify a matte color!
                    }
                }

                //GIF encodes as GUID_WICPixelFormat8bppIndexed
                //If the current format is > 8bpp, quantization may be required, and we may need to manually build the palette with Median Cut.

                //PNG encodes as EVERYTHING! Way too many formats supported.
                // If the user is specifying a colors setting, we need to
                // convert to GUID_WICPixelFormat8bppIndexed, GUID_WICPixelFormat4bppIndexed, GUID_WICPixelFormat2bppIndexed, or GUID_WICPixelFormat1bppIndexed

                if ((guidEncoder.Equals(Consts.GUID_ContainerFormatPng) && this.Colors != -1) || (guidEncoder.Equals(Consts.GUID_ContainerFormatGif)))
                {
                    Guid target = Consts.GUID_WICPixelFormat8bppIndexed;

                    int colors = this.Colors;

                    if (colors > 0 && guidEncoder.Equals(Consts.GUID_ContainerFormatPng))
                    {
                        if (colors <= 2)
                        {
                            target = Consts.GUID_WICPixelFormat1bppIndexed;
                        }
                        if (colors <= 4)
                        {
                            target = Consts.GUID_WICPixelFormat2bppIndexed;
                        }
                        if (colors <= 32)
                        {
                            target = Consts.GUID_WICPixelFormat4bppIndexed;
                        }
                    }
                    if (colors < 0)
                    {
                        colors = 256;
                    }
                    if (colors < 2)
                    {
                        colors = 2;
                    }
                    if (colors > 256)
                    {
                        colors = 256;
                    }

                    var conv = factory.CreateFormatConverter();
                    com.Add(conv);
                    if (conv.CanConvert(pFormat, target))
                    {
                        var palette = factory.CreatePalette();
                        com.Add(palette);
                        palette.InitializeFromBitmap(data, (uint)colors, true);

                        /*dither, pIPalette, alphaThresholdPercent, and paletteTranslate are used to mitigate color loss when
                         * converting to a reduced bit-depth format. For conversions that do not need these settings, the
                         * following parameters values should be used: dither set to WICBitmapDitherTypeNone, pIPalette set to NULL,
                         * alphaThresholdPercent set to 0.0f, and paletteTranslate set to WICBitmapPaletteTypeCustom.*/
                        conv.Initialize(data, target, this.Dither ? WICBitmapDitherType.WICBitmapDitherTypeErrorDiffusion :  WICBitmapDitherType.WICBitmapDitherTypeNone,
                                        palette, 50.0f, WICBitmapPaletteType.WICBitmapPaletteTypeCustom);
                        data = conv;
                    }
                }

                //Get size
                uint fw, fh;
                data.GetSize(out fw, out fh);

                //Set destination frame size
                outputFrame.SetSize(fw, fh);

                // Write the data to the output frame
                outputFrame.WriteSource(data, null);
                outputFrame.Commit();
                encoder.Commit();
            } finally {
                //Manually cleanup all the com reference counts, aggressively
                while (com.Count > 0)
                {
                    Marshal.ReleaseComObject(com[com.Count - 1]); //In reverse order, so no item is ever deleted out from under another.
                    com.RemoveAt(com.Count - 1);
                }
            }
        }
Example #44
0
 int IVsLibrary2.SaveState(IStream pIStream, LIB_PERSISTTYPE lptType)
 => VSConstants.E_NOTIMPL;
Example #45
0
 //Float2
 public static void NifStream(out Float2 val, IStream s, NifInfo info)
 {
     val         = new Float2();
     val.data[0] = ReadFloat(s);
     val.data[1] = ReadFloat(s);
 }
Example #46
0
 //bool
 public static void NifStream(out bool val, IStream s, NifInfo info) => val = ReadBool(s, info.version);
Example #47
0
 //string
 public static void NifStream(out string val, IStream s, NifInfo info) => val = ReadString(s);
Example #48
0
 //short
 public static void NifStream(out short val, IStream s, NifInfo info) => val = ReadShort(s);
Example #49
0
 /// <summary>
 /// Initializes a new instance of the <see cref="ComStream" /> class.
 /// </summary>
 /// <param name="comStream">The source COM stream.</param>
 public ComStream(IStream comStream)
 {
     //  Set the stream.
     this.comStream = comStream;
     bufferPointer  = Marshal.AllocCoTaskMem(8);
 }
Example #50
0
 public static IKeyedStream <TIn, TKey> ToExcelFile <TIn, TKey>(this IKeyedStream <TIn, TKey> stream, string name, IStream <Stream> resourceStream)
 {
     return(new ToExcelFileStreamNode <TIn, IKeyedStream <TIn, TKey> >(name, new ToExcelFileArgs <TIn, IKeyedStream <TIn, TKey> >
     {
         MainStream = stream,
         TargetStream = resourceStream
     }).Output);
 }
Example #51
0
 //byte
 public static void NifStream(out byte val, IStream s, NifInfo info) => val = ReadByte(s);
Example #52
0
 public void Clone(out IStream ppstm)
 {
     ppstm = null;
     HRESULT.STG_E_INVALIDFUNCTION.ThrowIfFailed("The method is not implemented.");
 }
        public bool Serialize(IStream Stream)
        {
            Stream.Serialize(ref Id);

            return(true);
        }
Example #54
0
        public void CreateOutput(IStream stream)
        {
            var filterchainOutput = FilterchainOutput.Create(this, stream);

            OutputList.Add(filterchainOutput);
        }
Example #55
0
 //Bools are stored as integers before version 4.1.0.1 and as bytes from 4.1.0.1 on
 public static bool ReadBool(IStream s, uint version) => version <= 0x04010001 ? ReadUInt(s) != 0 : ReadByte(s) != 0;
Example #56
0
        public void CreateInput(IStream stream)
        {
            var streamId = StreamIdentifier.Create(Owner.Owner.Owner.Id, Owner.Owner.Id, stream.Map);

            ReceiptList.Add(streamId);
        }
Example #57
0
 /// <summary>
 ///     Saves changes made to the string table.
 /// </summary>
 /// <param name="stream">The stream to manipulate.</param>
 public void SaveChanges(IStream stream)
 {
     SaveOffsets(stream);
     SaveData(stream);
 }
Example #58
0
 public static void NifStream <T>(out Key <T> key, IStream file, NifInfo info, int type) => NifStream(out key, file, info, (KeyType)type);
Example #59
0
 public int Initialize(object metadataImporter, string fileName, string searchPath, IStream stream)
 {
     return(UnversionedReader.Initialize(metadataImporter, fileName, searchPath, stream));
 }
Example #60
0
 public ET_ObjectSequence(IStream element, int index, eTypeObjectCollection typeCollection, string text)
     : base(element, index, typeCollection)
 {
     Value = new BooleanValue(true);
 }