Example #1
0
        /// <summary>
        /// Construct an StreamContent from a provided populated OFX object
        /// </summary>
        /// <param name="ofxObject">A populated OFX message with request or response data</param>
        /// <returns>Created StreamContent ready to send with HttpClient.Post</returns>
        public static StreamContent Create(Protocol.OFX ofxObject)
        {
            // Serialized data will be written to a MemoryStream
            var memoryStream = new System.IO.MemoryStream();

            // XMLWriter will be used to encode the data using UTF8Encoding without a Byte Order Marker (BOM)
            var xmlWriter = new System.Xml.XmlTextWriter(memoryStream, new System.Text.UTF8Encoding(false));

            // Write xml processing instruction
            xmlWriter.WriteStartDocument();
            // Our OFX protocol uses a version 2.0.0 header with 2.1.1 protocol body
            xmlWriter.WriteProcessingInstruction("OFX", "OFXHEADER=\"200\" VERSION=\"211\" SECURITY=\"NONE\" OLDFILEUID=\"NONE\" NEWFILEUID=\"NONE\"");

            // Don't include namespaces in the root element
            XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
            ns.Add("", "");

            // Generate XML to the stream
            m_serializer.Serialize(xmlWriter, ofxObject, ns);

            // Flush writer to stream
            xmlWriter.Flush();

            // Position the stream back to the start for reading
            memoryStream.Position = 0;

            // Wrap in our HttpContent-derived class to provide headers and other HTTP encoding information
            return new StreamContent(memoryStream);
        }
        public override void Update(Protocol.Types.Shortcut shortcut)
        {
            base.Update(shortcut);

            if (shortcut is ShortcutEmote)
                Emote = ObjectDataManager.Instance.Get<Emoticon>((shortcut as ShortcutEmote).emoteId);
        }
Example #3
0
		public void Process(string s)
		{
			// split protocol, separator and actual value
			int separatorIndex = s.IndexOf(SEPARATOR);

			if (separatorIndex != -1)
			{
				switch(s.Substring(0, separatorIndex))
				{
					case XML_RPC:
						m_type = Protocol.XmlRpc;
						break;
					case SOAP:
						m_type = Protocol.Soap;
						break;
					case REST:
						m_type = Protocol.Rest;
						break;
                    case UIML:
                        // uiml:// style location
                        m_type = Protocol.Local;
                        m_value = Uiml.Utils.Location.Transform(s);
                        break;
				}

                if (m_value == string.Empty) // only if not already assigned
				    m_value = s.Substring(separatorIndex + SEPARATOR.Length);
			}
			else
			{
				// no separator, thus it's local
				m_type = Protocol.Local;
				m_value = s; // value is the complete string
			}
		}
Example #4
0
        public static void OpenDocument(Protocol p, string url)
        {
            string cmd = "";

            url = url.Trim().ToLower();

            if ( url.Length > 0 ) {
                if ( p == Protocol.Email ) {
                    cmd += EmailProtocolPrefix;
                }
                else
                if ( p == Protocol.Http ) {
                    if ( !url.StartsWith( HttpProtocolPrefix ) ) {
                        cmd += HttpProtocolPrefix;
                    }
                }

                cmd += url;
                System.Diagnostics.Process.Start( cmd );
            } else {
                throw new ApplicationException( "Empty url" );
            }

            return;
        }
Example #5
0
        public MessageOut(Protocol id)
        {
            data=new MemoryStream();
            writer=new BinaryWriter(data);

            writer.Write((UInt16)id);
        }
Example #6
0
 private static ScanNetworkResult ScanEndpoint(CancellationToken userToken, DnsResolverBase resolver, Protocol protocol, IPEndpoint endpoint)
 {
     var status = Ping.PerformPing(endpoint, protocol);
     var hostName = status ? GetHostName(resolver, endpoint) : null;
     var result = new ScanNetworkResult(protocol, endpoint, hostName, status);
     return result;
 }
 public void RemoveRequest(Protocol.Request request)
 {
     lock(_requests)
     {
         _requests.Remove(request.Id);
     }
 }
 public void AddRequest(Protocol.Request request)
 {
     lock(_requests)
     {
         _requests.Add(request.Id, request);
     }
 }
 public CharacterInfomation(int myID, string myName, int myTextureID, Protocol.Type myType)
 {
     setID(myID);
     setName(myName);
     setTextureID(myTextureID);
     setType(myType);
 }
Example #10
0
        public HookProxy(Client client)
        {
            this.client = client;
            serverRecvMsg = new NetworkMessage(client);
            serverSendMsg = new NetworkMessage(client);
            clientRecvMsg = new NetworkMessage(client);
            clientSendMsg = new NetworkMessage(client);

            if (client.Dll.Pipe == null)
            {
                client.Dll.InitializePipe();
                client.Dll.PipeIsReady.WaitOne();
            }

            client.Dll.Pipe.OnSocketRecv += new Pipe.PipeListener(Pipe_OnSocketRecv);
            client.Dll.Pipe.OnSocketSend += new Pipe.PipeListener(Pipe_OnSocketSend);

            if (client.LoggedIn)
            {
                protocol = Protocol.World;
            }
            else
            {
                protocol = Protocol.None;
            }
        }
        public override void Update(Protocol.Types.Shortcut shortcut)
        {
            base.Update(shortcut);

            if (shortcut is ShortcutObjectPreset)
                PresetId = ( shortcut as ShortcutObjectPreset ).presetId;
        }
        public RcTransmitter(int pin, Protocol protocol, int repeat = defaultRepeatTransmit)
        {
            this.protocol = protocol;
            this.repeatTransmit = repeat;
            switch (protocol)
            {
                case Protocol.REV:
                    pulseLength = 360;
                    spiFrequency = 10000000;
                    break;
                case Protocol.HomeEasy:
                    pulseLength = 250;
                    spiFrequency = 10000000;
                    break;
                case Protocol.Intertechno:
                default:
                    pulseLength = 350;
                    spiFrequency = 10000000;
                    break;
            }

            if (pin == 0 && spiDevice == null)
            {
                spiDevice = InitSpi().Result;
            }
            else
            {
                gpioController = GpioController.GetDefault();
                gpioPin = gpioController.OpenPin(pin, GpioSharingMode.Exclusive);
                gpioPin.Write(GpioPinValue.Low);
                gpioPin.SetDriveMode(GpioPinDriveMode.Output);
            }
        }
        public void Test_Name()
        {
            Protocol protocol = new Protocol(new Procedure());
            ProtocolResolutionStep procedureStep = new ProtocolResolutionStep(protocol);

            Assert.AreEqual("Protocol Resolution", procedureStep.Name);
        }
Example #14
0
 public override bool ContainsLayer(Protocol layer)
 {
     if (layer == Protocol.UDP)
         return true;
     else
         return base.ContainsLayer(layer);
 }
Example #15
0
 public void SendMessageAll(Protocol.Message message)
 {
     foreach (KeyValuePair<IWebClient,IDevice> client in Clients)
     {
         client.Key.SendMessage(message);
     }
 }
Example #16
0
 public void Send(int msgno, MemoryStream stream)
 {
     Protocol protocol = new Protocol();
     protocol.msgno = msgno;
     protocol.stream = stream;
     mSendBuffer.PushBack(protocol);
 }
Example #17
0
 /// <summary>
 /// Create proper typed Account from OFX object
 /// </summary>
 /// <param name="ofxAccount">OFX BankAccount object</param>
 /// <returns></returns>
 public static new Account Create(Protocol.BankAccount ofxAccount)
 {
     // Route to proper constructor
     if (ofxAccount.ACCTTYPE == AccountEnum.SAVINGS)
         return new SavingsAccount(ofxAccount);
     return new CheckingAccount(ofxAccount);
 }
Example #18
0
 public static void createProtocol(TreeView tree)
 {
     TreeNodeCollection treeCol = tree.Nodes;
     Protocol prot = new Protocol(treeCol[0].Text, treeCol[0].ImageKey, treeCol[0].SelectedImageKey);
     Block data = null;
     foreach (TreeNode t in treeCol[0].Nodes)
     {
         if (t.Name.Equals("block"))
         {
             data = prot.createBlock(t.Text, t.ImageKey, t.SelectedImageKey);
             createProtocol(t.Nodes, data);
         }
         else
         {
             if(t.Name.Equals("multi"))
             {
             Field f = prot.createField(t.Text, t.Name,  "", t.SelectedImageKey);
             string[] values = t.ImageKey.Split(';');
             foreach(string s in values)
                 {
                     string[] pair = s.Split(':');
                     ((MultiField)f).addKey(pair[0], pair[1]);
                 }
            } else prot.createField(t.Text, t.Name, t.ImageKey, t.SelectedImageKey);
         }
     }
     createXML(prot);
 }
 public LoadBalancerProbe(Protocol protocol, string path, int? port)
 {
     //TODO: Validate params
     this.Protocol = protocol;
     this.Path = path;
     this.Port = port;
 }
Example #20
0
        public void Test_IsPreStep()
        {
            Protocol protocol = new Protocol();
            ConcreteProtocolProcedureStep procedureStep = new ConcreteProtocolProcedureStep(protocol);

            Assert.IsTrue(procedureStep.IsPreStep);
        }
 /// <summary>
 /// Constructs a FriendTreeNode
 /// </summary>
 /// <param name="protocol">Associated protocol</param>
 /// <param name="friend">Associated friend</param>
 public FriendTreeNode(Protocol protocol, Friend friend)
 {
     this.protocol = protocol;
     this.friend = friend;
     this.Tag = friend;
     this.Text = friend.DisplayName;
 }
Example #22
0
 public void Read (TProtocol iprot)
 {
   TField field;
   iprot.ReadStructBegin();
   while (true)
   {
     field = iprot.ReadFieldBegin();
     if (field.Type == TType.Stop) { 
       break;
     }
     switch (field.ID)
     {
       case 1:
         if (field.Type == TType.I32) {
           Pid = (Protocol)iprot.ReadI32();
         } else { 
           TProtocolUtil.Skip(iprot, field.Type);
         }
         break;
       default: 
         TProtocolUtil.Skip(iprot, field.Type);
         break;
     }
     iprot.ReadFieldEnd();
   }
   iprot.ReadStructEnd();
 }
Example #23
0
 public MessageSegment(IChannel connection, Protocol protocol, EndPoint ep, byte[] data)
 {
     Protocol = protocol;
     EndPoint = ep;
     Data = data;
     Connection = connection;
 }
Example #24
0
        public void CompatibleWithProtcolDifferentId()
        {
            var p1 = new Protocol (2, 2);
            var p2 = new Protocol (3, 2);

            Assert.IsFalse (p1.CompatibleWith (p2));
        }
Example #25
0
        public static bool CloseFirewallPort(Protocol p, int port)
        {
            NetworkInterface[] nics =
            NetworkInterface.GetAllNetworkInterfaces();
            try
            {
                //for each nic in computer...
                foreach (NetworkInterface nic in nics)
                {
                    if (nic.OperationalStatus != OperationalStatus.Up)
                        continue;

                    //send msg to each gateway configured on this nic
                    foreach (GatewayIPAddressInformation gwInfo in nic.GetIPProperties().GatewayAddresses)
                    {
                        string gateWayAddr = gwInfo.Address.ToString();
                        Console.Out.WriteLine("trying to close port forwarding {0}\tgateway address: {1}", port, gateWayAddr);
                        CloseFirewallPort(p, gwInfo.Address.ToString(), port);
                    }//each gateay
                }//each nic
            }//try
            catch (Exception x)
            {
                Console.Out.WriteLine(x);
                return false;
            }
            return true;
        }
        public void Test_CanApprove()
        {
            Procedure procedure = new Procedure();
            Protocol protocol = new Protocol(procedure);
            ProtocolAssignmentStep procedureStep = new ProtocolAssignmentStep(protocol);

            Assert.AreEqual(ProtocolStatus.PN, procedureStep.Protocol.Status);
            Assert.IsFalse(procedureStep.CanApprove);

            protocol.SubmitForApproval();

            Assert.AreEqual(ActivityStatus.SC, procedureStep.State);
            Assert.AreEqual(ProtocolStatus.AA, procedureStep.Protocol.Status);
            Assert.IsTrue(procedureStep.CanApprove);

            procedureStep.Start(new Staff());

            Assert.AreEqual(ActivityStatus.IP, procedureStep.State);
            Assert.AreEqual(ProtocolStatus.AA, procedureStep.Protocol.Status);
            Assert.IsTrue(procedureStep.CanApprove);

            procedureStep.Suspend();

            Assert.AreEqual(ActivityStatus.SU, procedureStep.State);
            Assert.AreEqual(ProtocolStatus.AA, procedureStep.Protocol.Status);
            Assert.IsFalse(procedureStep.CanApprove);

            procedureStep.Complete();

            Assert.AreEqual(ActivityStatus.CM, procedureStep.State);
            Assert.AreEqual(ProtocolStatus.AA, procedureStep.Protocol.Status);
            Assert.IsFalse(procedureStep.CanApprove);

            // TODO : test all other Protocol state conditions
        }
Example #27
0
 public void AddMessage(Protocol.IMessage message, Interfaces.IUserAgent user)
 {
     lock (this)
     {
         mQueue.Enqueue(new MessageToken { Message = message, UserAgent = user });
     }
 }
		/// <summary>
		/// Creates a new association of a given type at an OpenID Provider.
		/// </summary>
		/// <param name="protocol">The protocol.</param>
		/// <param name="associationType">Type of the association (i.e. HMAC-SHA1 or HMAC-SHA256)</param>
		/// <param name="associationUse">A value indicating whether the new association will be used privately by the Provider for "dumb mode" authentication
		/// or shared with the Relying Party for "smart mode" authentication.</param>
		/// <param name="associationStore">The Provider's association store.</param>
		/// <param name="securitySettings">The security settings of the Provider.</param>
		/// <returns>
		/// The newly created association.
		/// </returns>
		/// <remarks>
		/// The new association is NOT automatically put into an association store.  This must be done by the caller.
		/// </remarks>
		internal static HmacShaAssociation Create(Protocol protocol, string associationType, AssociationRelyingPartyType associationUse, IProviderAssociationStore associationStore, ProviderSecuritySettings securitySettings) {
			Requires.NotNull(protocol, "protocol");
			Requires.NotNullOrEmpty(associationType, "associationType");
			Requires.NotNull(associationStore, "associationStore");
			Requires.NotNull(securitySettings, "securitySettings");
			Contract.Ensures(Contract.Result<HmacShaAssociation>() != null);

			int secretLength = HmacShaAssociation.GetSecretLength(protocol, associationType);

			// Generate the secret that will be used for signing
			byte[] secret = MessagingUtilities.GetCryptoRandomData(secretLength);

			TimeSpan lifetime;
			if (associationUse == AssociationRelyingPartyType.Smart) {
				if (!securitySettings.AssociationLifetimes.TryGetValue(associationType, out lifetime)) {
					lifetime = DefaultMaximumLifetime;
				}
			} else {
				lifetime = HmacShaAssociation.DumbSecretLifetime;
			}

			string handle = associationStore.Serialize(secret, DateTime.UtcNow + lifetime, associationUse == AssociationRelyingPartyType.Dumb);

			Contract.Assert(protocol != null); // All the way up to the method call, the condition holds, yet we get a Requires failure next
			Contract.Assert(secret != null);
			Contract.Assert(!string.IsNullOrEmpty(associationType));
			var result = HmacShaAssociation.Create(protocol, associationType, handle, secret, lifetime);
			return result;
		}
Example #29
0
        public static bool OpenFirewallPort(string serviceName, Protocol p, int port)
        {
            NetworkInterface[] nics =
            NetworkInterface.GetAllNetworkInterfaces();
            try
            {
                //for each nic in computer...
                foreach (NetworkInterface nic in nics)
                {
                    if (nic.OperationalStatus != OperationalStatus.Up)
                         continue;

                    foreach (UnicastIPAddressInformation addrInfo in nic.GetIPProperties().UnicastAddresses)
                    {
                        if (addrInfo.Address.AddressFamily != AddressFamily.InterNetwork)
                            continue;
                        string machineIP = addrInfo.Address.ToString();
                        //send msg to each gateway configured on this nic
                        foreach (GatewayIPAddressInformation gwInfo in nic.GetIPProperties().GatewayAddresses)
                        {
                            string gateWayAddr = gwInfo.Address.ToString();
                            Console.Out.WriteLine("trying to add port forwarding {0} machineIP: {1}\tgateway address: {2}",port, machineIP,gateWayAddr);
                            OpenFirewallPort(serviceName,p ,machineIP, gwInfo.Address.ToString(), port);
                        }//each gateay
                    }//each ip
                }//each nic
            }//try
            catch(Exception x)
            {
                Console.Out.WriteLine(x);
                return false;
            }
            return true;
        }
        /// <summary>
        /// Constructs a ProtocolReporter
        /// </summary>
        /// <param name="protocol">Protocol to attach to</param>
        public ProtocolReporter(Protocol protocol)
        {
            this.protocol = protocol;
            this.debug = new Debug(protocol.Name);

            this.protocol.AddListener(this);
        }
Example #31
0
        public string GenerateProtocolText(Protocol protocol)
        {
            string result = "";

            result += string.Format("Valdybos, susirinkusios {0}\r\n\r\n            PROTOKOLAS\r\n", protocol.Date.ToShortDateString());
            result += "\r\n";
            User protocoller = protocol.Participants.Where(p => p.Role == "Protokolinikas").First().user;

            result += string.Format("Posėdžio pirmininkas: {0} {1}\r\n", protocoller.name, protocoller.surname);
            result += "\r\n";
            result += "Posėdžio dalyviai:\r\n";
            result += "\r\n";
            int i = 1;

            foreach (Participant participant in protocol.Participants)
            {
                if (participant.Role == "Dalyvis")
                {
                    string Role = "";
                    switch (participant.user.status)
                    {
                    case Status.Supervisor:
                        Role = "Valdybos narys";
                        break;

                    case Status.Member:
                        Role = "Narys";
                        break;

                    case Status.Newbie:
                        Role = "Naujas narys";
                        break;

                    case Status.Candidate:
                        Role = "Kandidatas";
                        break;
                    }
                    result += string.Format("   {0}. {1} {2} - {3}\r\n", i, participant.user.name, participant.user.surname, Role);
                }
                else if (participant.Role != "Protokolinikas")
                {
                    result += string.Format("   {0}. {1} {2} - {3}\r\n", i, participant.user.name, participant.user.surname, participant.Role);
                }
                i++;
            }
            result += "\r\n";
            result += protocol.Quorum ? "Kvorumas yra, sprendimai galiojantys.\r\n" : "Kvorumo nėra, sprendimai negaliojantys.\r\n";
            result += "\r\n";
            result += "KLAUSIMAI:\r\n";
            result += "\r\n";
            i       = 1;
            foreach (Question question in protocol.Questions)
            {
                result += i + ". " + question.Content + "\r\n";
                i++;
            }
            result += "\r\n";
            result += "SPRENDIMAI:\r\n";
            result += "\r\n";
            i       = 1;
            List <Solution> added   = protocol.Solutions.Where(s => s.Description.Equals("Pridėti nariai:")).ToList();
            List <Solution> removed = protocol.Solutions.Where(s => s.Description.Equals("Pašalinti nariai:")).ToList();
            List <Solution> changed = protocol.Solutions.Where(s => s.Description.Equals("Keistas nario statusas:")).ToList();
            List <Solution> rest    = protocol.Solutions.Where(s => !s.Description.Equals("Keistas nario statusas:") &&
                                                               !s.Description.Equals("Pridėti nariai:") && !s.Description.Equals("Pašalinti nariai:")).ToList();
            int j = 1;

            if (added.Count > 0)
            {
                result += i + ". " + "Pridėti nauji nariai į klubą:\r\n";
                result += "\r\n";
                foreach (Solution s in added)
                {
                    foreach (User u in s.affected_users)
                    {
                        result += "     " + i + "." + j + ". " + string.Format("{0} {1}\r\n", u.name, u.surname);
                        j++;
                    }
                }
                i++;
                result += "\r\n";
            }
            if (changed.Count > 0 || removed.Count > 0)
            {
                result += i + ". " + "Patvirtinti pokyčiai narių sąraše (ar pereikšti įspėjimai):\r\n";
                result += "\r\n";
                i++;
                j = 0;

                foreach (Solution s in changed)
                {
                    foreach (User u in s.affected_users)
                    {
                        result += "     " + i + "." + j + ". " + string.Format("{0} {1} - {2}\r\n", u.name, u.surname, Enum.GetName(typeof(Status), u.status));
                        j++;
                    }
                }
                foreach (Solution s in removed)
                {
                    foreach (User u in s.affected_users)
                    {
                        result += "     " + i + "." + j + ". " + string.Format("{0} {1} – pašalintas iš klubo veiklos\r\n", u.name, u.surname);
                        j++;
                    }
                }
                result += "\r\n";
            }
            foreach (Solution s in rest)
            {
                result += i + ". " + s.Description + "\r\n";
                result += "\r\n";
                if (s.affected_users != null)
                {
                    foreach (User u in s.affected_users)
                    {
                        result += "     " + string.Format("{0} {1}\r\n", u.name, u.surname);
                    }
                }
                i++;
            }
            return(result);
        }
Example #32
0
        public void Write(InboundItemInfo structs, Protocol oprot)
        {
            Validate(structs);
            oprot.WriteStructBegin();

            if (structs.GetVendor_code() != null)
            {
                oprot.WriteFieldBegin("vendor_code");
                oprot.WriteString(structs.GetVendor_code());

                oprot.WriteFieldEnd();
            }


            if (structs.GetWarehouse_code() != null)
            {
                oprot.WriteFieldBegin("warehouse_code");
                oprot.WriteString(structs.GetWarehouse_code());

                oprot.WriteFieldEnd();
            }


            if (structs.GetPo_no() != null)
            {
                oprot.WriteFieldBegin("po_no");
                oprot.WriteString(structs.GetPo_no());

                oprot.WriteFieldEnd();
            }


            if (structs.GetItem_code() != null)
            {
                oprot.WriteFieldBegin("item_code");
                oprot.WriteString(structs.GetItem_code());

                oprot.WriteFieldEnd();
            }


            if (structs.GetItem_name() != null)
            {
                oprot.WriteFieldBegin("item_name");
                oprot.WriteString(structs.GetItem_name());

                oprot.WriteFieldEnd();
            }


            if (structs.GetBrand_code() != null)
            {
                oprot.WriteFieldBegin("brand_code");
                oprot.WriteString(structs.GetBrand_code());

                oprot.WriteFieldEnd();
            }


            if (structs.GetBrand_name() != null)
            {
                oprot.WriteFieldBegin("brand_name");
                oprot.WriteString(structs.GetBrand_name());

                oprot.WriteFieldEnd();
            }


            if (structs.GetInbound_status() != null)
            {
                oprot.WriteFieldBegin("inbound_status");
                oprot.WriteString(structs.GetInbound_status());

                oprot.WriteFieldEnd();
            }


            if (structs.GetCreated_date() != null)
            {
                oprot.WriteFieldBegin("created_date");
                oprot.WriteString(structs.GetCreated_date());

                oprot.WriteFieldEnd();
            }


            if (structs.GetInbound_date() != null)
            {
                oprot.WriteFieldBegin("inbound_date");
                oprot.WriteString(structs.GetInbound_date());

                oprot.WriteFieldEnd();
            }


            if (structs.GetPoTotal_qty() != null)
            {
                oprot.WriteFieldBegin("poTotal_qty");
                oprot.WriteI32((int)structs.GetPoTotal_qty());

                oprot.WriteFieldEnd();
            }


            if (structs.GetCheck_qty() != null)
            {
                oprot.WriteFieldBegin("check_qty");
                oprot.WriteI32((int)structs.GetCheck_qty());

                oprot.WriteFieldEnd();
            }


            if (structs.GetDiff_qty() != null)
            {
                oprot.WriteFieldBegin("diff_qty");
                oprot.WriteI32((int)structs.GetDiff_qty());

                oprot.WriteFieldEnd();
            }


            if (structs.GetDefect_qty() != null)
            {
                oprot.WriteFieldBegin("defect_qty");
                oprot.WriteI32((int)structs.GetDefect_qty());

                oprot.WriteFieldEnd();
            }


            oprot.WriteFieldStop();
            oprot.WriteStructEnd();
        }
Example #33
0
        public void Read(InboundItemInfo structs, Protocol iprot)
        {
            String schemeStruct = iprot.ReadStructBegin();

            if (schemeStruct != null)
            {
                while (true)
                {
                    String schemeField = iprot.ReadFieldBegin();
                    if (schemeField == null)
                    {
                        break;
                    }
                    bool needSkip = true;


                    if ("vendor_code".Equals(schemeField.Trim()))
                    {
                        needSkip = false;
                        string value;
                        value = iprot.ReadString();

                        structs.SetVendor_code(value);
                    }



                    if ("warehouse_code".Equals(schemeField.Trim()))
                    {
                        needSkip = false;
                        string value;
                        value = iprot.ReadString();

                        structs.SetWarehouse_code(value);
                    }



                    if ("po_no".Equals(schemeField.Trim()))
                    {
                        needSkip = false;
                        string value;
                        value = iprot.ReadString();

                        structs.SetPo_no(value);
                    }



                    if ("item_code".Equals(schemeField.Trim()))
                    {
                        needSkip = false;
                        string value;
                        value = iprot.ReadString();

                        structs.SetItem_code(value);
                    }



                    if ("item_name".Equals(schemeField.Trim()))
                    {
                        needSkip = false;
                        string value;
                        value = iprot.ReadString();

                        structs.SetItem_name(value);
                    }



                    if ("brand_code".Equals(schemeField.Trim()))
                    {
                        needSkip = false;
                        string value;
                        value = iprot.ReadString();

                        structs.SetBrand_code(value);
                    }



                    if ("brand_name".Equals(schemeField.Trim()))
                    {
                        needSkip = false;
                        string value;
                        value = iprot.ReadString();

                        structs.SetBrand_name(value);
                    }



                    if ("inbound_status".Equals(schemeField.Trim()))
                    {
                        needSkip = false;
                        string value;
                        value = iprot.ReadString();

                        structs.SetInbound_status(value);
                    }



                    if ("created_date".Equals(schemeField.Trim()))
                    {
                        needSkip = false;
                        string value;
                        value = iprot.ReadString();

                        structs.SetCreated_date(value);
                    }



                    if ("inbound_date".Equals(schemeField.Trim()))
                    {
                        needSkip = false;
                        string value;
                        value = iprot.ReadString();

                        structs.SetInbound_date(value);
                    }



                    if ("poTotal_qty".Equals(schemeField.Trim()))
                    {
                        needSkip = false;
                        int?value;
                        value = iprot.ReadI32();

                        structs.SetPoTotal_qty(value);
                    }



                    if ("check_qty".Equals(schemeField.Trim()))
                    {
                        needSkip = false;
                        int?value;
                        value = iprot.ReadI32();

                        structs.SetCheck_qty(value);
                    }



                    if ("diff_qty".Equals(schemeField.Trim()))
                    {
                        needSkip = false;
                        int?value;
                        value = iprot.ReadI32();

                        structs.SetDiff_qty(value);
                    }



                    if ("defect_qty".Equals(schemeField.Trim()))
                    {
                        needSkip = false;
                        int?value;
                        value = iprot.ReadI32();

                        structs.SetDefect_qty(value);
                    }



                    if (needSkip)
                    {
                        ProtocolUtil.skip(iprot);
                    }

                    iprot.ReadFieldEnd();
                }

                iprot.ReadStructEnd();
                Validate(structs);
            }
            else
            {
                throw new OspException();
            }
        }
Example #34
0
        public void Read(Head structs, Protocol iprot)
        {
            String schemeStruct = iprot.ReadStructBegin();

            if (schemeStruct != null)
            {
                while (true)
                {
                    String schemeField = iprot.ReadFieldBegin();
                    if (schemeField == null)
                    {
                        break;
                    }
                    bool needSkip = true;


                    if ("responseTime".Equals(schemeField.Trim()))
                    {
                        needSkip = false;
                        string value;
                        value = iprot.ReadString();

                        structs.SetResponseTime(value);
                    }



                    if ("sysResponseCode".Equals(schemeField.Trim()))
                    {
                        needSkip = false;
                        string value;
                        value = iprot.ReadString();

                        structs.SetSysResponseCode(value);
                    }



                    if ("sysResponseMsg".Equals(schemeField.Trim()))
                    {
                        needSkip = false;
                        string value;
                        value = iprot.ReadString();

                        structs.SetSysResponseMsg(value);
                    }



                    if (needSkip)
                    {
                        ProtocolUtil.skip(iprot);
                    }

                    iprot.ReadFieldEnd();
                }

                iprot.ReadStructEnd();
                Validate(structs);
            }
            else
            {
                throw new OspException();
            }
        }
        public void Write(InvUpdateRetryRequest structs, Protocol oprot)
        {
            Validate(structs);
            oprot.WriteStructBegin();

            if (structs.GetTransId() != null)
            {
                oprot.WriteFieldBegin("transId");
                oprot.WriteString(structs.GetTransId());

                oprot.WriteFieldEnd();
            }

            else
            {
                throw new ArgumentException("transId can not be null!");
            }


            if (structs.GetBatchNo() != null)
            {
                oprot.WriteFieldBegin("batchNo");
                oprot.WriteString(structs.GetBatchNo());

                oprot.WriteFieldEnd();
            }

            else
            {
                throw new ArgumentException("batchNo can not be null!");
            }


            if (structs.GetVendorId() != null)
            {
                oprot.WriteFieldBegin("vendorId");
                oprot.WriteI32((int)structs.GetVendorId());

                oprot.WriteFieldEnd();
            }

            else
            {
                throw new ArgumentException("vendorId can not be null!");
            }


            if (structs.GetCooperationNo() != null)
            {
                oprot.WriteFieldBegin("cooperationNo");
                oprot.WriteI32((int)structs.GetCooperationNo());

                oprot.WriteFieldEnd();
            }

            else
            {
                throw new ArgumentException("cooperationNo can not be null!");
            }


            if (structs.GetWarehouse() != null)
            {
                oprot.WriteFieldBegin("warehouse");
                oprot.WriteString(structs.GetWarehouse());

                oprot.WriteFieldEnd();
            }

            else
            {
                throw new ArgumentException("warehouse can not be null!");
            }


            if (structs.GetBarcode() != null)
            {
                oprot.WriteFieldBegin("barcode");
                oprot.WriteString(structs.GetBarcode());

                oprot.WriteFieldEnd();
            }

            else
            {
                throw new ArgumentException("barcode can not be null!");
            }


            if (structs.GetVendorQuantity() != null)
            {
                oprot.WriteFieldBegin("vendorQuantity");
                oprot.WriteI32((int)structs.GetVendorQuantity());

                oprot.WriteFieldEnd();
            }

            else
            {
                throw new ArgumentException("vendorQuantity can not be null!");
            }


            if (structs.GetCartQuantity() != null)
            {
                oprot.WriteFieldBegin("cartQuantity");
                oprot.WriteI32((int)structs.GetCartQuantity());

                oprot.WriteFieldEnd();
            }

            else
            {
                throw new ArgumentException("cartQuantity can not be null!");
            }


            if (structs.GetUnpaidQuantity() != null)
            {
                oprot.WriteFieldBegin("unpaidQuantity");
                oprot.WriteI32((int)structs.GetUnpaidQuantity());

                oprot.WriteFieldEnd();
            }

            else
            {
                throw new ArgumentException("unpaidQuantity can not be null!");
            }


            if (structs.GetSellableQuantity() != null)
            {
                oprot.WriteFieldBegin("sellableQuantity");
                oprot.WriteI32((int)structs.GetSellableQuantity());

                oprot.WriteFieldEnd();
            }

            else
            {
                throw new ArgumentException("sellableQuantity can not be null!");
            }


            if (structs.GetIsPos() != null)
            {
                oprot.WriteFieldBegin("isPos");
                oprot.WriteI32((int)structs.GetIsPos());

                oprot.WriteFieldEnd();
            }

            else
            {
                throw new ArgumentException("isPos can not be null!");
            }


            if (structs.GetCreateTime() != null)
            {
                oprot.WriteFieldBegin("createTime");
                oprot.WriteI64((long)structs.GetCreateTime());

                oprot.WriteFieldEnd();
            }

            else
            {
                throw new ArgumentException("createTime can not be null!");
            }


            if (structs.GetRetryTimes() != null)
            {
                oprot.WriteFieldBegin("retryTimes");
                oprot.WriteI32((int)structs.GetRetryTimes());

                oprot.WriteFieldEnd();
            }

            else
            {
                throw new ArgumentException("retryTimes can not be null!");
            }


            if (structs.GetAreaWarehouseId() != null)
            {
                oprot.WriteFieldBegin("areaWarehouseId");
                oprot.WriteString(structs.GetAreaWarehouseId());

                oprot.WriteFieldEnd();
            }


            oprot.WriteFieldStop();
            oprot.WriteStructEnd();
        }
Example #36
0
        public IEnumerator RealTimeWithAuthCallback_WhenTokenExpired_ShouldRetry_WhenRetryFails_ShouldSetError([ValueSource(nameof(_protocols))] Protocol protocol)
        {
            return(UniTask.ToCoroutine(async() =>
            {
                // create a short lived token
                var authRestClient = await AblySandbox.GetRestClient(protocol);
                var token = await authRestClient.Auth.RequestTokenAsync(new TokenParams
                {
                    Ttl = TimeSpan.FromMilliseconds(1000),
                });

                bool didRetry = false;
                var realtimeClient = await AblySandbox.GetRealtimeClient(protocol, (options, _) =>
                {
                    options.TokenDetails = token;
                    options.AuthCallback = tokenParams =>
                    {
                        didRetry = true;
                        throw new Exception("AuthCallback failed");
                    };
                    options.AutoConnect = false;
                });

                var awaiter = new TaskCompletionAwaiter(5000);
                realtimeClient.Connection.Once(ConnectionEvent.Disconnected, state =>
                {
                    state.Reason.Code.Should().Be(ErrorCodes.ClientAuthProviderRequestFailed);
                    awaiter.SetCompleted();
                });

                await Task.Delay(2000);
                realtimeClient.Connect();

                var result = await awaiter.Task;
                result.Should().BeTrue();
                didRetry.Should().BeTrue();
            }));
        }
Example #37
0
 public UnsupportedProtocolException(string reason, Protocol bad, Protocol supported, Exception ex) : base(reason, ex)
 {
     Bad       = bad;
     Supported = supported;
 }
Example #38
0
        public IEnumerator Auth_WithRealtimeClient_WhenAuthFails_ShouldTransitionToOrRemainInTheCorrectState([ValueSource(nameof(_protocols))] Protocol protocol)
        {
            return(UniTask.ToCoroutine(async() =>
            {
                async Task TestConnectingBecomesDisconnected(string context, Action <ClientOptions, TestEnvironmentSettings> optionsAction)
                {
                    TaskCompletionAwaiter tca = new TaskCompletionAwaiter(5000);
                    var realtimeClient = await AblySandbox.GetRealtimeClient(protocol, optionsAction);
                    realtimeClient.Connection.On(ConnectionEvent.Disconnected, change =>
                    {
                        change.Previous.Should().Be(ConnectionState.Connecting);
                        change.Reason.Code.Should().Be(ErrorCodes.ClientAuthProviderRequestFailed);
                        tca.SetCompleted();
                    });

                    realtimeClient.Connection.Connect();
                    await realtimeClient.ProcessCommands();

                    (await tca.Task).Should().BeTrue(context);
                }

                // authUrl fails
                void AuthUrlOptions(ClientOptions options, TestEnvironmentSettings settings)
                {
                    options.AutoConnect = false;
                    options.AuthUrl = new Uri(_errorUrl);
                    options.RealtimeRequestTimeout = TimeSpan.FromSeconds(2);
                    options.HttpRequestTimeout = TimeSpan.FromSeconds(2);
                }

                // authCallback fails
                static void AuthCallbackOptions(ClientOptions options, TestEnvironmentSettings settings)
                {
                    options.AutoConnect = false;
                    options.AuthCallback = (tokenParams) => throw new Exception("AuthCallback force error");
                }
Example #39
0
        public IEnumerator RealTimeWithAuthUrl_WhenTokenExpired_And_WithServerTime_ShouldRenewToken([ValueSource(nameof(_protocols))] Protocol protocol)
        {
            return(UniTask.ToCoroutine(async() =>
            {
                var authRestClient = await AblySandbox.GetRestClient(protocol);
                var token = await authRestClient.Auth.RequestTokenAsync(new TokenParams
                {
                    Ttl = TimeSpan.FromMilliseconds(1000),
                });

                // this realtime client will have a key for the sandbox, thus a means to renew
                var mainClient = await AblySandbox.GetRestClient(protocol, options =>
                {
                    options.QueryTime = true;
                    options.TokenDetails = token;
                });

                await Task.Delay(2000);
                // This makes sure we get server time
                ((AblyAuth)mainClient.Auth).CreateTokenRequest();

                await mainClient.StatsAsync();
                ((AblyAuth)mainClient.Auth).CurrentToken.Should().NotBeSameAs(token);
            }));
        }
Example #40
0
        public IEnumerator RealTimeWithAuthUrl_WhenTokenExpired_ShouldRetry_WhenRetryFails_ShouldSetError([ValueSource(nameof(_protocols))] Protocol protocol)
        {
            return(UniTask.ToCoroutine(async() =>
            {
                var authRestClient = await AblySandbox.GetRestClient(protocol);
                var token = await authRestClient.Auth.RequestTokenAsync(new TokenParams
                {
                    Ttl = TimeSpan.FromMilliseconds(1000)
                });

                // this realtime client will have a key for the sandbox, thus a means to renew
                var realtimeClient = await AblySandbox.GetRealtimeClient(protocol, (options, _) =>
                {
                    options.TokenDetails = token;
                    options.AuthUrl = new Uri(_errorUrl);
                    options.AutoConnect = false;
                });

                var awaiter = new TaskCompletionAwaiter(5000);
                realtimeClient.Connection.Once(ConnectionEvent.Disconnected, state =>
                {
                    state.Reason.Code.Should().Be(ErrorCodes.ClientAuthProviderRequestFailed);
                    awaiter.SetCompleted();
                });

                await Task.Delay(2000);
                realtimeClient.Connect();

                var result = await awaiter.Task;
                result.Should().BeTrue();
            }));
        }
Example #41
0
        public ParticipationReportPage(Protocol protocol)
        {
            Title = protocol.Name;

            #if __IOS__
            string howToIncreaseScore = "You can increase your score by opening Sensus more often and responding to questions that Sensus asks you.";
            #elif __ANDROID__
            string howToIncreaseScore = "You can increase your score by allowing Sensus to run continuously and responding to questions that Sensus asks you.";
            #elif WINDOWS_PHONE
            string userNotificationMessage = null; // TODO:  How to increase score?
            #else
            #error "Unrecognized platform."
            #endif

            Button helpButton = null;
            if (!string.IsNullOrWhiteSpace(protocol.ContactEmail))
            {
                helpButton = new Button
                {
                    Text     = "Email Study Manager",
                    FontSize = 20
                };

                helpButton.Clicked += (o, e) =>
                {
                    UiBoundSensusServiceHelper.Get(true).SendEmailAsync(protocol.ContactEmail, "Help with study:  " + protocol.Name, "Hello - " + Environment.NewLine + Environment.NewLine + "I am having the following problem:" + Environment.NewLine + Environment.NewLine + "[DESCRIBE YOUR PROBLEM HERE]");
                };
            }

            StackLayout contentLayout = new StackLayout
            {
                Orientation     = StackOrientation.Vertical,
                VerticalOptions = LayoutOptions.FillAndExpand,
                Padding         = new Thickness(0, 50, 0, 0),
                Children        =
                {
                    new Label
                    {
                        Text              = "Participation Level",
                        FontSize          = 20,
                        HorizontalOptions = LayoutOptions.CenterAndExpand
                    },
                    new Label
                    {
                        Text              = Math.Round(protocol.OverallParticipationLevel * 100, 0) + "%",
                        FontSize          = 75,
                        HorizontalOptions = LayoutOptions.CenterAndExpand
                    },
                    new Label
                    {
                        Text              = "This score reflects your overall participation level in the \"" + protocol.Name + "\" study over the past " + (protocol.ParticipationHorizonDays == 1 ? "day" : protocol.ParticipationHorizonDays + " days") + ". " + howToIncreaseScore + (helpButton == null ? "" : " If you have questions, please click the button below to email the study manager."),
                        FontSize          = 20,
                        HorizontalOptions = LayoutOptions.CenterAndExpand
                    }
                }
            };

            if (helpButton != null)
            {
                contentLayout.Children.Add(helpButton);
            }

            Content = new ScrollView
            {
                Content = contentLayout
            };
        }
Example #42
0
        public IEnumerator RealtimeClient_ConnectedWithExpiringToken_WhenTokenExpired_ShouldNotRetryAndHaveError([ValueSource(nameof(_protocols))] Protocol protocol)
        {
            return(UniTask.ToCoroutine(async() =>
            {
                var helper = new RSA4Helper(this);

                // Create a token that is valid long enough for a successful connection to occur
                var authClient = await AblySandbox.GetRestClient(protocol);
                var almostExpiredToken = await authClient.AblyAuth.RequestTokenAsync(new TokenParams
                {
                    ClientId = "123",
                    Ttl = TimeSpan.FromMilliseconds(8000),
                });

                // get a realtime client with no Key, AuthUrl, or authCallback
                var realtimeClient =
                    await helper.GetRealTimeClientWithRequests(protocol, almostExpiredToken, invalidateKey: true);

                await realtimeClient.WaitForState(ConnectionState.Connected);

                // assert that there is no pre-existing error
                realtimeClient.Connection.ErrorReason.Should().BeNull();

                await realtimeClient.WaitForState(ConnectionState.Failed);
                realtimeClient.Connection.State.Should().Be(ConnectionState.Failed);

                realtimeClient.Connection.ErrorReason.Code.Should().Be(ErrorCodes.NoMeansProvidedToRenewAuthToken);
                helper.Requests.Count.Should().Be(0);
            }));
        }
Example #43
0
            public async Task ShouldSuccessfullyRemoveAChannelSubscriptionWithCustomFilter(Protocol protocol)
            {
                // Arrange
                var client = await GetRestClient(protocol, options => options.PushAdminFullWait = true);

                var device = GetTestLocalDevice(client);

                var savedDevice = await client.Push.Admin.DeviceRegistrations.SaveAsync(device);

                Func <Task> executeTest = async() =>
                {
                    var channelName = "pushenabled:test".AddRandomSuffix();
                    var channelSub  = PushChannelSubscription.ForDevice(channelName, savedDevice.Id);
                    var savedSub    = await client.Push.Admin.ChannelSubscriptions.SaveAsync(channelSub);

                    await client.Push.Admin.ChannelSubscriptions.RemoveWhereAsync(new Dictionary <string, string> {
                        { "channel", savedSub.Channel }, { "deviceId", savedSub.DeviceId }
                    });

                    var channelSubForClient = PushChannelSubscription.ForClientId(channelName, "123");
                    var clientSavedSub      = await client.Push.Admin.ChannelSubscriptions.SaveAsync(channelSubForClient);

                    await client.Push.Admin.ChannelSubscriptions.RemoveWhereAsync(new Dictionary <string, string> {
                        { "channel", clientSavedSub.Channel }, { "clientId", clientSavedSub.ClientId }
                    });

                    await client.Push.Admin.ChannelSubscriptions.RemoveWhereAsync(new Dictionary <string, string> {
                        { "channel", "not-existent" }, { "deviceId", "not-existent" }
                    });
                };

                await executeTest.Should().NotThrowAsync();
            }
Example #44
0
        public IEnumerator RealtimeWithAuthError_WhenTokenExpired_ShouldRetry_WhenRetryFails_ShouldSetError([ValueSource(nameof(_protocols))] Protocol protocol)
        {
            return(UniTask.ToCoroutine(async() =>
            {
                var helper = new RSA4Helper(this);

                var restClient = await AblySandbox.GetRestClient(protocol);
                var token = await restClient.Auth.AuthorizeAsync(new TokenParams
                {
                    Ttl = TimeSpan.FromMilliseconds(1000),
                });

                // this realtime client will have a key for the sandbox, thus a means to renew
                var realtimeClient = await AblySandbox.GetRealtimeClient(protocol, (options, _) =>
                {
                    options.TokenDetails = token;
                    options.AutoConnect = false;
                });

                realtimeClient.RestClient.ExecuteHttpRequest = helper.AblyResponseWith500Status;

                var awaiter = new TaskCompletionAwaiter(5000);

                realtimeClient.Connection.Once(ConnectionEvent.Disconnected, state =>
                {
                    state.Reason.Code.Should().Be(ErrorCodes.ClientAuthProviderRequestFailed);
                    awaiter.SetCompleted();
                });

                await Task.Delay(2000);
                realtimeClient.Connect();

                var result = await awaiter.Task;
                result.Should().BeTrue();
                helper.Requests.Count.Should().Be(1);
                helper.Requests[0].Url.EndsWith("requestToken").Should().BeTrue();
            }));
        }
Example #45
0
        public async Task WithExplicitClientIdNotMatchingClientIdInOptions_ReturnsMessageWithCorrectClientId(Protocol protocol)
        {
            var message = new Message("test", "test")
            {
                ClientId = "999"
            };
            var client = await GetRestClient(protocol, opts => opts.ClientId = "111");

            var channel = client.Channels.Get("test");

            _ = await Assert.ThrowsAsync <AblyException>(() => channel.PublishAsync(message));

            // Can publish further messages in the same channel
            await channel.PublishAsync("test", "test");
        }
Example #46
0
        public IEnumerator RealtimeClient_NewInstanceWithExpiredToken_ShouldNotRetryAndHaveError([ValueSource(nameof(_protocols))] Protocol protocol)
        {
            return(UniTask.ToCoroutine(async() =>
            {
                var helper = new RSA4Helper(this);
                var authClient = await AblySandbox.GetRestClient(protocol);
                var almostExpiredToken = await authClient.AblyAuth.RequestTokenAsync(new TokenParams
                {
                    ClientId = "123",
                    Ttl = TimeSpan.FromMilliseconds(1)
                });

                await Task.Delay(TimeSpan.FromMilliseconds(2));

                // Modify the expiry date to fool the client it has a valid token
                almostExpiredToken.Expires = DateTimeOffset.UtcNow.AddHours(1);

                // get a realtime client with no key
                var realtimeClient =
                    await helper.GetRealTimeClientWithRequests(protocol, almostExpiredToken, invalidateKey: true);

                bool connected = false;
                realtimeClient.Connection.Once(ConnectionEvent.Connected, (_) => { connected = true; });

                // assert that there is no pre-existing error
                realtimeClient.Connection.ErrorReason.Should().BeNull();

                await realtimeClient.WaitForState(ConnectionState.Failed);
                realtimeClient.Connection.State.Should().Be(ConnectionState.Failed);
                connected.Should().BeFalse();

                realtimeClient.Connection.ErrorReason.Code.Should().Be(ErrorCodes.NoMeansProvidedToRenewAuthToken);
                helper.Requests.Count.Should().Be(0);
            }));
        }
Example #47
0
            public async Task ShouldSuccessfullyDeleteDeviceRegistrationWithFilterByDeviceId(Protocol protocol)
            {
                // Arrange
                var client = await GetRestClient(protocol, options => options.PushAdminFullWait = true);

                var device = GetTestLocalDevice(client);

                Func <Task> callSaveAndDelete = async() =>
                {
                    await client.Push.Admin.DeviceRegistrations.SaveAsync(device);

                    await client.Push.Admin.DeviceRegistrations.RemoveWhereAsync(new Dictionary <string, string> {
                        { "deviceId", device.Id }
                    });
                };

                await callSaveAndDelete.Should().NotThrowAsync <AblyException>();
            }
Example #48
0
            public async Task ShouldSuccessfullyDeleteDeviceRegistrationWithOutMatchingFilter(Protocol protocol)
            {
                // Arrange
                var client = await GetRestClient(protocol, options => options.PushAdminFullWait = true);

                Func <Task> callRemoveWithNoFilter = async() =>
                {
                    await client.Push.Admin.DeviceRegistrations.RemoveWhereAsync(new Dictionary <string, string>() { { "deviceId", "test" } });
                };

                await callRemoveWithNoFilter.Should().NotThrowAsync <AblyException>();
            }
Example #49
0
 public PrivateMessage(Protocol protocol, ushort type)
     : base(protocol, type)
 {
 }
 /// <summary>
 /// Sets the Protocol property for this request.
 /// Specifies whether the pre signed URL will use
 /// http or https. Defaults to https unless otherwise
 /// set.
 /// </summary>
 /// <param name="protocol">The value that Protocol is set to</param>
 /// <returns>the response with the Protocol set</returns>
 public GetPreSignedUrlRequest WithProtocol(Protocol protocol)
 {
     this.protocol = protocol;
     return(this);
 }
Example #51
0
        public async Task WithExplicitClientIdMatchingClientIdInOptions_ReturnsMessageWithCorrectClientId(Protocol protocol)
        {
            var message = new Message("test", "test")
            {
                ClientId = "999"
            };
            var client = await GetRestClient(protocol, opts => opts.ClientId = "999");

            var channel = client.Channels.Get("persisted:test".AddRandomSuffix());
            await channel.PublishAsync(message);

            var result = await channel.HistoryAsync();

            result.Items.First().ClientId.Should().Be("999");
        }
Example #52
0
 public void Setup()
 {
     protocol = new Protocol(MockProtocol.Instance.id, MockProtocol.Instance.Version);
 }
Example #53
0
        public async Task SendingAVeryLargeMessage_ShouldThrowErrorToIndicateSendingFailed(Protocol protocol)
        {
            var message = new Message
            {
                Name = "large",
                Data = new string('a', 50 * 1024 * 8), // 100KB
            };
            var client = await GetRestClient(protocol);

            var channel = client.Channels.Get("large");

            _ = await Assert.ThrowsAsync <AblyException>(() => channel.PublishAsync(message));
        }
Example #54
0
        public async Task WithBasicAuthWhenMessageHasClientId_ShouldRetrieveMessageWithSameClientId(Protocol protocol)
        {
            var message = new Message("test", "test")
            {
                ClientId = "123"
            };
            var client = await GetRestClient(protocol);

            var channel = client.Channels.Get("persisted:test");
            await channel.PublishAsync(message);

            var result = await channel.HistoryAsync();

            result.Items.First().ClientId.Should().Be("123");
        }
        public void Read(SalesTimeRange structs, Protocol iprot)
        {
            String schemeStruct = iprot.ReadStructBegin();

            if (schemeStruct != null)
            {
                while (true)
                {
                    String schemeField = iprot.ReadFieldBegin();
                    if (schemeField == null)
                    {
                        break;
                    }
                    bool needSkip = true;


                    if ("sales_time_from_begin".Equals(schemeField.Trim()))
                    {
                        needSkip = false;
                        long?value;
                        value = iprot.ReadI64();

                        structs.SetSales_time_from_begin(value);
                    }



                    if ("sales_time_from_end".Equals(schemeField.Trim()))
                    {
                        needSkip = false;
                        long?value;
                        value = iprot.ReadI64();

                        structs.SetSales_time_from_end(value);
                    }



                    if ("sales_time_to_begin".Equals(schemeField.Trim()))
                    {
                        needSkip = false;
                        long?value;
                        value = iprot.ReadI64();

                        structs.SetSales_time_to_begin(value);
                    }



                    if ("sales_time_to_end".Equals(schemeField.Trim()))
                    {
                        needSkip = false;
                        long?value;
                        value = iprot.ReadI64();

                        structs.SetSales_time_to_end(value);
                    }



                    if (needSkip)
                    {
                        ProtocolUtil.skip(iprot);
                    }

                    iprot.ReadFieldEnd();
                }

                iprot.ReadStructEnd();
                Validate(structs);
            }
            else
            {
                throw new OspException();
            }
        }
Example #56
0
 public async Task IdempotentPublishing_LibraryGeneratesIds(Protocol protocol)
 {
        public void Read(SyncVrwIncrInvRequestPayload structs, Protocol iprot)
        {
            String schemeStruct = iprot.ReadStructBegin();

            if (schemeStruct != null)
            {
                while (true)
                {
                    String schemeField = iprot.ReadFieldBegin();
                    if (schemeField == null)
                    {
                        break;
                    }
                    bool needSkip = true;


                    if ("data_list".Equals(schemeField.Trim()))
                    {
                        needSkip = false;
                        List <com.vipshop.cis.sdk.api.datain.si.request.SyncVrwIncrInvRequestPayloadItem> value;

                        value = new List <com.vipshop.cis.sdk.api.datain.si.request.SyncVrwIncrInvRequestPayloadItem>();
                        iprot.ReadListBegin();
                        while (true)
                        {
                            try{
                                com.vipshop.cis.sdk.api.datain.si.request.SyncVrwIncrInvRequestPayloadItem elem1;

                                elem1 = new com.vipshop.cis.sdk.api.datain.si.request.SyncVrwIncrInvRequestPayloadItem();
                                com.vipshop.cis.sdk.api.datain.si.request.SyncVrwIncrInvRequestPayloadItemHelper.getInstance().Read(elem1, iprot);

                                value.Add(elem1);
                            }
                            catch (Exception e) {
                                break;
                            }
                        }

                        iprot.ReadListEnd();

                        structs.SetData_list(value);
                    }



                    if (needSkip)
                    {
                        ProtocolUtil.skip(iprot);
                    }

                    iprot.ReadFieldEnd();
                }

                iprot.ReadStructEnd();
                Validate(structs);
            }
            else
            {
                throw new OspException();
            }
        }
        public void Read(InvUpdateRetryRequest structs, Protocol iprot)
        {
            String schemeStruct = iprot.ReadStructBegin();

            if (schemeStruct != null)
            {
                while (true)
                {
                    String schemeField = iprot.ReadFieldBegin();
                    if (schemeField == null)
                    {
                        break;
                    }
                    bool needSkip = true;


                    if ("transId".Equals(schemeField.Trim()))
                    {
                        needSkip = false;
                        string value;
                        value = iprot.ReadString();

                        structs.SetTransId(value);
                    }



                    if ("batchNo".Equals(schemeField.Trim()))
                    {
                        needSkip = false;
                        string value;
                        value = iprot.ReadString();

                        structs.SetBatchNo(value);
                    }



                    if ("vendorId".Equals(schemeField.Trim()))
                    {
                        needSkip = false;
                        int value;
                        value = iprot.ReadI32();

                        structs.SetVendorId(value);
                    }



                    if ("cooperationNo".Equals(schemeField.Trim()))
                    {
                        needSkip = false;
                        int value;
                        value = iprot.ReadI32();

                        structs.SetCooperationNo(value);
                    }



                    if ("warehouse".Equals(schemeField.Trim()))
                    {
                        needSkip = false;
                        string value;
                        value = iprot.ReadString();

                        structs.SetWarehouse(value);
                    }



                    if ("barcode".Equals(schemeField.Trim()))
                    {
                        needSkip = false;
                        string value;
                        value = iprot.ReadString();

                        structs.SetBarcode(value);
                    }



                    if ("vendorQuantity".Equals(schemeField.Trim()))
                    {
                        needSkip = false;
                        int value;
                        value = iprot.ReadI32();

                        structs.SetVendorQuantity(value);
                    }



                    if ("cartQuantity".Equals(schemeField.Trim()))
                    {
                        needSkip = false;
                        int value;
                        value = iprot.ReadI32();

                        structs.SetCartQuantity(value);
                    }



                    if ("unpaidQuantity".Equals(schemeField.Trim()))
                    {
                        needSkip = false;
                        int value;
                        value = iprot.ReadI32();

                        structs.SetUnpaidQuantity(value);
                    }



                    if ("sellableQuantity".Equals(schemeField.Trim()))
                    {
                        needSkip = false;
                        int value;
                        value = iprot.ReadI32();

                        structs.SetSellableQuantity(value);
                    }



                    if ("isPos".Equals(schemeField.Trim()))
                    {
                        needSkip = false;
                        int value;
                        value = iprot.ReadI32();

                        structs.SetIsPos(value);
                    }



                    if ("createTime".Equals(schemeField.Trim()))
                    {
                        needSkip = false;
                        long value;
                        value = iprot.ReadI64();

                        structs.SetCreateTime(value);
                    }



                    if ("retryTimes".Equals(schemeField.Trim()))
                    {
                        needSkip = false;
                        int value;
                        value = iprot.ReadI32();

                        structs.SetRetryTimes(value);
                    }



                    if ("areaWarehouseId".Equals(schemeField.Trim()))
                    {
                        needSkip = false;
                        string value;
                        value = iprot.ReadString();

                        structs.SetAreaWarehouseId(value);
                    }



                    if (needSkip)
                    {
                        ProtocolUtil.skip(iprot);
                    }

                    iprot.ReadFieldEnd();
                }

                iprot.ReadStructEnd();
                Validate(structs);
            }
            else
            {
                throw new OspException();
            }
        }
Example #59
0
        public IEnumerator RealTimeWithAuthUrl_WhenTokenExpired_And_WithServerTime_And_NoWayToRenewToken_ShouldErrorBeforeCallingServer([ValueSource(nameof(_protocols))] Protocol protocol)
        {
            return(UniTask.ToCoroutine(async() =>
            {
                var authRestClient = await AblySandbox.GetRestClient(protocol);
                var token = await authRestClient.Auth.RequestTokenAsync(new TokenParams
                {
                    Ttl = TimeSpan.FromMilliseconds(1000),
                });

                // this realtime client will have a key for the sandbox, thus a means to renew
                var mainClient = await AblySandbox.GetRestClient(protocol, options =>
                {
                    options.Key = null;
                    options.QueryTime = true;
                    options.TokenDetails = token;
                });

                bool madeHttpCall = false;
                var previousExecuteRequest = mainClient.ExecuteHttpRequest;
                mainClient.ExecuteHttpRequest = request =>
                {
                    if (request.Url != "/time")
                    {
                        madeHttpCall = true;
                    }

                    return previousExecuteRequest(request);
                };
                await Task.Delay(2000);
                // This makes sure we get server time
                ((AblyAuth)mainClient.Auth).SetServerTime();

                var ex = await E7Assert.ThrowsAsync <AblyException>(mainClient.StatsAsync());
                ex.ErrorInfo.Should().BeSameAs(ErrorInfo.NonRenewableToken);
                madeHttpCall.Should().BeFalse();
            }));
        }
Example #60
0
        public async Task WithTokenId_WhenTryingToPublishToUnspecifiedChannel_ThrowsAblyException(Protocol protocol)
        {
            var capability = new Capability();

            capability.AddResource("foo").AllowPublish();

            var ably = await GetRestClient(protocol);

            var token = ably.Auth.RequestTokenAsync(CreateTokenParams(capability), null).Result;

            var tokenAbly = new AblyRest(new ClientOptions {
                Token = token.Token, Environment = "sandbox"
            });

            var error =
                await
                Assert.ThrowsAsync <AblyException>(() => tokenAbly.Channels.Get("boo").PublishAsync("test", "true"));

            error.ErrorInfo.Code.Should().Be(40160);
            error.ErrorInfo.StatusCode.Should().Be(HttpStatusCode.Unauthorized);
        }